4Lesson 4 of 5

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!
Python has two main loop types: for and while. Each is suited for different situations.

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, 8
range(start, stop) - start is included, stop is NOT included. Think of it as 'up to but not including'.

Looping 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
# n

The 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!
Always update the condition variable inside the loop! Without count += 1, this would run forever.

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 loop
Always have an exit strategy! Use break or a condition that eventually becomes False.

break 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, 4

Printing 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 ->
The default is end='\n' (newline). You can use end='' for no separator at all.

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

  1. Print numbers from 10 to 1 (countdown)
  2. Print only even numbers from 1 to 20
  3. Create a multiplication table for any number
  4. Build a password checker using while loop
  5. Print a triangle pattern of stars (* ** *** **** *****)