Loops - Repeating Actions
Master Python loops to automate repetitive tasks and iterate over collections of data efficiently.
Loops are fundamental to programming - they let you repeat actions without writing the same code over and over. Without loops, printing numbers 1 to 100 would require 100 print statements! In this lesson, you will learn about for loops and while loops, break and continue statements, and how to use them effectively.
Why Do We Need Loops?
Imagine printing numbers from 1 to 5 without a loop. You would need to write print() five times! Now imagine 1 to 100. A loop allows us to repeat code automatically, avoid duplication, and control repetition logically.
# Without a loop - repetitive and tedious!
print(1)
print(2)
print(3)
print(4)
print(5)
# What if we need 1 to 100?
# We would need 100 lines of code!The for Loop
Use for loops when you repeat over a sequence or know how many times to repeat. A sequence is an ordered collection of values like strings, lists, or ranges.
# Basic for loop syntax
for variable in sequence:
# code to repeat
# Example: print numbers 0-4
for i in range(5):
print(i)Using range()
The range() function generates number sequences. It's perfect for when you know exactly how many times to repeat.
# range(5) produces 0, 1, 2, 3, 4
for i in range(5):
print(i)
# Custom range: start at 1, stop before 6
for i in range(1, 6):
print(i) # Prints 1, 2, 3, 4, 5
# With step: every other number
for i in range(0, 10, 2):
print(i) # Prints 0, 2, 4, 6, 8Looping Over Strings
Strings are sequences of characters, so you can loop over them directly. Each iteration, the variable takes the next character.
# Loop through each character
for letter in "Python":
print(letter)
# Output:
# P
# y
# t
# h
# o
# nThe while Loop
Use while loops when repetition depends on a condition and you don't know the exact number of repetitions beforehand.
# while loop syntax
while condition:
# code to repeat
# Example: count to 5
count = 1
while count <= 5:
print(count)
count += 1 # Don't forget this!Infinite Loops
while True creates an infinite loop that runs forever. This is useful for programs that should run continuously, but be careful!
# Infinite loop - runs forever!
while True:
print("Running...")
# Press CTRL+C to stop
# Useful for: servers, games, menu systems
while True:
choice = input("Enter command: ")
if choice == "quit":
break # Exit the loopbreak and continue
break stops the loop immediately. continue skips the current iteration and moves to the next one.
# break - exit loop early
for i in range(10):
if i == 5:
break # Stop when i is 5
print(i) # Prints 0, 1, 2, 3, 4
# continue - skip current iteration
for i in range(5):
if i == 2:
continue # Skip 2
print(i) # Prints 0, 1, 3, 4Printing on Same Line
By default, print() adds a newline after each output. Use the end parameter to change this behavior.
# Default behavior - each on new line
for i in range(5):
print(i)
# Output: 0 (newline) 1 (newline) 2...
# Same line with space separator
for i in range(1, 6):
print(i, end=" ")
# Output: 1 2 3 4 5
# Custom separator
for i in range(1, 4):
print(i, end=" -> ")
# Output: 1 -> 2 -> 3 ->Key Takeaways
- for loops iterate over sequences like strings, lists, or range()
- while loops repeat as long as a condition is True
- range(start, stop) generates numbers from start to stop-1
- break exits a loop immediately, continue skips to next iteration
- Always update loop variables in while loops to prevent infinite loops
- Use end parameter in print() to control line endings
Practice Exercises
- Print numbers from 10 to 1 (countdown)
- Print only even numbers from 1 to 20
- Create a multiplication table for any number
- Build a password checker using while loop
- Print a triangle pattern of stars (* ** *** **** *****)