Extending Your Command Tools
• Any C-program can be a command
• Unix Philosophy: [Eric Raymond's 17 Unix Rules]
• Do one thing and do it well
• Work well with others
• Handle text streams CLA Exit code
• Stick to conventions
• Read only from stdin stdin Command stdout
• Output only to stdout
• Errors only to stderr
• Use CLA to alter behavior
stderr
• Use exit status properly
35
Lecture 2: Programming Python
“Python is an experiment in how much freedom
programmers need. Too much freedom and
nobody can read another's code; too little and
expressiveness is endangered.”
- Guido van Rossum
Anoop M. Namboodiri
Benevolent Dictator for Life
IIIT Hyderabad (stepped down in 2018)
Why Python?
• Scripting Language
• Versatile
• Popular
• Simplicity
• Modules and Frameworks
• Data Visualization, Machine Learning, Cyber Security, Web
Servers,
• Extensive Online Documentation
• Community Support
Brief History of Python
• Invented in early 90s by Guido van Rossum
• Named after Monty Python (not the snake)
• Open sourced from the beginning
• A scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Highly Popular (Google, Meta, Uber, Dropbox, Amazon, Microsoft, ...)
• Consistently ranks #1 in indices like TIOBE and PYPL
[Link]
[Link]
Advantages of Python
• Easy to Learn and write error-free code
• You can start coding today
• Encourages and Insists Coherence (clean/readable code)
• Limited ways to do a specific task (unlike perl)
• Forces you to indent
• Language avoid unnecessary steps (declaration, semicolons)
• Powerful (batteries included)
• Provides an ever-growing number of powerful modules
• Provides flexibility
• You can extend the language with additional modules
• Can make hybrid systems
• Provides Speed
• Can compile to portable byte code
• Widely used
Uses of Python
• Shell tools
• System admin tools, Command line programs
• Text processing
• Rapid prototyping and development
• Integration of modules from different languages
• Graphical user interfaces
• Database access
• Distributed programming
• Internet scripting
What Gives?
• Slower than C; like any other scripting language
• Although efficient built-in algorithms and Data structures might
offset this
• Delayed error notification
• Lack of profiling tools
Installing Python
• Pre-installed on Unix systems (Linux, Mac OSX).
• Binaries available for Windows
• Latest stable versions are 3.13.11 and 3.14.2
• We will stick with 3.10 and might touch upon later versions
• Several editors and IDEs
• VIM / Emacs
• IDLE
• PyCharm
• VS Code
Python Interpreter
• Just type python on the command shell (or invoke IDLE)
• Python prompts with a ‘>>>’
>>> 5 + 4 * 3
17
>>> Ctrl+D
Running Programs on UNIX
1. Call python program via the python interpreter
% python [Link]
2. Make a python file directly executable by
• Adding the appropriate path to your python interpreter
as the first line of your script
#!/usr/bin/python
• Making the file executable
% chmod a+x [Link]
• Invoking file from Unix command line
% [Link]
Let us Jump Right In
#!/usr/bin/python
x : int = 34 - 23 # A comment
y : str = “Hello” # Another one
z : float = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concatenation
print(x)
print(y)
Understanding the Code
• Indentation matters to code meaning
• Block structure indicated by indentation; starts with a :
• First assignment to a variable creates it
• Variable types need not be declared, but do suggest them.
• Python figures out the object/variable types on its own.
• Assignment is = and comparison is ==
• For numbers, arithmetic operators are as in C
• Special use of + for string
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print
• Comments start with a #. Rest of the line is ignored
Let’s look at it again
#!/usr/bin/python
x : int = 34 - 23 # A comment
y : str = “Hello” # Another one
z : float = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concatenation
print(x)
print(y)
Variables in Python
• Variables are not declared; just assigned
• They are created the first time you use it
• Variables are references to objects
• Type info is with the object, not the reference
• Everything in Python is an object (even functions!!)
• The reference may change during execution
• When an object is no-longer referenced, it is deleted
automatically (garbage collection)
Variables: C vs. Python
int x = y = 12; x = y = 12
Name: x 0x3514
Name: x 0x3240
Type: int 0…00001100
Addr: 0x3240 Type: int
Addr: 0x3514
Ref_Count: 2
0
Name: y 0x3518 0…00001100
Name: y
Type: int 0…00001100 Addr: 0x3240
Addr: 0x3518
y = 13; y = 13 0x3240
Type: int
Name: x 0x3514 Ref_Count: 1
Name: x
Type: int 0…00001100
0…00001100 Addr: 0x3240
Addr: 0x3514
0x3284
Name: y 0x3518
Name: y Type: int
Type: int 0…00001101 Addr: 0x3284 Ref_Count: 1
Addr: 0x3518 0…00001101
Numbers are Immutable
Code What Happens
x = 2.5 • x 2.5
y=x •y
y = y+3
•x 2.5 y 5.5
print (x, y)
Output: 2.5 5.5
Numbers
• Integer: An unbounded integer value >>> 132224
• No long int since Python 3.x 132224
• No L suffix anymore. >>> 132323 ** 2
17509376329
• Float: Equiv. of 64-bit double precision in C >>> 3.1416
3.1416
• Type Convertion >> int(2.0)
• int(x) converts x to an integer 2
• float(x) converts x to a floating point >> float(2)
2.0
• type(var_name) gives the type
Arithmetic Operators
• Basic arithmetic operators are the same as in C
² + addition
² - subtraction (and unary negation)
² * multiplication
² / division
²% modulo division
² ( ) paranthesis
• ** indicates power operator: 3**2 is 9
• // floored quotient: 5 // 2.3 is 2.0
• Brackets -> Exponential -> Mult/Div -> Add/Sub
Arithmetic Expressions: Practice
•3+2*5-1 • 12
•3+2*5–1/2 • 12.5
• 3 + 2 * 5 – 1 / 2. • 12.5
*, //, and % all have the
• 3 + 2 * (5 – 1) / 2.0 • 7.0 SAME priority
When operators have the
same precedence, Python
•5+2*5%7 •8 evaluates them:
from left to right
• 3 + 2 * 5 ** 2 % 7 •4
• 3 + 2 * 5 // 2.8 • 6.0
Boolean Expressions
Things that are False
• The boolean value: False
• The numbers 0 (integer), 0.0 (float) and 0j (complex)
• The empty string ””
• The empty list [], empty dictionary {} and empty set set()
Things that are True
• The boolean value: True
• All non-zero numbers
• Any string containing at least one character
• A non-empty data structure
Boolean Expressions
• Any expression that has a truth value
• Comparison operators
• Result of a comparison of two objects is a boolean
• "<" , ">" , "==" , ">=" , "<=” , "!=” have evident meanings
• "is" ["not”]: true if both operands refer to the same object
• ["not"] "in”: checks collection membership (more later) 3python
in [1, 2, 3, 4 ]
returns
• Order of evaluation: Left to Right. true
• Comparison operators have lower precedence than Arithmetic
• Logical operators
• The results of logical operators on boolean is a boolean
• and, or, not : have evident meanings
• Order of evaluation: not, and, or
• Logical operators have lower precedence than comparisons
if: The Conditional Statement
if boolean-expression:
statements
elif boolean-expression:
statements
else:
statements
• elif stands for else if
• Evaluates the expressions one by one until one is found to
be true; then that set of statements (suite) is executed
(and no other part of the if statement is executed or
evaluated). If all expressions are false, the statements of
the else clause, if present, is executed.
if Statement: Examples
if num % 10 == 0:
print("Number is a multiple of 10”)
elif num % 2:
print("Number is odd”)
else:
print("Number is even”)
if a <= 5 and c >= 10 or d == “done” and b != 5:
print(“Right Conditions”)
If 8 <= Time <= 17:
print(“Working Time”)
01
Let us Code: if
• Write a code that prints if a number is divisible by 11 or not
if num % 11:
print(“num is not divisible by 11”)
else:
print(“num is divisible by 11”)
• Write a code that decides if a floating-point number, x, is in the
open interval (a,b)
if a < x < b:
print(“x is in the open interval ({a},{b})”)
else:
print(“x is outside (a,b)”)
Coding Practice: if
1. Given a circle (center, x and y, and radius r),
decide is a given point, (x1,y1) is within the
circle or not.
2. Write the code that decides if a number is an
integer, a complex number or a float
3. Given two integers, write a code that decides
if one is a factor of the other or not
Python Lists
The most versatile data structure
List: Most Versatile Sequence Type
• Creating list1 = [elt1,elt2, .., eltn]
• Element access using list1[ ], just as in strings
• Elements need not be of the same type. List is a general
form of arrays in c.
• Elements could in-turn be lists (multidimensional arrays)
• Like strings: Indexing, Slicing, Concatenation
• Elements can be added at the end using append or
anywhere using assignment/insert (mutable type)
• list1[3] = ‘abc’ or list1[2:2] = ‘abc’ (insertion)
• Deletion of an element: del list[3]
Methods Related to List
• String to List and Vice versa
• [Link](‘c’) : splits str at character c to a list
• [Link](lst): joins lst to string with c as delimiter
• [Link](obj):
• Returns lowest index of obj in lst (raises exception if
not found)
• [Link](obj):
• Counts number of times obj occurs in str
• [Link](index,obj): inserts obj at position index
• [Link](), [Link](), [Link](), [Link],
[Link](), [Link]()
• cmp(lst1,lst2), max(lst), min(lst), len(lst)
Let us Code: List
• Write the code for inserting a number, num,
into a sorted list, List1, at the correct position.
Assume sorting to be in ascending order.
pos = len(List1)-1
while pos >= 0 and List1[pos] > num:
pos -= 1
[Link](pos+1,num)
Coding Practice: List
1. Write the code for inserting a number, num,
into a sorted list, List1, at the correct position.
Assume sorting to be in descending order.
2. What if the sorting order is either ascending or
descending, and you are supposed to insert at
the correct position for both cases.
3. Carry out insertion sort using the above code.
4. Read the postal address from a user and find
the pincode: a 6-digit number in the last line.
Python Loops
for: The versatile loop
for: Looping through Collections
for target-list in expression-list:
statements
else:
statements
• The expression-list is evaluated once and should yeild
an iterable object (say list). The statements in the for
block is executed once for each item given by the
iterator (each item in the list) in the ascending order of
indices. When the items are exhausted (which might
even be when the expression-list is evaluated), the
statements in the else block (if present) are executed
and the loop terminates.
Let us Code: for
• Write a code that prints all primes up to n (n>=2)
n=123
primes = [2]
for p in range(3,n+1,2):
prm = True
for p1 in primes:
if p % p1 == 0:
prm = False
break;
if prm:
[Link](p)
print primes
Let us Code: for
• Write a code that prints all primes up to n (n>=2): Use ‘for else’
n=123
primes = [2]
for p in range(3,n+1,2):
for p1 in primes:
if p % p1 == 0:
break
else: # runs only if no break → prime
[Link](p)
print primes
Coding Practice: for
1. Write a program that, given an integer n, finds
three integers a, b and c, such that a+b+c = n
and a*b*c is maximum.