Python Programming – Unit 2
Part – 2
Looping
Dr.VIDHYA B
ASSISTANT PROFESSOR & HEAD
Department of Computer Technology
Sri Ramakrishna College of Arts and Science
Coimbatore - 641 006
Tamil Nadu, India
1
DECISION CONTROL STATEMENTS
February 23, 2025 UNIT 2 2
Introduction to Decision Control Statements
- Control Statement determines the control flow of a
set of instruction
- Decides the sequence in which the instructions in
a program are to be executed
- Three fundamental methods of control flow in a
programming language are…
(i) Sequential
(ii) Selection and
(iii) Iterative Process
February 23, 2025 UNIT 2 3
(i) Sequential Flow
“Sequence control structure” refers to the line-by-line
execution by which statements are
executed sequentially, in the same order in which they
appear in the program.
February 23, 2025 UNIT 2 4
(ii) Selection Flow
“Selection Flow” Allows one set of statements to be
executed if a condition is true and another set of actions
to be executed if a condition is false.
February 23, 2025 UNIT 2 5
(iii) Iterative Process
Repeating a sequence or series of instructions over-and-over. When the
computer receives these repeated instructions, it continues to complete the
process until a designated event occurs or until the desired number of
repetitions is over.
February 23, 2025 UNIT 2 6
Selection Statements
Allows to execute statements selectively
based on certain decisions. Hence called as
Selection control statements or conditional
branching statements.
Types of Conditional Branching Statements:
February 23, 2025 UNIT 2 7
If - Statement
- The statements inside the body of “if” execute if the given
condition returns true.
- If the condition returns false then the statements inside “if”
are skipped. if (condition):
- It takes the form…
- if structure may include 1
statements
statement or n statements ……
enclosed within the block.
- Contains header keyword followed
by:
- Group of statements following a
header is called as “Suite”.
Header & Suite together called as
“Clause”
February 23, 2025 UNIT 2 8
If – Statement (Example)
February 23, 2025 UNIT 2 9
if else – Statement
- The else keyword catches anything which isn't
caught by the preceding conditions.
- It takes the form…
if (condition) :
statements
else:
statement
... ... ...
February 23, 2025 UNIT 2 10
if else – Statement
February 23, 2025 UNIT 2 11
if else – Statement
Largest of 2 numbers Odd or Even
February 23, 2025 UNIT 2 12
if..elif..else statements
- if..elif..else statement is used to have multiple
conditions also called as nested-if-constructs
- it takes the following form
Syntax:
Note:
if expression:
Python doesnot
statements
support switch
elif expression:
statement hence
statements
if…elif…else can
else:
be used.
statements
February 23, 2025 UNIT 2 13
if..elif..else statements
February 23, 2025 UNIT 2 14
if elif-else statement - Example
Number negative, positive , equal to
zero Output:
February 23, 2025 UNIT 2 15
Nested if Statement
- placing an if statement inside another statement called as
Compound statement
- If statements can be nested resulting in multi-way
selection
- It takes the form
if condition:
if condition:
statements
else:
statements
else:
statements
February 23, 2025 UNIT 2 16
Nested if Statement
February 23, 2025 UNIT 2 17
Nested if Statement (Example)
mark = 72
if mark > 50:
if mark > = 80:
print ("You got A Grade !!")
elif mark > =60 and mark < 80 :
print ("You got B Grade !!")
else:
print ("You got C Grade !!") Output:
else: You got B Grade!!
print("You failed!!") (Try the Code)
February 23, 2025 UNIT 2 18
LOOP STRUCTURE
- Python supports loop
structures through iterative
statements
- Iterative Statements are
decision control statements
that are used to repeat the
execution of a list of
statement
- Two type of iterative
statements are
(i) while loop
(ii) for loop
February 23, 2025 UNIT 2 19
(i) ‘while’ Loop Structures
- Provides a mechanism to repeat one or more statement
while a particular condition is true. Also referred to top-
checking loop since control
- It takes the form
Statement x
while (condition):
Statement block
Statement y
February 23, 2025 UNIT 2 20
‘while’ Loop Structures (Example)
i= 0
while(i<=10):
print (i, end = “ “)
i=i+1
Output:
0 1 2 3 4 5 6 7 8 9 10
February 23, 2025 UNIT 2 21
‘while’ Loop Structures (Example)
i=0
s=0
while(i<=10):
s=s+i
i = i+1
avg = float(s) / 10
print(“ The sum of first 10 numbers:”, s)
print(“The Average of first 10 numbers:”, avg)
Output:
The sum of first 10 numbers:55
The Average of first 10 numbers: 5.5
February 23, 2025 UNIT 2 22
“for” - Loop
- Provides a mechanism to
repeat a task until a particular
condition is true
- Also called a Determinate loop
or definite loop since the
programmer knows exactly the
number of times the loop will
execute
- It takes the form
for loop_control_var in sequence:
statement block
February 23, 2025 UNIT 2 23
“for” - Loop
- Python syntax uses the range function makes the loop
simpler, expressive and less prone to errors.
- For loop is widely used to execute a single or group of
statements a limited number of times.
- The for.. in statement is a looping statement used in
python to iterate over a sequence of objects.
- Every iteration of the loop make the loop control variable
closer to the end of the range.
- With every iteration the loop variable must be updated.
- Updating makes it to move to the next item in the
sequence.
February 23, 2025 UNIT 2 24
range( ) function of ‘for’ – Loop
- range( ) is a built-in function to iterate over the sequence
of numbers.
- It takes the form
range(begin, end, [step])
- begin is the starting point of the iteration
- end is the last iteration
- [step] is the optional argument, specifies the
increment/decrement value. By default it is 1
- It can be both negative and positive but not zero.
February 23, 2025 UNIT 2 25
range( ) function of ‘for’ – Loop
If range( ) function is given a single argument, it produces,
an object with values from 0 to argument-1.
range(10)is equal to writing - range(0, 10)
If range( ) is called with two arguments, it
produces, values from the first to the second.
range(0,10)
If range( ) has three arguments, then the argument specifies
the interval of the sequence produced. In this case, the third
argument must be an integer.
range(1, 20, 3) =>1, 4, 7, 10, 13, 16, 19
February 23, 2025 UNIT 2 26
“for” – loop (Example)
for i in range(1, 5): for i in range(1, 10):
print(i, end=“ “) print(i, end=“ “)
Output: Output:
1 2 3 4 123456789
for i in range(1, 10, 2): for i in range(1, 20, 3):
print(i, end = “ “) print(i, end=“ “)
Output: Output:
1 3 5 7 9 1 4 7 10 13 16 19
for i in range(10): color =[“red”, ”blue”, “green”]
for x in color:
print(i, end=“ “) print(x)
Output: Output:
0 123456789 red blue green
February 23, 2025 UNIT 2 27
‘for’ – Loop (Example)
Output:
n= int(input(“Enter any number:”)) Enter any number: 2
Multiplication Table
print(“Multiplication Table”) *****************
print(“******************”) 2x1=2
2x2=4
for i in range(1,11): 2x3=6
print(n, “x”, i, “=“, n*i) 2x4=8
.
.
.
.
2 x 10 = 20
February 23, 2025 UNIT 2 28
Nested Loop
- Nested loop is a loop that can be placed inside another
loop.
- A “for” loop can be used to control the number of times a
particular set of statements will be executed.
- Another outer loop could be used to control the number of
times that a whole loop is repeated.
- Loops can be nested to any desired level, with proper
indention level.
February 23, 2025 UNIT 2 29
Nested Loop (Example)
for i in range(5): for i in range(1,6):
print( ) print( )
for j in range(10): for j in range(1, i+1):
print(“*”) print(j)
Output:
Output:
**********
1
**********
12
**********
123
**********
1234
**********
12345
February 23, 2025 UNIT 2 30
February 23, 2025 UNIT 2 31
The ‘Break’ Statement
- Is used to terminate the loop in a specified iteration
- widely used with ‘for’ loop and ‘while’ loop.
i=1
while i < = 10:
print(i, end=“ “)
if i= = 5 1 2 3 4 5
Done
break
i= i+1
print(“\n Done”)
February 23, 2025 UNIT 2 32
The ‘continue’ Statement
- Is used to skip the specified iteration in a loop
i=1
while i < = 10:
print(i, end=“ “)
if i= = 5 1 2 3 4 6 7 8 9 10
Done
continue
i= i+1
print(“\n Done”)
February 23, 2025 UNIT 2 33
The ‘pass’ Statement
- Used when a statement is required syntactically but no
command or code has to be executed
- Specifies a null operation or simply ‘No Operation’
statement.
- Nothing happens when a pass statement is executed
H
for letter in “HELLO”: E
L
pass L
print(letter) O
February 23, 2025 UNIT 2 34
Looping Statements (Example)
count = 0 print("\nString Iteration")
while (count < 3): s = “India"
count = count+1 for i in s :
print(“SRCAS") print(i)
Output:
Output:
I
SRCAS
n
SRCAS
d
SRCAS
i
a
February 23, 2025 UNIT 2 35
Looping Statements (Example)
print("\nDictionary Iteration") for letter in ‘sunilsamson':
d = dict() if letter == ‘s' or letter == ‘a':
d['xyz'] = 123 continue
d['abc'] = 345 print 'Current Letter :', letter
for i in d :
print("%s %d" (i, d[i])) Output:
Current Letter : u
Output: Current Letter : n
Current Letter : i
Dictionary Iteration Current Letter : l
xyz 123 Current Letter : m
abc 345 Current Letter :o
Current Letter : n
February 23, 2025 UNIT 2 36
Looping Statements (Example)
for i in range(1, 5): student_name = 'Suresh'
for j in range(i): marks = {'James': 90, 'Julie': 55, 'Arthur': 77}
for student in marks:
print(i, end=' ')
if student == student_name:
print() print(marks[student])
break
else:
print('No entry with that name found.')
Output:
Output:
1
22
No entry with that name found.
333
4 4 4February
4 23, 2025 UNIT 2 37
Looping Statements (Example)
for n in range(2, 10):
for x in range(2, n):
Output:
if n % x == 0:
2 is a prime number
print(n, 'equals', x, '*', n//x) 3 is a prime number
break 4 equals 2 * 2
else: 5 is a prime number
print(n, 'is a prime number') 6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
February 23, 2025 UNIT 2 38