Comp117 Unit 06
Comp117 Unit 06
Python Programming
by Manoj Shakya
COMP117 - UNIT 6 2
Unit 6 - Loops
COMP117 - UNIT 6 3
Contents
COMP117 - UNIT 6 4
Looping
• Definition:
Loops are control structures that repeat a block of code until a
certain condition is met.
code
• Importance:
• Iterating over data
• Automating repetitive tasks, and
• Efficient code execution. condition
• Two looping statements
• while loop False
True
• for loop
loop body
code
COMP117 - UNIT 6 5
The while statement
COMP117 - UNIT 6 6
Examples (while loop)
COMP117 - UNIT 6 7
Trace Table
LN factorial current number test
1 4
2 1
3 1
5 True
6 1
7 2
5 True
6 2
7 3
5 True
6 6
7 4
5 True
6 24
7 5
5 False
9 24 4
COMP117 - UNIT 6 8
The for statement
COMP117 - UNIT 6 10
The for statement
COMP117 - UNIT 6 11
range(start, stop, step)
mysum = 0
for i in range(7,10):
mysum += i
print(mysum)
mysum = 0
for i in range(5,11,2):
mysum += i
print(mysum)
COMP117 - UNIT 6 12
Examples (for loop w/ Trace Table)
LN sum_of i num i<num num%i
_divis == 0?
ors
2 6
5 0
6 1 True
7 True
8 1
6 2 True
7 True
8 3
6 3 True
Complete yourself!!!
COMP117 - UNIT 6 13
The break statement
mysum = 0
COMP117 - UNIT 6 14
The continue statement
mysum = 0
COMP117 - UNIT 6 15
The pass statement
COMP117 - UNIT 6 16
for vs while loops
COMP117 - UNIT 6 17
Nested loops (while loop)
# Outer loop
i = 1
while i <= 3:
# Inner loop
j = 1
while j <= 3:
print(f"i = {i}, j = {j}")
j += 1
i += 1
COMP117 - UNIT 6 18
Nested loops (for loop)
# Outer loop
for i in range(1, 4):
# Inner loop
for j in range(1, 4):
print(f"i = {i}, j = {j}”)
COMP117 - UNIT 6 19
Let’s practice Lab #6
COMP117 - UNIT 6 20
The end!
COMP117 - UNIT 6 21