Loops in Python
Doing repetitive tasks the smart way
A hands-on class on for loops, while loops & debugging
Why Do We Need Loops?
A loop repeats a block of code many times — without you rewriting it.
THE LONG WAY THE SMART WAY
print("Hi") for i in range(5):
print("Hi")
print("Hi") → print("Hi")
print("Hi")
print("Hi")
Like washing 10 plates — repeat
the same steps, don't invent a
new way each time.
Two Types of Loops
for while
Count-controlled Condition-controlled
Use when you know how many times to Use when repetition depends on a
repeat, or you're going through a condition and you don't know in
sequence — a list, a string, or a range. advance how many times it will run.
For Loop: Syntax
THE PATTERN
for variable in sequence:
# code to repeat
IN ACTION
for i in range(5):
print(i)
For Loop: Dry Run
Walk through the loop one pass at a time — watch i change.
Iteration i Output
for i in range(5): 1 0 0
print(i)
2 1 1
3 2 2
Each pass gives i the next value from
range, then runs the body. 4 3 3
5 4 4
While Loop: Syntax
THE PATTERN
while condition:
# code to repeat
# update statement (important!)
IN ACTION
i = 0
while i < 5:
print(i)
i += 1
For vs While: Which One?
for while
Known count Unknown count
Use it when the number of repetitions Use it when repeating depends on a
is known, or you're iterating over condition. Example: keep asking until
something — a list, a string, a range. the user enters the correct password.
IN-CLASS PROBLEM 1
Multiplication Table
EASY
Print the multiplication table (1–10) of a number entered
by the user.
Solution: Multiplication Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
IN-CLASS PROBLEM 2
Sum of Digits
MEDIUM
Using a while loop, find the sum of the digits of a number.
Example: 123 → 1 + 2 + 3 = 6
Solution: Sum of Digits
num = int(input("Enter a number: "))
total = 0
while num > 0: Output
digit = num % 10
123
total += digit → 6
num = num // 10
print("Sum of digits:", total)
IN-CLASS PROBLEM 3
Prime Numbers 1–N
HARD
Using nested loops, print all prime numbers between 1 and
N.
Solution: Prime Numbers
n = int(input("Enter N: "))
for num in range(2, n + 1):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)
Predict the Output · Q1
for i in range(3):
print(i * 2)
What will this print?
Predict the Output · Q2
i = 5
while i > 0:
print(i)
i -= 2
What will this print?
Spot the Bug · Q1
i = 0
while i < 5:
print(i)
What's wrong with this code?
Spot the Bug · Q2
count = 10
while count > 0:
print(count)
count += 1
What's wrong with this code?
Spot the Bug · Q3
while i < 5:
print(i)
i = 0
What's wrong with this code?
Assignment
Practice these on your own before the next class.
1 Multiplication tables 1–10
2 Factorial of a number
3 Reverse a number
4 Count vowels in a string
Thank You!
Any questions before we move to hands-on practice?