Imagine you need to print "Hello" 100 times. Would you write 100 print() statements? Of course not! That's what for loops are for โ they let you repeat code a specific number of times.
for Loop with range()Syntax:
for variable in range(count):
# code to repeat
Example โ repeat 5 times:
for i in range(5):
print("Hello!")
Output:
Hello!
Hello!
Hello!
Hello!
Hello!
range(5) generates the numbers 0, 1, 2, 3, 4. The loop runs once for each number. The variable i takes each value in turn.
Example โ print the loop variable:
for i in range(5):
print(f"Iteration {i}")
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
for loop that prints "Python is fun!" 8 times.for loop that prints the numbers 0 to 9.range(start, stop, step)Syntax:
range(start, stop) # from start to stop-1
range(start, stop, step) # with custom step
Example โ start at 1, stop before 6:
for i in range(1, 6):
print(i, end=" ") # 1 2 3 4 5
Example โ count by 2s:
for i in range(2, 11, 2):
print(i, end=" ") # 2 4 6 8 10
Example โ count down:
for i in range(10, 0, -1):
print(i, end=" ") # 10 9 8 ... 1
print("๐ Blast off!")
range(start, stop, step) stops before reaching stop. So range(1, 6) gives 1,2,3,4,5 (not 6).
Syntax โ for-each style:
for item in list:
print(item)
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}s!")
Output:
I love apples!
I love bananas!
I love cherries!
Using index โ range(len()):
numbers = [10, 20, 30, 40]
for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
nums = [5, 10, 15, 20], write a loop that prints each number doubled (10, 20, 30, 40).enumerate() โ Index and Value Togetherstudents = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(students):
print(f"Student {i+1}: {name}")
Output:
Student 1: Alice
Student 2: Bob
Student 3: Charlie
enumerate() to print a shopping list with numbered items.break and continuebreak โ exit the loop immediately:
for i in range(10):
if i == 5:
break # stop when i reaches 5
print(i, end=" ") # 0 1 2 3 4
continue โ skip to the next iteration:
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i, end=" ") # 1 3 5 7 9
break).continue).Now that you understand the basic for loop, let's look at two essential exam patterns.
Totalling โ add up values:
total = 0
for score in [45, 78, 92, 60, 55]:
total = total + score # or total += score
print(f"Total: {total}") # 330
Counting โ count how many match a condition:
count = 0
for score in [45, 78, 92, 60, 55]:
if score >= 50:
count = count + 1 # or count += 1
print(f"Passed: {count}") # 4
0 before the loop. Update it inside the loop.
Combined โ find average:
scores = [45, 78, 92, 60, 55]
total = 0
count = 0
for s in scores:
total += s
count += 1
average = total / count
print(f"Average: {average:.1f}") # 66.0
for loop to calculate the sum of all numbers from 1 to 50.[12, 7, 9, 15, 4, 20, 3] are greater than 10.[8, 12, 15, 9, 11].IGCSE pseudocode has a loop that always runs at least once. In Python, we use while True + break:
# Pseudocode equivalent:
# REPEAT
# OUTPUT "Enter a positive number:"
# INPUT num
# UNTIL num > 0
while True:
num = int(input("Enter a positive number: "))
if num > 0:
break
print("Try again!")
A while loop keeps running as long as a condition is True. Unlike for (which runs a fixed number of times), while is perfect when you don't know how many iterations you'll need.
while LoopSyntax:
while condition:
# code to repeat
Example โ count to 5:
count = 0
while count < 5:
print(f"Count is {count}")
count = count + 1 # ๐ Don't forget to update!
Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
False. If you forget count += 1, the loop runs forever! Press Ctrl+C to stop an infinite loop.
while loop that prints numbers from 10 down to 1.while loop that prints "Keep going!" 5 times.while with User InputA very common use โ keep asking until the user gives valid input.
num = 0
while num <= 0:
num = int(input("Enter a positive number: "))
if num <= 0:
print("That's not positive! Try again.")
print(f"Thanks! You entered {num}")
while loop that keeps asking "Are we there yet?" until the user types "yes".while vs for โ When to Use WhichUse for | Use while |
|---|---|
| You know the number of iterations | You're waiting for a condition |
| Looping through a list/range | Reading input until valid |
| Counting or iterating | Number guessing, game loops |
while loop is better than a for loop.break to Exit a While Loopwhile True:
cmd = input("Enter command ('quit' to exit): ")
if cmd == "quit":
break
print(f"Executing: {cmd}")
while True creates an infinite loop โ but break lets you exit from inside.
Now that you understand the basic while loop, here's the key exam pattern:
# Enter scores until -1, then show average
total = 0
count = 0
score = int(input("Enter score (-1 to stop): "))
while score != -1:
total += score
count += 1
score = int(input("Enter score (-1 to stop): "))
if count > 0:
print(f"Total: {total}")
print(f"Average: {total/count:.1f}")
else:
print("No scores entered.")
Finding the first match:
# Find the first number divisible by 7
num = 1
while num % 7 != 0:
num += 1
print(f"The first multiple of 7 is {num}") # 7
while loop to keep entering numbers until the user types 0, then print the total.while loop to find the smallest number whose square is greater than 1000.while loop to reverse a number (e.g., 12345 โ 54321).while loop to print the Fibonacci sequence up to 1000.