PWP Chapter 2
PWP Chapter 2
Unit No. 2
Python operator &
control flow statements
by
P. S. Bhandare
Hours: 6
Marks: 10
1|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Syllabus:
2.1 Basic Operators: Arithmetic, Comparison/ Relational, Assignment,
Logical, Bitwise, Membership, Identity operators, Python Operator
Precedence
2.2 Control Flow:
2.3 Conditional Statements (if, if ... else, nested if)
2.4 Looping in python (while loop, for loop, nested loops)
2.5 loop manipulation using continue, pass, break, else.
2|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
3|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Introduction:
Operator
An operator is a symbol that performs an operation. An operator acts on
some variables called operands. For example, if we write a + b the operator
'+' is acting on two operands 'a' and 'b'. If an operator acts on a single
variable, it is called unary operator. If an operator acts on two variables, it is
called binary operator. If an operator acts on three variables, then it is
called ternary operator. This is one type of classification. We can classify the
operators depending upon their nature, as shown below:
Arithmetic operators
Assignment operators
Unary minus operator
Relational operators
Logical operators
Boolean operators
Bitwise operators
Membership operators
Identity operators
Arithmetic Operators
These operators are used to perform basic arithmetic operations like
addition, subtraction, division, etc.
There are seven arithmetic operators available in Python. Since these
operators act on two operands, they are called binary 'operators' also.
There are two types of division operators:
Float division
Floor division
Float division
The quotient returned by this operator is always a float number, no matter
if two numbers are integers. For example:
Example: The code performs division operations and prints the results. It
demonstrates that both integer and floating-point divisions return accurate
results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’
4|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0
5.0
-5.0
10.0
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being
passed. If any of the numbers is float, it returns output in float. It is also
known as Floor division because, if any number is negative, then the output
will be floored. For example:
Example: The code demonstrates integer (floor) division operations using
the ‘//’ operator. It provides results as follows: ’10//3′ equals ‘3’, ‘-
5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer
division returns the largest integer less than or equal to the division result.
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-2
2.0
-2.0
5|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
6|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
7|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
8|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Relational Operators
Relational operators are used to compare two quantities. We can
understand whether two values are same or which one is bigger or which
one is lesser, etc. using these operators. These operators will result in True
or False depending on the values compared, as shown in Table. In this
table, we are assuming a =1 and b = 2
'Yes' and if it becomes False, then it will display 'No'. In this case, (1>2) is
False and hence 'No' will be displayed.
Relational operators can be chained. It means, a single expression can hold
more than one relational operator. For example,
x=15
10<x<20 # displays True
Here, 10 is less than 15 is True, and then 15 is less than 20 is True. Since
both the conditions are evaluated to True, the result will be True.
10>=x<20 # displays False
Here, 10 is greater than or equal to 15 is False. But 15 is less than 20 is
True. Since we get False and True, the result will be False.
10<x>20 # displays False
Here, 10 is less than 15 is True. But 15 is greater than 20 is False. Since we
are getting True and False, the total result will be False. So, the point is this:
in the chain of relational operators, if we get all True, then only the final
result will be True. If any comparison yields False, then we get False as the
final result. Thus,
1<2<3<4 # will give True
1<2>3<4 # will give False
4>2>=2>1 # will give True
Logical Operators
Logical operators are useful to construct compound conditions. A
compound condition is a combination of more than one simple condition.
Each of the simple condition is evaluated to True or False and then the
decision is taken to know whether the total condition is True or False. We
should keep in mind that in case of logical operators, False indicates 0 and
True indicates any other number. There are 3 logical operators as shown in
Table 4.4. Let's take x = 1 and y = 2 in this table.
10 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
11 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Boolean Operators
We know that there are two ‘bool' type literals. They are True and False.
Boolean operators act upon 'bool' type literals and they provide 'bool' type
output. It means the result provided by Boolean operators will be again
either True or False. There are three Boolean operators as mentioned in
Table.
Let's take x = True and y = False
Bitwise Operators
These operators act on individual bits (0 and 1) of the operands. We can
use bitwise operators directly on binary numbers or on integers also. When
we use these operators on integers, these numbers are converted into bits
(binary number system) and then bitwise operators act upon those bits.
The results given by these operators are always in the form of integers.
12 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
We use decimal number system in our daily life. This number system
consists of 10 digits from 0 to 9. We count all numbers using these 10 digits
only. But in case of binary number system that is used by computers
internally, there are only 2 digits, i.e. O and 1 which are called bits (binary
digits). All values are represented only using these two bits.
x 0 1 0 0 0 0 0
~x 1 0 1 1 1 1 1
e.g
x=10
~x
-11
13 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
14 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
15 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
16 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Membership Operators
The membership operators are useful to test for membership in a sequence
such as strings, lists, tuples or dictionaries. For example, if an element is
found in the sequence or not can be asserted using these operators. There
are two membership operators as shown here:
in
not in
17 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
The in Operator
This operator returns True if an element is found in the specified sequence.
If the element is not found in the sequence, then it returns False.
The not in Operator
This works in reverse manner for 'in' operator. This operator returns True if
an element is not found in the sequence. If the element is found, then it
returns False.
Let's take a group of strings in a list. We want to display the members of the
list using a
for loop where the 'in' operator is used. The list of names is given below:
names = ["Poly", "Tech", "TYCO", "Ppur"]
Here the list name is 'names'. It contains a group of names. Suppose, we
want to retrieve all the names from this list, we can use a for loop as:
for name in names: print (name)
print(name)
o/p:
Poly
Tech
TYCO
Ppur
Identity Operators
These operators compare the memory locations of two objects. Hence, it is
possible to know whether the two objects are same or not. The memory
location of an object can be seen using the id() function. This function
returns an integer number, called the identity number that internally
18 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
represents the memory location of the object. For example, id(a) gives the
identity number of the object referred by the name 'a'. See the following
In the first statement, we are assigning the name (or identifier) 'a' to the
object 25. In the second statement, we are assigning another name 'b' to the
same object 25. In Python, everything is considered as an object. Here, 25 is
the object for which two names are given. If we display an identity number
of these two variables, we will get same numbers as they refer to the same
object.
statements:
a = 25
b = 25
id(a)
1670954952
id(b)
1670954952
There are two identity operators:
is
is not
The is Operator
The 'is' operator is useful to compare whether two objects are same or not.
It will internally compare the identity number of the objects. If the identity
numbers of the objects are same, it will return True; otherwise, it returns
False.
The is not Operator
This is not operator returns True, if the identity numbers of two objects
being compared are not same. If they are same, then it will return False.
The is' and 'is not' operators do not compare the values of the objects. They
compare the identity numbers or memory locations of the objects. If we
19 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
want to compare the value of the objects, we should use equality operator
(==)
a = 25
b = 25
if(a is b)
print("a and b have same identity")
else:
print("a and b do not have same identity")
Output:
a and b have same identity
As another example, we will take two lists with 4 elements each as:
one = [1, 2, 3, 4]
two = [1.2 * 0.3 * 0.4]
if(one is two):
print("one and two are same")
else:
print("one and two are not same")
Output:
one and two are not same
In the preceding example, the lists one and two are having same elements
or values. But the output is "one and two are not same". The reason is this:
'is' operator does not compare the values. It compares the identity numbers
of the lists. Let's see the identity numbers of these two lists by using the
id() function:
id (one)
51792432
id(two)
20 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division,
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, Comparisons, Identity, Membership
not in operators
not Logical NOT
and Logical AND
21 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
or Logical OR
Input statements
Output statements
To display output or results, Python provides the print() function. This
function can be used in different formats which are discussed hereunder.
The print() Statement
When the print() function is called simply, it will throw the cursor to the
next line. It means that a blank line will be displayed.
The print("string") Statement
A string represents a group of characters. When a string is passed to the
print() function, the string is displayed as it is. See the example:
print("Hello")
Hello
Please remember that in case of strings, double quotes and single quotes
have the same meaning and hence can be used interchangeably.
print('Hello')
Hello
22 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
23 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print() function sees a comma, it will assume that the values are different
and hence a space should be used between them for clarity.
Dear
How are U?
Each print() function throws the cursor into the next line after displaying
the output. This is the reason we got the output in 3 lines. We can ask the
print() function not to throw the cursor into the next line but display the
output in the same line. This is done using 'end' attribute. The way one can
use it is end="characters" which indicates the ending characters for the
line. Suppose, we write end=", then the ending character for each line will
be ‘ ‘ (nothing) and hence it will display the next output in the same line.
See the
print("Hello", end=' ‘ )
print("Dear", end=’ ' )
print('How are u?', end=' ' )
HelloDearHow are U?
If we use end='\t' then the output will be displayed in the same line but tab
space will separate them as:
print ("Dear",end=’\t’)
print('How are u?', end='\t')
Output:
Hello
example:
Output:
Dear How are U?
If we use end='\n' then the output is displayed in a separate line. So, '\n' is
the default value for 'end' attribute.
25 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
26 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
As seen above, to display a single variable (i.e. x) we need not wrap it inside
parentheses. When more than one variable is to be displayed, then
parentheses are needed as:
x , y = 10 , 20
print(‘x=%i y=%d’, %(x,y))
x=10 y=20
To display a string, we can use %s in the formatted string. When we use
%20s, it will allot 20 spaces and the string is displayed right aligned in
those spaces. To align the string towards left side in the spaces, we can use
%-20s. Consider the following examples:
name=’Poly’
print(‘name %s’, %name )
name Poly
name=’Poly’
print(‘name (%20s)’, %name )
name ( Poly)
name=’Poly’
print(‘name (%-20s)’, %name )
name (Poly )
27 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
name='Poly'
print ('Name %c, %c’, % (name [0:2]))
Name PO
To display floating point values, we can use %f in the formatted string. If we
use %8.2f, then the float value is displayed in 8 spaces and within these
spaces, a decimal point and next 2 fraction digits.
When we use %.3f, then the float value is displayed with 3 fraction digits
after the decimal point. However, the digits before decimal point will be
displayed as they are. Consider the following examples:
num-123.456789
print('The value is: %f' % num)
The value is: 123.456789
print('The value is: %8.2f' %num)
The value is: 123.46 #observe 2 spaces before the value
print('The value is: %.2f' %num)
The value is: 123.46
Inside the formatted string, we can use replacement field which is denoted
by a pair of curly braces { }. We can mention names or indexes in these
replacement fields. These names or indexes represent the order of the
values. After the formatted string, we should write member operator and
then format() method where we should mention the values to be displayed.
Consider the general format given below:
print('format string with replacement fields' .format(values))
To display a single value using index in the replacement field, we can write
as:
n1, n2, n3=1,2,3
print (‘number1={0}’ .format(nl))
number1=1
28 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
In the above statement, observe (0) which was replaced by the value of n1.
To display all the three numbers, we can use:
print('number1={0},number2={1},number3={2}'.format(n1,n2,n3))
number1=1, number2=2, number3=3
In the above statement, {0},{1},{2} represent the values of n1, n2 and n3,
respectively. Hence, if we change the order of these fields, we will have
order of the values to be changed in the output as:
print('number1={1},number2={0},number3={2}'.format(n1, n2, n3))
number1=2, number2=1, number3=3
As an alternate, we can also use names in the replacement fields. But the
values for these names should be provided in the format() method.
Consider the following example:
print('number1={two}, number2={one}, number3={three}’. format
(one=n1. Two=n2, three=n3))
number1-2, number2-1, number3=3
We can also use the curly braces without mentioning indexes or names. In
this case, those braces will assume the sequence of values as they are given.
Consider the following
print('number1={}, number2={}, number3={}'. format(n1, n2, n3))
number1=1, number2=2, number3=3
All format given in below program.
nm,sal='poly', 1200.453
print('name={0},salary={1}'.format(nm,sal))
print('name={n},salary={n}'.format(n=nm,s=sal))
print('name={:s},salary={:.2f}'.format(nm,sal))
print('name=%s,salary=%.2f'%(nm,sal))
"""
o/p:
29 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
name=poly,salary=1200.453
name=poly,salary=poly
name=poly,salary=1200.45
name=poly,salary=1200.45
"""
Input Statements
To accept input from keyboard, Python provides the input() function. This
function takes a value from the keyboard and returns it as a string. For
example,
str = input() #this will wait till we enter a string
Poly tech # enter this string
print(str)
Poly tech
It is a better idea to display a message to the user so that the user
understands what to enter. This can be done by writing a message inside
the input() function as:
str= input('Enter your name: ')
Enter your name: Poly tech
print(str)
Poly tech
Once the value comes into the variable 'str', it can be converted into 'int' or
'float' etc. This is useful to accept numbers as:
str = input('Enter a number: ')
Enter a number: 125
x = int(str) # str is converted into int
print(x)
125
30 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
We can use the int() function before the input() function to accept an
integer from the keyboard as:
x = int (input('Enter a number: '))
Enter a number: 125
print(x)
125
Similarly, to accept a float value from the keyboard, we can use the float()
function along with the input() function as:
x = float(input('Enter a number: '))
Enter a number: 12.345
print(x)
12.345
We will understand these concepts with the help of a Python program. Let's
write a program to accept a string and display it, as shown in Program .
31 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
32 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
The same procedure can be adopted to accept a floating point number from
the keyboard. While the input() function accepts a float value as a string, it
should be converted into float number using the float() function.
#accepting float number from keyboard
X = float(input('Enter a number: '))
print('U entered: ', x); #display the float number
Output:
Enter a number: 12. 54621345789
U entered: 12.54621345789
From the above output, we can understand that the float values are
displayed to an accuracy of 15 digits after decimal point. In the next
program, we will accept two integer numbers and display them.
A Python program to accept two integer numbers from keyboard.
#accepting two numbers from keyboard
x=int( input (print(‘Enter first number: '))
y=int( input (print(‘Enter Second number: '))
print('u entered: ', x, y) #display both the numbers separating with a
space
Enter first number: 45
Enter Second number:54
u entered: 45 54
The eval() function takes a string and evaluates the result of the string by
taking it as a Python expression. For example, let's take a string - a + b -4^ -
where a = 5 and b = 10 If we pass the string to the eval() function, it will
evaluate the string and returns the result Consider the following example:
a, b = 5,10
result = eval("a+b-4")
33 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print(result)
11
We can use the eval() function along with input() function. Since the input()
function accepts a value in the form of a string, the eval() function receives
that string and evaluates it. In Program 14, we can enter an expression that
is evaluated by the eval() function and result is displayed.
Evaluating an expression entered from keyboard.
# using eval() along with input function
x=eval( input (‘Enter an expression: "))
print(‘Result=%d’%x)
Enter an expression: 10 + 5 - 4
Result= 11
We can use the combination of eval( ) and input() functions to accept
objects like lists or tuples. When the user types the list using square braces
[ ], eval() will understand that it is a list.
A Python program to accept a list and display it.
35 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
b=sys.argv[2]
c=int(a)+int(b)
print("C= ",c)
print("\n No of ARGV:- ", n)
"""
o/p:
python commandline.py 10 20
C= 30
No of ARGV:- 3
"""
Control Statements
When we write a program, the statements in the program are normally
executed We by and one by one. This type of execution is called 'sequential
execution’.
To develop critical programs, the programmer should be able to change the
flow of execution as needed by him. For example, the programmer may
wish to repeat a group of statements several times or he may want to
directly jump from one statement to another statement in the program. For
this purpose, we need control statements.
Conditional Statements
Conditional statements are statements which control or change the flow of
execution. The following are the control statements available in Python:
if statement
if... else statement
if... elif... else statement
while loop
for loop
else suite
break statement
36 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
continue statement
pass statement
assert statement
return statement
Please note that the switch statement found in many languages like C and
Java is not available in Python.
The if Statement
This statement is used to execute one or more statement depending on
whether a condition is True or not. The syntax or correct format of if
statement is given below:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements
given after colon (:) are executed. We can write one or more statements
after colon (:). If the condition is False, then the statements mentioned after
colon are not executed.
37 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
A Word on Indentation
Understanding indentation is very important in Python. Indentation refers
to spaces that are used in the beginning of a statement. The statements
with same indentation belong to same group called a suite. By default,
Python uses 4 spaces but it can be increased or decreased by the
programmers. Consider the statements given below
f x ==1
print('a')
print('b')
if y ==2
print('c')
38 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print (‘d’ )
print (‘end’ )
if x=1:
print('end')
belong to same group as they do not have any spaces before them. So, after
executing the if statement, Python interpreter goes to the next statement,
i.e. print('end'). Even if the statement if x== 1' is not executed, interpreter
will execute print('end') statement as it is the next executable statement in
our program.
In the next level, the following statements are typed with 4 spaces before
them and hence they are at the same level (same suite).
print('a')
print('b')
if y = 2
These statements are inside if x== 1 statement. Hence if the condition is
True (i.e. x ==1 is satisfied), then the above 3 statements are executed.
Thus, the third statement if y== 2 is executed only if x ==1 is True. At the
next level, we can find the following statements:
print (‘ c’ )
print('d')
These two statements are typed with 8 spaces before them and hence they
belong to the same group (or suite). Since they are inside if y = 2 statement,
they are executed only if condition y ==2 is True.
39 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
statements1
else:
statements2
If the condition is True, then it will execute statements1 and if the condition
is False, then it will execute statements2. It is advised to use 4 spaces as
indentation before statements1 and statements2. In following Program, we
are trying to display whether a given number is even or odd. The logic is
simple. If the number is divisible by 2, then it is an even number; otherwise,
it is an odd number. To know whether a number is divisible by 2 or not, we
can use modulus operator (%). This operator gives remainder of division. If
the remainder is 0, then the number is divisible, otherwise not.
A Python program to test whether a number is even or odd.
# to know if a given number is even or odd
x = 10
if x%2==0:
print (x,” is even number")
else:
print ( x ," is odd number")
Output:
10 is even number
The same program can be rewritten to accept input from keyboard. In
Program 5, we are accepting an integer number from keyboard and testing
whether it is even or odd.
A Python program to accept a number from the keyboard and test whether
it is even or odd.
# to know if a given number is even or odd
x=int (input) "Enter a number: "))
if x%2 ==0:
print(x, is even number")
40 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
else:
print(x, " is odd number")
Output:
Enter a number: 11
11 is odd number
We will write another program where we accept a number from the user
and test whether that number is in between 1 and 10 (inclusive) or not. If
the entered number is x, then the condition x >= 1 and x <= 10 checks
whether the number is in between 1 and 10.
A Python program to test whether a given number is in between 1 and 10.
# using 'and' in if else statement .
x = int(input('Enter a number: '))
if x >= 1 and x <= 10:
print("You typed", x, "which is between 1 and 10”)
else:
print("You typed", x, "which is below 1 or above 10 “)
Output:
Enter a number: 9
You typed 9 which is between 1 and 10
Observe the condition after 'if'. We used 'and' to combine two conditions x
>= 1 and x <= 10. Such a condition is called compound condition.
41 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
if conditionl:
statementsl
elif condition2:
statements2
elif condition3:
statements3
else:
statements4
When condition1 is True, the statements1 will be executed. If condition1 is
False, then condition2 is evaluated. When condition2 is True, the
statements2 will be executed. When condition2 is False, the condition3 is
tested. If condition3 is True, then statements3 will be executed. When
condition3 is False, the statements4 will be executed. It means statements4
will be executed only if none of the conditions are True.
Observe colon (:) after each condition. The statements1, statements2,
represent one statement or a suite. The final 'else' part is not compulsory. It
means, it is possible to write if…elif statement, without 'else' and
statements4. Let's write a program to understand the usage of if…elif…else
statement. In below program we are checking whether a number is positive
or negative. A number becomes positive when it is greater than 0. A number
becomes negative when it is lesser than 0. Apart from positive and negative,
a number can also become zero (neither +ve nor -ve). All these 3
combinations are checked in the program.
A Python program to know if a given number is zero, positive or negative.
# to know if a given number is zero or +ve or -ve
num=-5
if num==0:
print(num, "is zero")
elif num>0:
print(num, "is positive")
42 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
else:
print(num, "is negative")
Output:
-5 is negative
observe the indentation. There are 4 spaces before every statement after
colon. Now, we write another program that accepts a numeric digit from
keyboard and prints it in words. In this program, we will use several elif
conditions. After colon, we are leaving only one space before every print()
statement. While this is not recommended way of using indentation, this
program will run properly since every statement has equal number of
spaces (1 space) as indentation.
A program to accept a numeric digit from keyboard and display in words.
# to display a numeric digit in words
x = int(input('Enter a digit: '))
if x ==0: print("ZERO")
elif x ==1: print("ONE")
elif x ==2: print("TWO"),
elif x ==3: print("THREE")
elif x ==4: print(“FOUR")
elif x ==5: print ("FTVE” )
elif x ==6: print("SIX")
elif x ==7: print("SEVEN")
elif x ==8: print("EIGHT")
elif x ==9: print ("NINE”) # else part not compulsory
Output:
Enter a digit: 5
FIVE
43 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
In the above program, if we enter a digit '15', then the program does not
display any output. On the other hand, if we want to display a message like
'Please enter digit between 0 and 9', we can add 'else' statement at the end
of the program, as:
else: print('Please enter digit between 0 and 9')
44 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print(x)
Once this is done, we have to increment x value by 1, by writing x +=1 or x =
x + 1 . Now, consider Program in which while loop is used to display
numbers.
x=1
while x<=10:
print(x)
x+=1
print("End")
1
2
3
4
5
6
7
8
9
10
End
For loop
A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string). This is less like the for keyword in other
programming languages, and works more like an iterator method as found
in other object-orientated programming languages. With the for loop, we
can execute a set of statements, once for each item in a list, tuple, set etc.
The for loop is useful to iterate over the elements of a sequence. It means,
the for loop can be used to execute a group of statements repeatedly
depending upon the number of elements in the sequence. The for loop can
45 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
work with sequence like string, list, tuple, range etc. The syntax of the for
loop is given below:
for var in sequence:
statements
The first element of the sequence is assigned to the variable written after
'for' and then the statements are executed. Next, the second element of the
sequence is assigned to the variable and then the statements are executed
second time. In this way, for each element of the sequence, the statements
are executed once. So, the for loop is executed as many times as there are
number of elements in the sequence.
A Python program to display characters of a string using for loop.
# to display each character from a string
str='Hello'
For ch in str :
print(ch)
H
e
l
l
o
Display odd numbers between 1 and 10:
for i in range(1, 10, 2):
print(i)
46 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
A Python program to display and find the sum of a list of numbers using for
loop.
# to find sum of list of numbers using for.
list = [10,20,30,40,50] # take a list of numbers
sum=0 #initially sum is zero
for i in list:
print(i) #display the element from list
sum+=i #add each element to sum
print('Sum=', sum)
# to find sum of list of numbers using while.
list=[10,22,33,44,55,66]
sum=0
i=0
while i < len(list):
print(list[i])
sum+=list[i]
i+=1
print("sum=",sum)
o/p:
10
22
33
44
55
66
47 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
sum= 230
Infinite Loops
i=1
while i<=10:
print(i)
It will display the value 1 forever. To stop the program, we have press
Control+C at system prompt. Another way of creating an infinite loop is to
write 'True' in the condition part of the while loop so that the Python
interpreter thinks that the condition is True always and hence executes it
forever. See the example:
while(True)
print("Hai")
This loop will always display 'Hai' without stopping since the condition is
read as 'True' always. Infinite loops are drawbacks in a program because
when the user is caught in an infinite loop, he cannot understand how to
come out of the loop. So, it is always recommended to avoid infinite loops in
any program.
Nested Loops
It is possible to write one loop inside another loop. For example, we can
write a for loop inside a while loop or a for loop inside another for loop.
Such loops are called 'nested loops'. Take the following for loops:
When outer for loop is executed once, the inner for loop is executed for 4
times. It means, when i value is 0, j values will change from 0 to 3. So,
print() function will display the following output:
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
Once the inner for loop execution is completed (j reached 3), then Python
interpreter will go back to outer for loop to repeat the execution for second
time. This time, i value will be 1& again loop is executed for 4 times.
i=1 j=0
i=1 j=1
i=1 j=2
i=1 j=3
This time, i value will be 2 & again loop is executed for 4 times.
i=2 j=0
i=2 j=1
i=2 j=2
i=2 j=3
A Python program that displays stars in right angled triangular form using
nested loops.
# to display stars in right angled triangular form
for i in range(1, 11): # to display 10 rows
for j in range(1, i+1): # no. of stars = row number
print('*’ , end=' ')
print()
49 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
Ans 2:
for i in range(1,11):
print('*'*(i))
o/p:
*
**
***
****
*****
******
*******
********
*********
**********
A Python program to display the stars in an equilateral triangular form
using a single for loop.
# to display stars in equilateral triangular form
n=40
for i in range(1, 11):
print(‘ ‘*n, end='') # repeat space for n times
print ('* '*(i)) # repeat star for i times
n-=1
A Python program to display numbers from 1 to 100 in a proper format. #
Displaying nur numbers from 1 to 100 in 10 rows and 10 cols. for
50 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The else Suite
In Python, it is possible to use 'else' statement along with for loop or while
loop in the form
for with else
for(var in sequence):
statements
else:
statements
while with else
while(condition):
statements
else:
statements
The statements written after 'else' are called suite. The else suite will be
always executed irrespective of the statements in the loop are executed or
not. For example,
for i in range (5):
print (“ Yes” )
else:
51 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print (“N0”)
this will display the following output:
Yes
Yes
Yes
Yes
Yes
No
It means, the for loop statement is executed and also the else suite is
executed. Suppose, we write:
for i in range(0):
print (“ Yes”)
else:
print("No")
This will display the following output:
No
Here, the statement in the for loop is not even executed once, but the else
suite is executed as usual. So, the point is this: the else suite is always
executed. But then where is this else suite useful?
Sometimes, we write programs where searching for an element is done in
the sequence When the element is not found, we can indicate that in the
else suite easily. In this case, else with for loop or while loop - is very
convenient. Let's now write a program where we take a list of elements and
using for loop we will search for a particular element in the list. If the
element is found in the list, we will display that is found in the group; else
we will display a message that the element is not found in the list. This is
displayed using else suite.
list=[10,20,30,50,60,40,70]
search=int(input(“Enter The no to search:- ”))
for ele in list:
if ele==search
52 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
print(“Element found”)
brea;
else:
print(“Element not found in list”)
The break Statement
The break statement can be used inside a for loop or while loop to come out
of the loop. When break' is executed, the Python interpreter jumps out of
the loop to process the next statement in the program.
We have already used break inside for loop in search Program. When the
element is found, it would break the for loop and comes out. We can also
use break inside a while loop.
i=10
while i>=1:
print(i)
i-=1
if i==5:
break;
print("out of loop")
o/p:
10
9
8
7
6
out of loop
53 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
continue
print(i)
o/p:
2
4
6
8
10
12
14
16
18
In this case, the Python interpreter checks if x>0 is True or not. If it is True,
then the next statements will execute, else it will display AssertionError
along with the message "Wrong input entered".
e.g.
x=int(input("Enter no greater than 0: "))
assert x>0, "Wrong input entered"
print("No -",x)
o/p:
Enter no greater than 0: 5
No – 5
Questions
Summer-22
1. List identity operators in python. (2M)
2. Write a program to print following : (4M)
1
1 2
1 2 3
1 2 3 4
55 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)
56 | P a g e
Prashant S. Bhandare