Ch. 2 Python Operators and Control Flow Statements
Ch. 2 Python Operators and Control Flow Statements
Learning Objectives…
[
2.0 INTRODUCTION
• Operators are the constructs which can manipulate the value of operands. Consider the expression
4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. The Python language provides a
rich set of operators.
• The operator and operand when combined to perform a certain operation, it becomes an expression.
For example, in expression x + y, x and y are the variables (operands) and the plus (+) sign is the
operator that specifies the type of operation performed on the variables.
• In any programming language, a program is written as a set of instructions. The instructions written
in programs are termed as statements.
• In Python, statements in a program are executed one after another in the order in which they are
written. This is called sequential execution of the program.
• But in some situations, the programmer may need to alter the normal flow of execution of a
program or to perform the same operations a number of times.
• For this purpose, Python provides a control structure which transfers the control from one part of
the program to some other part of the program.
• A control structure is a statement that determines the control flow of the set of instructions i.e. a
program. Control statements are the set of statements that are responsible to change the flow of
execution of the program.
• There are different types of control statements supported by Python programming like
decision/conditional control, loop/iteration control and jump or loop control.
[2.1]
Programming with 'Python' 2.2 Python Operators and Control Flow Statements
2.1 OPERATORS
• An operator is a symbol which specifies a specific action. An operator is a special symbol that tells
the interpreter to perform a specific operation on the operands. The operands can be literals,
variables or expressions.
• An operand is a data item on which operator acts. Operators are the symbol, which can manipulate
the value of operands. Some operators require two operands while others require only one.
Comparison operators, Logical operators, Bitwise operators, Identity operators and Membership
operators.
2.1.1 Arithmetic Operators
• The arithmetic operators perform basic arithmetic operations like addition, subtraction,
multiplication and division. All arithmetic operators are binary operators because they can perform
operations on two operands. There are seven arithmetic operators provided in Python programming
such as addition, subtraction, multiplication, division, modulus, floor division, and exponential
operators.
• Assume variable a holds the value 10 and variable b holds the value 20.
Sr. Operator
Operator Description Example
No. Type
1. + Addition Adds the value of the left and right operands. >>> a+b
30
2. − Subtraction Subtracts the value of the right operand from >>> b-a
the value of the left operand. 10
3. * Multiplication Multiplies the value of the left and right >>> a*b
operand. 200
4. / Division Divides the value of the left operand by the right >>> b/a
operand. 2.0
5. ** Exponent Performs exponential calculation. >>> a**2
100
6. % Modulus Returns the remainder after dividing the left >>> a%b
operand with the right operand. 10
7. // Floor Division Division of operands where the solution is a >>> b//a
quotient left after removing decimal numbers. 2
• Membership operators are used to check an item or an element that is part of a string, a list or a
tuple. A membership operator reduces the effort of searching an element in the list.
• Python provides ‘in’ and ‘not in’ operators which are called membership operators and used to test
whether a value or variable is in a sequence.
Sr. No. Operator Description Example
1. in True if value is found in list or in sequence, >>> x="Hello World"
and false it item is not in list or in sequence >>> print('H' in x)
True
2. not in True if value is not found in list or in >>> x="Hello World"
sequence, and false it item is in list or in >>> print("Hello" not in x)
sequence. False
Example:
>>> x="Hello World" # using string
>>> print("H" in x)
True
>>> print("Hello" not in x)
False
>>> y={1:"a",2:"b"} # using list
>>> print(1 in y)
True
>>> print("a" in y)
False
>>> z=("one","two","three") # using tuple
>>> print ("two" in z)
True
• The following table lists all operators from highest precedence to the lowest.
Sr. Operator Name/Description Assoicativity
No.
1. (), [] Parentheses Left to Right
2. ** Exponent Right to Left
3. +x, −x, ~x Unary plus, Unary minus, Bitwise NOT Right to Left
4. *, /, //, % Multiplication, Division, Floor division, Left to Right
Modulus
5. +, − Addition, Subtraction Left to Right
6. <<, >> Bitwise left and right shift operators Left to Right
7. & Bitwise AND Left to Right
8. ^ Bitwise XOR Left to Right
9. | Bitwise OR Left to Right
10. <=, <, >, >= Comparison Operator Left to Right
11. <> == != Equality operators Left to Right
12. = %= /= //= -= Assignment Operators Right to Left
+= *= **=
13. is, is not Identity Left to Right
14. in, not in Membership operators Left to Right
15. Not, OR, AND Logical Operators NOT, AND, OR Left to Right
2. Associativity of Pythons Operators:
• When two operators have the same precedence, associativity helps to determine which the order of
operations. Associativity decides the order in which the operators with same precedence are
executed.
• There are two types of associativity.
(i) Left-to-right: The operator of same precedence is executed from the left side first.
(ii) Right-to-left: The operator of same precedence is executed from the right side first.
• Most of the operators in Python have left-to-right associativity.
Example:
>>> 5*2//3
3
>>> 5*(2//3)
0
Syntax:
if condition1:
if condition2:
statement1
else:
statement2
else:
statement3
Control Flow diagram of Nested if Example:
Statement: a=30
b=20
c=10
if (a>b):
if (a>c):
print("a is greater than b
and c")
else:
print("a is less than b
and c")
print("End of Nested if")
Output:
a is greater than b and c
End of Nested if
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20
print('Reverse of number=',rev)
Output:
Enter a number: 123
Reverse of number= 321
2. Program to find sum of digit of a given number.
n=int(input('Enter a number:'))
sum=0
while(n>0):
rem=n%10
sum=sum+rem
n=int(n/10)
print('Sum of number=',sum)
Output:
Enter a number: 123
Sum of number= 6
3. Program to check whether the input number is Armstrong.
n=int(input('Enter a number:'))
num=n
sum=0
while(n>0):
rem=n%10
sum=sum+rem*rem*rem
n=int(n/10)
if num==sum:
print(num, "is armstrong")
else:
print(num, "is not armstrong")
Output:
Enter a number: 153
153 is armstrong
Enter a number: 123
123 is not armstrong
Example:
list=[10,20,30,40,50]
for x in list:
print(x)
Programming with 'Python' 2.15 Python Operators and Control Flow Statements
Output:
10
20
30
40
50
range() Function:
• The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax: range(begin, end, step)
where,
o Start: An integer number specifying at which position to start. Default is 0.
o End: An integer number specifying at which position to end. i.e. the last number in the sequence.
o Step: An integer number specifying the increment. Default is 1.
Example: For range() function.
>>> list(range(1,6))
[1, 2, 3, 4, 5]
• More examples of range() function:
Example Output
list(range(5)) [0, 1, 2, 3, 4]
list(range(1,5)) [1, 2, 3, 4]
list(range(1,10,2)) [1, 3, 5, 7, 9]
list(range(5,0,-1)) [5, 4, 3, 2, 1]
list(range(10,0,-2)) [10, 8, 6, 4, 2]
list(range(-4,4)) [-4, -3, -2, -1, 0, 1, 2, 3]
list(range(-4,4,2)) [-4, -2, 0, 2]
list(range(0,1)) [0]
list(range(1,1)) [] Empty
list(range(0)) [] Empty
Example:
for i in range(1,11):
print (i, end=' ')
Output:
1 2 3 4 5 6 7 8 9 10
• The print() function has end=' ' which appends a space instead of default newline. Hence, the
numbers will appear in one row.
Additional Programs:
1. Program to print prime numbers in between a range.
start=int(input("Enter starting number: "))
end=int(input("Enter ending number: "))
for n in range(start,end + 1):
if (n>1):
for i in range(2,n):
Programming with 'Python' 2.16 Python Operators and Control Flow Statements
if(n%i)== 0:
break
else:
print(n)
Output:
Enter starting number: 1
Enter ending number: 20
2
3
5
7
11
13
17
19
2. Program to check whether the entered number is prime or not.
n=int(input("Enter a number:"))
for i in range(2,n+1):
if n%i==0:
break
if i==n:
print(n," is prime number")
else:
print(n," is not a prime number")
Output:
Enter a number:5
5 is prime number
Enter a number:4
4 is not a prime number
3. Program to print and sum of all even numbers between 1 to 20.
sum=0
for i in range(0,21,2):
print(i)
sum=sum+i
print("Sum of Even numbers= ",sum)
Output:
0
2
4
6
8
10
12
14
16
18
Programming with 'Python' 2.17 Python Operators and Control Flow Statements
20
Sum of Even numbers= 110
print()
3. Program to print following pyramid:
1
2 3
4 5 6
7 8 9 1
2 3 4 5 6
count=1
for i in range(1,6):
for j in range(1,i+1):
print(count,end=' ')
count=count+1
if count>9:
count=1
print()
4. Program to print following pyramid:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
count=1
for i in range(1,6):
for j in range(1,i+1):
print(count,end=' ')
count=count+1
print()
5. Program to print pyramid:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
for row in range(1,6):
for sp in range(1,6-row):
print(' ',end=' ')
for col in range(1,row+1):
print(col, end=' ')
for erow in range(col-1,0,-1):
print(erow,end=' ')
print()
• Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
• Loop control statement in Python is basically used to terminate a loop or skip the particular code in
the block or it can also be used to escape the execution of the program.
• The loop control statements in Python programming includes break statement, continue statement
and pass statement.
2.5.1 break Statement
• The break statement in Python terminates the current loop and resumes execution at the next
statement, just like the traditional break found in C.
Syntax: break
Control Flow Diagram for break Statement: Example: For break statement.
i=0
while i<10:
i=i+1
if i==5:
break
print("i= ",i)
Output:
i=1
i=2
i=3
i=4
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
3. Program to find out whether the input number is perfect number or not.
n=int(input("Enter number"))
sum=0
for i in range(1,n):
if n%i==0:
sum=sum+i
if sum==n:
print(n,' is perfect number')
else:
print(n,' is not perfect number')
Output:
Enter number 20
20 is not perfect number
Enter number 28
28 is perfect number
4. Program to generate Student Result. Accept marks of five subject and display result according to
following conditions:
Percentage Division
>=75 First class with Distinction
>=60 and <75 First Class
>=45 and <60 Second Class
>=40 and <45 Pass
<40 Fail
m1=int(input("Enter marks of Subject-1:"))
m2=int(input("Enter marks of Subject-2:"))
m3=int(input("Enter marks of Subject-3:"))
total=m1+m2+m3
per=total/3
print("Total Marks=",total)
print("Percentage=",per)
if per >= 75:
print("Distinction")
elif per >=60 and per<75:
print("First class")
elif per >=45 and per<60:
print("Second class")
elif per >=40 and per<45:
print("Pass")
else:
print("Fail")
Output:
Enter marks of Subject-1:60
Programming with 'Python' 2.22 Python Operators and Control Flow Statements
if num == rev:
print("number is palindrome")
else:
print("number is not palindrome")
Output:
enter a number: 121
number is palindrome
enter a number: 123
number is not palindrome
8. Program to return prime numbers from a list.
list=[3,2,9,10,43,7,20,23]
print("list=",list)
l=[]
print("Prime numbers from the list are:")
for ain list:
prime=True
for i in range(2,a):
if (a%i==0):
prime=False
break
if prime:
l.append(a)
print(l)
Output:
list= [3, 2, 9, 10, 43, 7, 20, 23]
Prime numbers from the list are:
[3, 2, 43, 7, 23]
9. Program to add, subtract, multiply and division of two complex numbers.
print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-0.15517241379310348+0.6379310344827587j)
10. Program to find the best of two test average marks out of three test’s marks accepted from the
user.
n1=int(input('enter a number'))
n2=int(input('enter 2nd number'))
n3=int(input('enter the 3rd number'))
avg1=(n1+n2)/2
avg2=(n2+n3)/2
avg3=(n3+n1)/2
maxm=max(avg1, avg2, avg3)
Programming with 'Python' 2.24 Python Operators and Control Flow Statements
print(maxm)
11. Print patterns of (*) using loop.
(i) for i in range(0, 5):
for j in range(0, i+1):
print("* ",end="")
print("\r")
Output:
*
* *
* * *
* * * *
* * * * *
(ii) for i in range(0, 5):
num = 1
for j in range(0, i+1):
print(num, end=" ")
num = num + 1
print("\r")
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Practice Questions
1. What is operator? Which operators used in Python?
2. What is meant by control flow of a program?
3. Define the terms: (i) Loop, (ii) Program, (iii) Operator, (iv) Control flow.
4. What are the different loops available in Python?
5. What happens if a semicolon (;) is placed at the end of a Python statement?
6. Explain about different logical operators in Python with appropriate examples.
7. Explain about different relational operators in Python with examples.
8. Explain about membership operators in Python.
9. Explain about Identity operators in Python with appropriate examples.
10. Explain about arithmetic operators in Python.
11. List different conditional statements in Python.
12. What are the different nested loops available in Python?
13. What are the different loop control (manipulation) statements available in Python? Explain with
suitable examples.
14. Explain if-else statement with an example.
15. Explain continue statement with an example.
16. Explain use of break statement in a loop with example.
17. Predict output and justify your answer: (i)−11%9 (ii) 7.7//7 (iii) (200-70)*10/5 (iv) 5*1**2.
18. What the difference is between == and is operator in Python?
19. List different operators in Python, in the order of their precedence.
20. Write a Python program to print factorial of a number. Take input from user.
Programming with 'Python' 2.25 Python Operators and Control Flow Statements
21. Write a Python program to calculate area of triangle and circle and print the result.
22. Write a Python program to check whether a string is palindrome.
23. Write a Python program to print Fibonacci series up to n terms.
24. Write a Python program to print all prime numbers less than 256.
25. Write a Python program to find the best of two test average marks out of three test’s marks
accepted from the user.