Imagine: you need to print numbers from 1 to 1000. Write 1000 print() calls? š±
Loops are the superpower of programming! They let you repeat actions as many times as you like.
š¤ Why do we need loops?
Without loops (100 lines):
print(1)
print(2)
print(3)
print(4)
print(5)
# ... 95 more lines
print(100)
With loops (2 lines):
for i in range(1, 101):
print(i)
The difference is obvious! š
š Two types of loops in Python
Python provides two main loop types:
whileā repeat while a condition holds (unknown count)forā iterate over each element (known count)
Let’s look at both!
1ļøā£ The WHILE loop ā “as long as”
Syntax:
while condition:
code to execute
Logic: While the condition is True ā run the code. When it’s False ā stop.
Simple example ā countdown:
count = 10
while count > 0:
print(count)
count -= 1 # count = count - 1
print("š Liftoff!")
What happens:
1. count = 10 ā 10 > 0 ā True ā prints 10, sets count to 9
2. count = 9 ā 9 > 0 ā True ā prints 9, sets count to 8
3. ⦠continues ā¦
4. count = 0 ā 0 > 0 ā False ā loop stops!
ā ļø Beware of infinite loops:
# ā NEVER DO THIS:
count = 10
while count > 0:
print(count)
# Forgot count -= 1 !
# This loop runs forever! š±
Stuck in an infinite loop? Press Ctrl+C to stop the program.
Example ā keep asking until the correct password:
password = ""
while password != "python123":
password = input("Enter password: ")
if password != "python123":
print("ā Wrong, try again")
print("ā
Access granted!")
The loop continues while the password is wrong.
Example ā game with while:
health = 100
while health > 0:
action = input("Action (attack/defend/run): ")
if action == "attack":
print("āļø You attacked!")
health -= 20
elif action == "defend":
print("š”ļø You're defending!")
elif action == "run":
print("š You ran away!")
break # Exit the loop
print(f"š Health: {health}")
if health <= 0:
print("ā ļø Game over")
2ļøā£ The FOR loop ā “for each”
Syntax:
for element in sequence:
code to execute
for is more convenient when you know how many times to repeat or what to iterate over.
š Option 1: for with range()
range(n) generates a sequence of numbers from 0 to n-1
for i in range(5):
print(f"Iteration {i}")
# Prints:
# Iteration 0
# Iteration 1
# Iteration 2
# Iteration 3
# Iteration 4
range() has 3 forms:
range(5) # 0, 1, 2, 3, 4
range(1, 6) # 1, 2, 3, 4, 5 (from start up to stop-1)
range(0, 10, 2) # 0, 2, 4, 6, 8 (step of 2)
range(10, 0, -1) # 10, 9, 8...1 (counting down)
Example ā multiplication table:
number = int(input("Enter a number: "))
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")
š Option 2: for with a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I love {fruit}! š")
Python automatically picks each element from the list!
š Option 3: for with a string
word = "PYTHON"
for letter in word:
print(letter)
# P
# Y
# T
# H
# O
# N
Each character is processed individually!
Example ā count vowels:
text = input("Enter text: ")
vowels = "aeiou"
count = 0
for char in text.lower():
if char in vowels:
count += 1
print(f"Number of vowels: {count}")
š BREAK ā early exit
break immediately stops the loop.
Example ā find a number:
numbers = [3, 7, 12, 5, 18, 9]
for num in numbers:
if num > 10:
print(f"Found a large number: {num}")
break # Found it, exit!
print(f"Checking {num}...")
# Prints:
# Checking 3...
# Checking 7...
# Found a large number: 12
After break the loop terminates entirely, even if elements remain.
Example ā exit an infinite loop:
while True: # Infinite loop!
answer = input("Continue? (yes/no): ")
if answer == "no":
break # Exit
print("Continuing...")
print("Program finished")
āļø CONTINUE ā skip an iteration
continue skips the current iteration and moves to the next one.
Example ā print only even numbers:
for i in range(10):
if i % 2 != 0: # If odd
continue # Skip it
print(i) # Only even numbers reach here
# Prints: 0, 2, 4, 6, 8
Difference between break and continue:
# BREAK ā exits entirely:
for i in range(5):
if i == 3:
break
print(i)
# Prints: 0, 1, 2 (stopped at 3)
# CONTINUE ā skips one iteration:
for i in range(5):
if i == 3:
continue
print(i)
# Prints: 0, 1, 2, 4 (skipped 3, kept going)
Example ā filter a list:
names = ["Anna", "Bob", "Alice", "Boris", "Andrew"]
print("Names starting with A:")
for name in names:
if not name.startswith("A"):
continue # Skip names that don't start with A
print(name)
# Prints: Anna, Alice, Andrew
šÆ Nested loops ā a loop inside a loop
A loop can contain another loop!
Example ā grid of stars:
size = 5
for row in range(size):
for col in range(size):
print("ā", end="")
print() # New line
# āāāāā
# āāāāā
# āāāāā
# āāāāā
# āāāāā
What happens:
- The outer loop (row) runs 5 times
- For each row ā the inner loop (col) runs 5 times
- Total: 5 Ć 5 = 25 iterations!
Example ā triangle:
for row in range(1, 6):
for col in range(row):
print("ā²", end="")
print()
# ā²
# ā²ā²
# ā²ā²ā²
# ā²ā²ā²ā²
# ā²ā²ā²ā²ā²
Example ā Pythagorean multiplication table:
print(" ", end="")
for i in range(1, 6):
print(f"{i:3}", end="")
print()
for i in range(1, 6):
print(f"{i:2} |", end="")
for j in range(1, 6):
print(f"{i*j:3}", end="")
print()
# 1 2 3 4 5
# 1 | 1 2 3 4 5
# 2 | 2 4 6 8 10
# 3 | 3 6 9 12 15
# 4 | 4 8 12 16 20
# 5 | 5 10 15 20 25
š while vs for comparison
| Criterion | while | for |
|---|---|---|
| When to use | Unknown iteration count | Known count |
| Condition | Checked each iteration | Iterates over a sequence |
| Risk | Infinite loop | Safer |
| Examples | Game loops, user input | Iterating lists, range() |
| Readability | Flexible | Concise |
Choosing which to use:
Use WHILE when:
- You don’t know how many iterations are needed
- The condition depends on what happens inside the loop
- You need an infinite loop with a break
Use FOR when:
- You’re iterating over a list / string / range
- You know the exact number of iterations
- You need to visit every element
š” Useful techniques
1. enumerate() ā index + element:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index+1}. {fruit}")
# 1. apple
# 2. banana
# 3. orange
2. Iterating over a dictionary:
student = {"name": "Anna", "age": 20, "year": 2}
for key, value in student.items():
print(f"{key}: {value}")
# name: Anna
# age: 20
# year: 2
3. else after a loop:
for i in range(5):
if i == 10: # Never True
break
else:
print("Loop completed without break")
else runs only if the loop was not interrupted by break.
4. Range with a step:
# Even numbers:
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Reverse order:
for i in range(10, 0, -1):
print(i) # 10, 9, 8...1
š® Practical examples
1. Calculator with a loop:
while True:
print("\nš§® Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = input("Choice: ")
if choice == "5":
print("Goodbye!")
break
if choice in ["1", "2", "3", "4"]:
a = float(input("First number: "))
b = float(input("Second number: "))
if choice == "1":
print(f"Result: {a + b}")
elif choice == "2":
print(f"Result: {a - b}")
elif choice == "3":
print(f"Result: {a * b}")
elif choice == "4":
if b != 0:
print(f"Result: {a / b}")
else:
print("ā Division by zero!")
else:
print("ā Invalid choice")
2. FizzBuzz ā the classic exercise:
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
3. Password generator:
import random
import string
length = int(input("Password length: "))
password = ""
for i in range(length):
char = random.choice(string.ascii_letters + string.digits)
password += char
print(f"Your password: {password}")
4. Find prime numbers:
n = int(input("Find primes up to: "))
for num in range(2, n+1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
ā ļø Common mistakes
1. Missing indentation:
# ā Wrong:
for i in range(5):
print(i) # SyntaxError!
# ā
Correct:
for i in range(5):
print(i)
2. Modifying the loop counter inside a for loop:
# ā Don't do this:
for i in range(5):
print(i)
i = 10 # Has no effect on the loop!
# ā
Use while instead:
i = 0
while i < 5:
print(i)
i += 1 # Works correctly
3. Forgetting to update the variable in while:
# ā Infinite loop:
i = 0
while i < 5:
print(i)
# Forgot i += 1
# ā
Correct:
i = 0
while i < 5:
print(i)
i += 1
4. Wrong range:
# ā range(5, 1) ā prints nothing:
for i in range(5, 1):
print(i)
# ā
Need a step of -1:
for i in range(5, 1, -1):
print(i) # 5, 4, 3, 2
š Summary
Loops are a fundamental building block of programming!
You’ve learned to:
ā
Use while for condition-based loops
ā
Use for to iterate over sequences
ā
Work with range() for numbers
ā
Apply break to exit early
ā
Apply continue to skip iterations
ā
Create nested loops
ā
Avoid infinite loops
With loops you can:
- Process large amounts of data
- Build games with repeating actions
- Automate repetitive tasks
- Implement complex algorithms
Practice in CodeHS! Write several programs using loops. Experiment with while, for, break, continue. Mix different techniques! šŖ
Next step: Learn about functions to organize your code even better! šÆ
š¬ Comments (0)
No comments yet
Be the first to share your opinion about this article!