Loops Jump to this section
Loops let your program repeat code so you don't have to write the same lines again and again.
while Loops
Jump to this section
A while loop:
- checks if a condition is
True - If it is, it runs the code inside
- Returns to step 1 and repeats until
False
count = 0 # start at 0
while count < 3: # keep looping while this is True
print("count is", count)
count += 1 # add 1 to the count
# Output:
# count is 0
# count is 1
# count is 2
Be careful to change the condition inside the loop (or the loop may never stop).
Everything indented under the loop runs repeatedly.
Any code not indented is not part of the loop and will be run once the loop finishes.
count = 0
while count < 3:
print("loop is still running")
count += 1
print("loop is finished")
for Loops
Jump to this section
Use for to run a block once for each item in a sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
You can read a this loop like this:
“For each fruit in fruits, print the fruit”
Use range() to loop a certain number of times:
range(5) # 0,1,2,3,4
range(2, 8) # 2,3,4,5,6,7
for i in range(5):
print(i) # i will be 0,1,2,3,4
Rule:
range(a, b)includesabut stops beforeb
Use enumerate() when you need both the position and the value.
for index, value in enumerate(fruits):
print(index, value)
break and continue
Jump to this section
breakexits the loop immediately.continueskips the rest of the current iteration and moves to the next one.
for i in range(10):
if i == 3:
continue # skip the rest of this loop
if i == 7:
break # exit the loop completely
print(i)
# Output:
# 0
# 1
# 2
# 4
# 5
# 6
Iterating Different Types Jump to this section
You can loop over strings (characters), lists, tuples, dictionaries, and more.
for character in "hello":
print(character)
# this loops through each character in hello, and sets character equal to the letter
# output:
# h
# e
# l
# l
# o
When looping over a dictionary, Python gives you the keys by default.
for key, value in d.items():
print(key, value)
Nested Loops Jump to this section
Loops can be inside other loops. Keep them simple to avoid confusion.
for i in range(3):
for j in range(2):
print(i, j)
Common Mistakes Jump to this section
- Forgetting to update the condition in a
whileloop (infinite loop). - Modifying the loop variable unexpectedly inside a
forloop.
# Infinite loop
count = 0
while count < 3:
print(count)
This never stops because count is never changed.
Simple challenge Jump to this section
Write a short program that asks the user for a number n and prints the numbers from 1 to n (make sure n is printed).
Hint
Use range(1, n+1) and a for loop, and remember to convert the input to an integer with int().
Show example solution
n = int(input("Enter n: "))
for i in range(1, n+1):
print(i)
# the range() function only goes to 1 before the 2nd number ( range(a, b) only goes to b-1 )
# this means you need to add 1 to n to make sure that n gets printed
Advanced Challenge Jump to this section
Write a program that asks for a number n and prints the numbers from 1 to n, skipping multiples of 3 and stopping early if you reach a number greater than 50.
Hint 1
Use range(1, n+1) to get numbers 1..n. Use if and % to test multiples of 3.
Hint 2
Use continue to skip multiples of 3 and break to stop when the number is greater than 50.
Show example solution
n = int(input("Enter n: "))
for i in range(1, n+1):
if i % 3 == 0: # check whether i is divisible by 3, and only continue if it isn't
continue
if i > 50:
break
print(i)
Key takeaways Jump to this section
- Use
forto iterate over sequences andwhilefor condition-based repetition. range()generates sequences of numbers and is commonly used withfor.- Use
breakto exit a loop andcontinueto skip to the next iteration. - Watch for infinite loops with
while, always ensure the loop condition will eventually become False. - Keep loops short and readable; prefer small helper functions when logic gets complex.
