Python_Module1_Notes
Python_Module1_Notes
MODULE I
Python Fundamentals
Data types
Operators
Flow Control statements
Loop statements
Exception Handling in Python
After understanding the basics of few editors of Python, let us start our communication with Python,
by saying Hello World. The Python uses print() function for displaying the contents. Consider the
following code –
Here, after typing the first line of code and pressing the enter key, we could able to get the output
of that line immediately. Then the prompt (>>>) is returned on the screen. This indicates, Python
isready to take next instruction as input for processing.
Once we are done with the program, we can close or terminate Python by giving quit() command
asshown –
>>> quit() #Python terminates
30
Here, x, y and z are variables storing respective values. As each line of code above is processed
immediately after the line, the variables are storing the given values.
Observe that, though each line is treated independently, the knowledge (or information) gained in the
previous line will be retained by Python and hence, the further lines can make use of previously used
variables.
Thus, each line that we write at the Python prompt are logically related, though they look independent.
NOTE that, Python do not require variable declaration (unlike in C, C++, Java etc) before its use. One
can use any valid variable name for storing the values. Depending on the type (like number, string etc)
of the value being assigned, the type and behavior of the variable name is judged by Python.
After understanding some important concepts about programming and programming languages, we
will now move on to learn Python as a programming language with its syntax and constructs.
Values and Types
A value is one of the basic things a program works with.
It may be like 2, 10.5, “Hello” etc.
Each value in Python has a type. Type of 2 is integer; type of 10.5 is floating point number;
“Hello” is string etc.
The type of a value can be checked using type function as shown below –
>>> type("hello")
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>
In the above four examples, one can make out various types str, int and float.
Observe the 4th example – it clearly indicates that whatever enclosed within a double quote is a
string.
Variable Names and Keywords
It is a good programming practice to name the variable such that its name indicates its purpose in
the program.
Statements
A statement is a small unit of code that can be executed by the Python interpreter.
It indicates some action to be carried out.
In fact, a program is a sequence of such statements.
Two kinds of statements are: print being an expression statement and assignment statement
Following are the examples of statements –
>>> print("hello") #printing statement
hello
>>> x=5 #assignment statement
>>> print(x) #printing statement
5
Operators and Operands
Special symbols used to indicate specific tasks are called as operators.
An operator may work on single operand (unary operator) or two operands (binary operator).
There are several types of operators like arithmetic operators, relational operators, logical operators
etc. in Python.
Arithmetic Operators are used to perform basic operations as listed in Table:
NOTE:
1. Python has a special feature – one can assign values of different types to multiple variables in
a single statement.
For example,
>>> x, y, st=3, 4.2, "Hello"
>>> print("x= ", x, " y= ",y, " st= ", st)
x=3 y=4.2 st=Hello
2. Python supports bitwise operators like &(AND), | (OR), ~(NOT), ^(XOR), >>(right shift) and
<<(left shift). These operators will operate on every bit of the operands. Working procedure of
these operators is same as that in other languages like C and C++.
3. There are some special operators in Python viz. Identity operator (is and is not) and
membership operator (in and not in). These will be discussed in further Modules.
Expressions
A combination of values, variables and operators is known as expression.
Following are few examples of expression –
x=5
y=x+10
z= x-y*3
The Python interpreter evaluates simple expressions and gives results even without print().
For example,
>>> 5
5 #displayed as it is
>>> 1+2
3 #displayed the sum
But, such expressions do not have any impact when written into Python script file.
Order of Operations
When an expression contains more than one operator, the evaluation of operators depends on the
precedence of operators.
The Python operators follow the precedence rule (which can be remembered as PEMDAS) as given
below –
Parenthesis have the highest precedence in any expression. The operations within parenthesis
will be evaluated first. For example, in the expression (a+b)*c, theaddition has to be
done first and then the sum is multiplied with c.
Exponentiation has the 2nd precedence. But, it is right associative. That is, if there are two
exponentiation operations continuously, it will be evaluated from right to left (unlike
most of other operators which are evaluated from left to right).
For example,
>>> print(2**3) #It is 23
8
2
>>> print(2**3**2) #It is 512 i.e., 23
Multiplication and Division are the next priority. Out of these two operations, whichever
comes first in the expression is evaluated.
>>> print(5*2/4) #multiplication and then division 2.5
>>> print(5/4*2) #division and then multiplication 2.5
Addition and Subtraction are the least priority. Out of these two operations, whichever
appears first in the expression is evaluated i.e., they are evaluated from left to right
String Operations
String concatenation can be done using + operator as shown below –
>>> x="32"
>>> y="45"
>>> print(x+y)
3245
Observe the output: here, the value of y (a string “45”, but not a number 45) is placed just in front
of value of x( a string “32”). Hence the result would be “3245” and its type would bestring.
NOTE: One can use single quotes to enclose a string value, instead of double quotes.
Python (and all programming languages) ignores the text written as comment lines.
They are only for the programmer‟s (or any reader‟s) reference.
Ex2.
basic=10000
da=0.3*basic
gross_sal=basic+da
print("Gross Sal = ",gross_sal) #output is 13000
One can observe that both of these two examples are performing same task.
But, compared to Ex1, the variables in Ex2 are indicating what is being calculated.
That is, variable names in Ex2 are indicating the purpose for which they are being
used in the program. Such variable names are known as mnemonic variable names.
The word mnemonic means memory aid. The mnemonic variables are created to
help the programmer to remember the purpose for which they have been created.
Python can understand the set of reserved words (or keywords), and hence it flashes
an error when such words are used as variable names by the programmer.
Moreover, most of the Python editors have a mechanism to show keywords in a
different color. Hence, programmer can easily make out the keyword immediately
when he/she types that word.
Ex1: When multiple variables have to be displayed embedded within a string, the format()
function is useful as shown below –
>>> x=10
>>> y=20
>>> print("x={0}, y={1}".format(x,y))
x=10, y=20
While using format() the arguments of print() must be numbered as 0, 1, 2, 3, etc. and they must be
provided inside the format() in the same order.
Ex2: The format() function can be used to specify the width of the variable (the number of
spaces that the variable should occupy in the output) as well. Consider below given example which
displays a number, its square and its cube.
for x in range(1,5):
print("{0:1d} {1:3d} {2:4d}".format(x,x**2, x**3))
Output:
1 1 1
2 4 8
3 9 27
4 16 64
Here, 1d, 3d and 4d indicates 1-digit space, 2-digit space etc. on the output screen.
Ex3: One can use % symbol to have required number of spaces for a variable. This will be useful
in printing floating point numbers.
>>> x=19/3
>>> print(x)
6.333333333333333 #observe number of digits after dot
>>> print("%.3f"%(x)) #only 3 places after decimal point 6.333
>>> x=20/3
>>> y=13/7
>>> print("x= ",x, "y=",y) #observe actual digits
x=6.666666666666667 y= 1.8571428571428572
>>> print("x=%0.4f, y=%0.2f"%(x,y))
x=6.6667, y=1.86 #observe rounding off digits
Boolean Expressions
A Boolean Expression is an expression which results in True or False.
The True and False are special values that belong to class bool.
Check the following –
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Boolean expression may be as below –
>>> 10==12
False
>>> x=10
>>> y=10
>>> x==y
True
Various comparison operations are shown in Table.
>>> print(x)
False
>>> print(a==b)
False
>>> print("a<b is ", a<b)
a<b is True
>>> print("a!=b is", a!=b)
a!=b is True
>>> 10 is 20
False
>>> 10 is 10
True
NOTE: For a first look, the operators ==and is look same. Similarly, the operators !=and is not look the
same. But, the operators == and != does the equality test. That is, they will compare the values stored in
the variables. Whereas, the operators is and is not does the identity test. That is, they will compare whether
two objects are same. Usually, two objects are same when their memory locations are same. This concept
will be more clear when we take up classes and objects in Python.
Logical Operators
There are 3 logical operators in Python as shown in Table
Table listing Logical Operators
Operator Meaning Example
and Returns true, if both operands are true a and b
or Returns true, if any one of two operands is true a or b
not Return true, if the operand is false (it is a unary operator) not a
NOTE:
1. Logical operators treat the operands as Boolean (True or False).
2. Python treats any non-zero number as True and zero as False.
3. While using and operator, if the first operand is False, then the second operand is not
evaluated by Python. Because False and’ed with anything is False.
4. In case of or operator, if the first operand is True, the second operand is not evaluated.
Because True or’ed with anything is True.
Complement of x is False
Example 2 (With numeric Operands):
>>> a=-3
>>> b=10
>>> print(a and b) #and operation
10 #a is true, hence b is evaluated and printed
>>> print(a or b) #or operation
-3 #a is true, hence b is not evaluated
>>> print(0 and 5) #0 is false, so printed
0
Conditional Execution
The basic level of conditional execution can be achieved in Python by using if statement.
The syntax and flowcharts are as below –
if condition:
Statement block False
condition?
Consider an example –
>>> x=10
>>> if x<40:
print("Fail") #observe indentation after if
Fail #output
Usually, the if conditions have a statement block.
In any case, the programmer feels to do nothing when the condition is true, the statement block can
be skipped by just typing pass statement as shown below –
>>> if x<0:
pass #do nothing when x is negative
Alternative Execution
A second form of if statement is alternative execution, in which there are two possibilities based on
condition evaluation.
Here, when the condition is true, one set of statements will be executed and when the condition isfalse,
another set of statements will be executed.
Dept of ECE, BNMIT Page 15
Python Programming on Raspberry PI -22ECE136 Module I
if condition: True
Statement block -1 Condition?
else:
Statement block -2
block-1 block -2
Sample output:
Enter x: 13
x is odd
Nested Conditionals
The conditional statements can be nested.
That is, one set of conditional statements can be nested inside the other.
It can be done in multiple ways depending on programmer’s requirements.
Examples are given below –
age=int(input("Enter age:"))
if gender == "M" :
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F":
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")
Sample Output:
Enter gender: F
Enter age: 17
Girl, Not Eligible for Marriage
NOTE: Nested conditionals make the code difficult to read, even though there are proper indentations.
Hence, it is advised to use logical operators like and to simplify the nested conditionals. For example,
the outer and inner conditions in Ex1 above can be joined as -
if marks>=60 and marks<70:
#do something
Chained Conditionals
Some of the programs require more than one possibility to be checked for executing a set of
statements.
That means, we may have more than one branch. This is solved with the help of chained
conditionals.
The syntax and flowchart is given below –
if condition1:
Statement Block-1
elif condition2:
Statement Block-2
|
|
|
|
elif condition_n:
Statement Block-n
else:
Statement Block-(n+1)
The conditions are checked one by one sequentially. If any condition is satisfied, the respective
statement block will be executed and further conditions are not checked. Note that, the last else block
is not necessary always.
Example: marks=float(input("Enter marks:"))
if marks >= 80:
print("First Class with Distinction")
elif marks >= 60 and marks < 80:
print("First Class")
elif marks >= 50 and marks < 60:
print("Second Class")
elif marks >= 35 and marks < 50:
print("Third Class")
else:
print("Fail")
Sample Output:
Enter marks: 78
First Class
ITERATION
Iteration is a processing of repeating some task. In a real time programming, we require a set of
statements to be repeated certain number of times and/or till a condition is met. Every programming
language provides certain constructs to achieve the repetition of tasks. In this section, various such
looping structures are discussed.
The while Statement
The while loop has the syntax as below –
while condition:
statement_1
statement_2
…………….
statement_n
statements_after_while
Here, while is a keyword, the flow of execution for a while statement is as below.
The condition is evaluated first, yielding True or False
If the condition is false, the loop is terminated and statements after the loop will be executed.
If the condition is true, the body will be executed which comprises of the statement_1 to
statement_n and then goes back to condition evaluation.
Consider an example –
n=1
while n<=5:
print(n) #observe indentation
n=n+1
print("over")
The output of above code segment would be –
1
2
3
4
5
over
In the above example, a variable n is initialized to 1. Then the condition n<=5 is being checked. As
the condition is true, the block of code containing print statement print(n) and increment statement
(n=n+1)are executed. After these two lines, condition is checked again. The procedure continues till
condition becomes false, that is when n becomes 6. Now, the while-loop is terminated and next statement
after the loop will be executed. Thus, in this example, the loop is iterated for 5 times.
Consider another example –
n=5
while n>0:
print(n) #observe indentation
Dept of ECE, BNMIT Page 19
Python Programming on Raspberry PI -22ECE136 Module I
n=n-1
print("Blast off!")
while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
Output:
Enter a umber: 23
Dept of ECE, BNMIT Page 20
Python Programming on Raspberry PI -22ECE136 Module I
while True:
line = input(">")
if line == 'done':
break
print(line)
print('Done!')
In the above example, since the loop condition is True, so the loop runs repeatedly until it hits the
break statement.
Each time it prompts the user to enter the data. If the user types done, the break statement exits the
loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop.
Output will be:
>hello
hello
>finished
finished
>done
Done!
Sometimes, programmer would like to move to next iteration by skipping few statements in the
loop, based on some condition with current iteration. For this purpose continue statement is used.
For example, we would like to find the sum of 5 even numbers taken as input from the keyboard.
The logic is –
Read a number from the keyboard
If that number is odd, without doing anything else, just move to next iteration for reading
another number
If the number is even, add it to sum and increment the accumulator variable.
When accumulator crosses 5, stop the program
The program for the above task can be written as –
sum=0
count=0
while True:
x=input("Enter a number:")
if x%2!=0:
continue
else:
sum+=x
count+=1
if count==5:
break
print("Sum= ", sum)
Output:
Enter a number: 23
Enter a number: 67
Enter a number: 789
Enter a number: 78
Enter a number: 5
Enter a number: 7
Sum= 891
Example of a loop that copies its input until the user types “done”, but treats lines that start with
the hash character as lines not to be printed
while True:
line=input('>')
if line[0] == '#':
continue
Dept of ECE, BNMIT Page 22
Python Programming on Raspberry PI -22ECE136 Module I
if line =='done':
break
print(line)
print('Done!')
Output:
> hello there
hello there
> #don’t print this
> print this!
print this!
> done
Done!
Above, all lines are printed except the one that starts with ‘#’ because when continue is executed, it
ends the current iteration and jumps back to the while statement to start the next iteration, thus
skipping the print statement.
statements_after_for
Example: In the below given example, a list names containing three strings has been created. Then
the counter variable x in the for-loop iterates over this list. The variable x takes the elements in
names one by one and the body of the loop is executed.
names=["Ram", "Shyam", "Bheem"]
for x in names:
print("Happy New Year",x)
Dept of ECE, BNMIT Page 23
Python Programming on Raspberry PI -22ECE136 Module I
print('Done!')
The output would be –
Happy New Year Ram
Happy New Year Shyam
Happy New Year Bheem
Done!
NOTE: In Python, list is an important data type. It can take a sequence of elements of different types.
It can take values as a comma separated sequence enclosed within square brackets. Elements in the list
can be extracted using index (just similar to extracting array elements in C/C++ language). Various
operations like indexing, slicing, merging, addition and deletion of elements etc. can be applied on lists.
The details discussion on Lists will be done in Module 3.
The for loop can be used to print (or extract) all the characters in a string as shown below –
for i in "Hello":
print(i, end=‟\t‟)
Output:
H e l l o
When we have a fixed set of numbers to iterate in a for loop, we can use a function
range(). The function range() takes the following format –
range(start, end, steps)
The start and end indicates starting and ending values in the sequence, where end is excluded in the
sequence (That is, sequence is up to end-1). The default value of start is 0. The argument steps
indicates the increment/decrement in the values of sequence with the default value as 1. Hence, the
argument steps is optional.
Let us consider few examples on usage of range() function.
Loop Patterns
The while-loop and for-loop are usually used to go through a list of items or the contents of a file and
to check maximum or minimum data value. These loops are generally constructed by the following
procedure –
Initializing one or more variables before the loop starts
Performing some computation on each item in the loop body, possibly changing the variables
in the body of the loop
Looking at the resulting variables when the loop completes
The construction of these loop patterns are demonstrated in the following examples.
Counting and Summing Loops: One can use the for loop for counting number of items in the list as
shown –
count = 0
for i in [4, -2, 41, 34, 25]:
count = count + 1
print(“Count:”, count)
Here, the variable count is initialized before the loop. Though the counter variable is not being
used inside the body of the loop, it controls the number of iterations.
The variable count is incremented in every iteration, and at the end of the loop the total number of
elements in the list is stored in it.
One more loop similar to the above is finding the sum of elements in the list –
total = 0
for x in [4, -2, 41, 34, 25]:
total = total + x
print(“Total:”, total)
Here, the variable total is called as accumulator because in every iteration, it accumulates the sum
of elements. In each iteration, this variable contains running total of values so far.
NOTE: In practice, both of the counting and summing loops are not necessary, because there are
built-in functions len()and sum()for the same tasks respectively.
Maximum and Minimum Loops:
To find maximum element in the list, the following code can be used –
big = None
Dept of ECE, BNMIT Page 25
Python Programming on Raspberry PI -22ECE136 Module I
NOTE: In Python, there are built-in functions max() and min()to compute maximum and minimum
values among. Hence, the above two loops need not be written by the programmer explicitly. The
inbuilt function min()has the following code in Python –
def min(values):
smallest = None
for value in values: