๐ Exercise Seven: Looping Structures
One of the most powerful features of programming is the ability to repeat a block of code multiple times. This is called looping (or iteration). Python provides two main types of loops: the while loop and the for loop. Each has its strengths, and knowing when to use which will make you a more effective programmer.
- The two types of loops in Python:
whileandfor - How to use the
range()function withforloops - When to use each type of loop
- How to control loops with
breakandcontinue - How to nest loops inside each other
Think of it this way: sometimes you know exactly how many times you want to repeat something (like "do this 10 times"), and sometimes you don't know in advanceโyou just want to keep going until something happens (like "keep asking until the user types 'quit'"). Python gives you the right tool for each situation!
๐บ๏ธ 1. Overview: Two Types of Loops
| Loop Type | Best Used When... | Basic Structure |
|---|---|---|
while |
You don't know how many iterations you need; loop continues until a condition becomes false | while condition: |
for |
You know how many iterations you need, or you're iterating over a sequence | for variable in range(): |
- Know the number of iterations? โ Use
for - Don't know when to stop? โ Use
while
๐ 2. The while Loop (Review)
You've already learned about the while loop in Exercise Five. Let's quickly review it before introducing the for loop.
while condition:
# code to repeat
# update the condition variable!Example: Counting with while
# Count from 1 to 5 using while
count = 1
while count <= 5:
print(count)
count += 1
print("Done!")2
3
4
5
Done!
Key Characteristics of while Loops
- Condition checked first: The condition is checked before each iteration
- May not run at all: If the condition is false initially, the loop body never executes
- Manual update required: You must update the loop variable yourself to avoid infinite loops
- Flexible: Can be used when you don't know how many iterations you'll need
๐ข 3. The for Loop
The for loop is Python's way of iterating a specific number of times. It's often simpler and cleaner than a while loop when you know in advance how many iterations you need.
for variable in range(n):
# code to repeat n timesYour First for Loop
# Print "Hello" 5 times
for i in range(5):
print("Hello")Hello
Hello
Hello
Hello
How Does This Work?
range(5)generates the sequence: 0, 1, 2, 3, 4- The loop runs once for each value in the sequence
- Each time through, the variable
itakes on the next value - After the last value (4), the loop ends
Using the Loop Variable
The loop variable (commonly named i) holds the current value from the range:
# See what values i takes
for i in range(5):
print("i =", i)i = 1
i = 2
i = 3
i = 4
range(5) starts at 0 and goes up to but does not include 5. This is a common pattern in programming called "zero-indexing."
๐ 4. The range() Function
The range() function is your best friend when using for loops. It generates a sequence of numbers that the loop iterates through.
Three Ways to Use range()
| Syntax | Description | Example | Produces |
|---|---|---|---|
range(stop) |
0 to stop-1 | range(5) |
0, 1, 2, 3, 4 |
range(start, stop) |
start to stop-1 | range(1, 6) |
1, 2, 3, 4, 5 |
range(start, stop, step) |
start to stop-1, counting by step | range(0, 10, 2) |
0, 2, 4, 6, 8 |
Example: range(stop) - One Argument
# Count from 0 to 4
for i in range(5):
print(i)1
2
3
4
Example: range(start, stop) - Two Arguments
# Count from 1 to 5
for i in range(1, 6):
print(i)2
3
4
5
Example: range(start, stop, step) - Three Arguments
# Count by 2s from 0 to 10
for i in range(0, 11, 2):
print(i)2
4
6
8
10
Counting Backwards
Use a negative step to count down:
# Countdown from 5 to 1
for i in range(5, 0, -1):
print(i)
print("Blastoff!")4
3
2
1
Blastoff!
stop value is still excluded. So range(5, 0, -1) goes from 5 down to 1 (not 0).
โ๏ธ 5. Comparing while and for
Let's see the same task done with both types of loops:
Task: Print the numbers 1 through 5
while:
count = 1
while count <= 5:
print(count)
count += 1for:
for count in range(1, 6):
print(count)Both produce the same output:
2
3
4
5
for is Often Better for Counting:
- Shorter and cleaner code
- No need to initialize the counter variable before the loop
- No need to manually increment the counter
- No risk of forgetting to update the counter (infinite loop impossible)
When to Use Which?
| Situation | Best Choice | Why? |
|---|---|---|
| Repeat exactly N times | for |
Cleaner, automatic counting |
| Count through a range of numbers | for |
Built-in range() makes it easy |
| Repeat until user says stop | while |
Don't know iterations in advance |
| Input validation (keep asking until valid) | while |
Don't know how many tries needed |
| Game loop (play until game over) | while |
Condition-based termination |
| Process data until end | while |
Unknown amount of data |
๐ฎ 6. Loop Control: break and continue
Sometimes you need more control over your loops. Python provides two special keywords to help:
The break Statement
The break statement immediately exits the loop, skipping any remaining iterations.
# Find the first number divisible by 7 between 1 and 100
for num in range(1, 101):
if num % 7 == 0:
print("Found it:", num)
break
print("Loop finished")Loop finished
What happened? When num reached 7, the condition was true, so the program printed the number and then break immediately exited the loopโit didn't continue checking 8, 9, 10, etc.
Example: break with while
# Keep asking for password, but allow only 3 attempts
secret = "python123"
attempts = 0
while True: # Infinite loop - we'll use break to exit
password = input("Enter password: ")
attempts += 1
if password == secret:
print("Access granted!")
break
if attempts >= 3:
print("Too many attempts. Locked out!")
break
print("Wrong password. Try again.")Wrong password. Try again.
Enter password: secret
Wrong password. Try again.
Enter password: python123
Access granted!
The continue Statement
The continue statement skips the rest of the current iteration and moves to the next one.
# Print numbers 1-10, but skip multiples of 3
for i in range(1, 11):
if i % 3 == 0:
continue # Skip this iteration
print(i)2
4
5
7
8
10
What happened? When i was 3, 6, or 9, the continue statement skipped the print(i) and went straight to the next iteration.
Comparison: break vs continue
| Statement | What It Does | Loop Continues? |
|---|---|---|
break |
Exits the loop completely | No - loop ends immediately |
continue |
Skips to the next iteration | Yes - with the next value |
break when you've found what you're looking for and want to stop. Use continue when you want to skip certain items but keep processing the rest.
๐ช 7. Nested Loops
You can put one loop inside another. This is called nesting. The inner loop runs completely for each iteration of the outer loop.
Basic Nested Loop Example
# Outer loop runs 3 times
for i in range(1, 4):
print("Outer loop: i =", i)
# Inner loop runs 2 times for EACH outer iteration
for j in range(1, 3):
print(" Inner loop: j =", j)
print() # Blank line for clarityInner loop: j = 1
Inner loop: j = 2
Outer loop: i = 2
Inner loop: j = 1
Inner loop: j = 2
Outer loop: i = 3
Inner loop: j = 1
Inner loop: j = 2
The outer loop runs 3 times (i = 1, 2, 3). For each of those 3 times, the inner loop runs completely (j = 1, 2). So the inner print statement executes 3 ร 2 = 6 times total.
Example: Multiplication Table
# Print a multiplication table (1-5)
print("Multiplication Table")
print("=" * 30)
for i in range(1, 6):
for j in range(1, 6):
product = i * j
print(str(i) + " x " + str(j) + " = " + str(product))
print() # Blank line after each row==============================
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
...
Example: Pattern Printing
# Print a right triangle of stars
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end="") # end="" prevents newline
print() # Move to next line after each row**
***
****
*****
end="" parameter in print() prevents it from adding a newline after each print. This lets us print multiple characters on the same line.
๐ฏ 8. Complete Examples
Example 1: Sum Calculator with for
# Calculate the sum of numbers from 1 to N
n = int(input("Enter a positive integer: "))
total = 0
for i in range(1, n + 1):
total += i
print("The sum of 1 to " + str(n) + " is: " + str(total))The sum of 1 to 10 is: 55
Example 2: Find Factors
# Find all factors of a number
number = int(input("Enter a positive integer: "))
print("Factors of " + str(number) + ":")
for i in range(1, number + 1):
if number % i == 0:
print(i)Factors of 12:
1
2
3
4
6
12
Example 3: Prime Number Checker
# Check if a number is prime
number = int(input("Enter a positive integer: "))
if number < 2:
print(str(number) + " is not prime")
else:
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
if is_prime:
print(str(number) + " is prime")
else:
print(str(number) + " is not prime")17 is prime
Example 4: Guessing Game with Limited Tries
# Number guessing game with for loop (limited attempts)
import random
secret = random.randint(1, 20)
max_guesses = 5
won = False
print("I'm thinking of a number between 1 and 20.")
print("You have " + str(max_guesses) + " guesses.")
print()
for attempt in range(1, max_guesses + 1):
guess = int(input("Guess " + str(attempt) + ": "))
if guess == secret:
print("Correct! You won in " + str(attempt) + " guesses!")
won = True
break
elif guess < secret:
print("Too low!")
else:
print("Too high!")
if not won:
print("Sorry! The number was " + str(secret))You have 5 guesses.
Guess 1: 10
Too low!
Guess 2: 15
Too high!
Guess 3: 12
Correct! You won in 3 guesses!
Example 5: Using Nested Loops with Functions
def print_rectangle(width, height, character):
"""Print a rectangle of the given dimensions"""
for row in range(height):
for col in range(width):
print(character, end="")
print() # New line after each row
# Main program
print("Rectangle 1:")
print_rectangle(5, 3, "*")
print()
print("Rectangle 2:")
print_rectangle(8, 2, "#")*****
*****
*****
Rectangle 2:
########
########
โ ๏ธ Common Mistakes (And How to Fix Them)
Mistake 1: Off-by-One with range()
for i in range(1, 5): # Stops at 4!
print(i)for i in range(1, 6): # Goes up to 5
print(i)Mistake 2: Modifying Loop Variable in for Loop
for i in range(5):
print(i)
i += 10 # This has no effect on the next iteration!while if you need to modify the counter:
i = 0
while i < 50:
print(i)
i += 10Mistake 3: Forgetting range() in for Loop
for i in 5: # ERROR! Can't iterate over an integer
print(i)for i in range(5): # Use range() to generate sequence
print(i)Mistake 4: Using break Outside a Loop
x = 5
if x > 3:
break # ERROR! break only works inside loopsfor i in range(10):
if i > 3:
break # Works - inside a loopMistake 5: Wrong Indentation in Nested Loops
for i in range(3):
for j in range(3):
print(i, j) # Wrong! Should be indented morefor i in range(3):
for j in range(3):
print(i, j) # Properly indented inside inner loopโ๏ธ Practice Exercises
Try writing these programs on your own!
Exercise 1: Sum of Even Numbers
Write a program using a for loop that calculates the sum of all even numbers from 2 to 100.
Hint: Use range(2, 101, 2) to generate even numbers.
Exercise 2: Factorial Calculator
Write a program that:
- Asks the user for a non-negative integer N
- Calculates N! (N factorial) using a
forloop - Displays the result
Remember: 5! = 5 ร 4 ร 3 ร 2 ร 1 = 120, and 0! = 1
Exercise 3: FizzBuzz
Write a program that prints the numbers 1 to 50, but:
- For multiples of 3, print "Fizz" instead of the number
- For multiples of 5, print "Buzz" instead of the number
- For multiples of both 3 and 5, print "FizzBuzz"
Exercise 4: Number Pyramid
Write a program that prints a number pyramid like this:
12
123
1234
12345
Hint: Use nested for loops.
Exercise 5: Prime Numbers in Range
Write a program that:
- Asks the user for two numbers (start and end)
- Prints all prime numbers between start and end
Hint: Create a function is_prime(n) and call it in your loop.
Exercise 6: Menu-Driven Calculator
Write a program with a menu that lets the user:
- Add two numbers
- Subtract two numbers
- Multiply two numbers
- Divide two numbers
- Exit the program
Use a while loop to keep showing the menu until the user chooses to exit.
๐ Quick Reference
Loop Structures
while loop:
while condition:
# code to repeat
# update condition!for loop:
for var in range(n):
# code runs n timesrange() Function
range(5)
# 0, 1, 2, 3, 4range(1, 6)
# 1, 2, 3, 4, 5range(0, 10, 2)
# 0, 2, 4, 6, 8range(5, 0, -1)
# 5, 4, 3, 2, 1Loop Control
break:
break # Exit loop nowcontinue:
continue # Skip to nextโญ Key Takeaways
- โ
whileloops repeat while a condition is trueโuse when you don't know how many iterations - โ
forloops repeat for a specific number of timesโuse when you know the count - โ
range(n)generates numbers from 0 to n-1 - โ
range(start, stop)generates numbers from start to stop-1 - โ
range(start, stop, step)lets you count by any increment (including negative) - โ
breakexits a loop immediately - โ
continueskips to the next iteration - โ Nested loops: the inner loop runs completely for each iteration of the outer loop
- โ Always indent code inside loops (and indent again for nested structures)
โ Need Help?
If your program doesn't work, check these common issues:
- TypeError: 'int' object is not iterableโDid you forget
range()in yourforloop? - Off-by-one errorsโRemember that
range()excludes the stop value - Infinite
whileloopโAre you updating the condition variable inside the loop? - 'break' outside loopโ
breakandcontinueonly work inside loops - Nested loop not workingโCheck your indentation carefully
for i in range(5):
print("DEBUG: i =", i) # See the loop variable
# rest of your codefor loop is perfect when you know how many times to repeat, while the while loop shines when you need to repeat until some condition is met. Master both, and you'll be able to tackle almost any repetitive task in programming!