Loops – for and while

Section Overview

This section introduces loops in Python. Loops let your program repeat actions automatically. You'll learn how to use for and while loops to iterate through data or repeat a block of code until a condition is met.

By the end of this section, you should be able to:

  • Use a for loop to repeat an action a fixed number of times
  • Use a while loop to repeat based on a condition
  • Understand the role of break and continue
  • Work with ranges and basic loop patterns

Lesson 1: for Loops and the range() Function

A for loop is used when you want to run something a certain number of times.

for i in range(5):
    print("Hello")

This prints "Hello" five times. The loop variable i goes from 0 to 4.

You can use range(start, stop) to control where the loop begins and ends:

for i in range(1, 6):
    print(i)

This prints numbers 1 to 5.


Lesson 2: Looping Through Strings and Lists

You can use for loops to go through each item in a string or a list:

for letter in "Python":
    print(letter)

 

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

This pattern is helpful when processing items one at a time.


Lesson 3: while Loops

A while loop keeps running as long as its condition is true.

Example:

count = 0

while count < 3:
    print("Counting:", count)
    count += 1 

Use while when you don’t know in advance how many times you’ll need to loop—like when waiting for user input or checking for a condition.


Lesson 4: break and continue

  • break stops the loop early.
  • continue skips to the next iteration.

Example:

while True:
    user_input = input("Type 'exit' to quit: ")
    if user_input == "exit":
        break
    print("You typed:", user_input)

This keeps asking for input until the user types "exit".

Another example using continue:

for i in range(5):
    if i == 2:
        continue
    print(i)

This prints 0, 1, 3, 4 — it skips 2.


Quiz: Check Your Understanding

1. What does this print?

for i in range(3):
    print(i)

Answer:
0
1
2


2. What is the main difference between for and while loops?
a) for is faster
b) while is used for strings only
c) for loops a known number of times; while loops as long as a condition is true
Answer: c)


3. What keyword do you use to skip the rest of a loop iteration?
Answer: continue


4. What happens if the condition in a while loop never becomes false?
Answer: The loop runs forever (infinite loop)


Practice Exercise: Countdown Timer

Write a program that:

  1. Asks the user to enter a number
  2. Counts down to 0, printing each number

Example:

Enter a number: 5 5 4 3 2 1 0
Blast off!

Starter code:

number = int(input("Enter a number: "))

while number >= 0:
    print(number)
    number -= 1

print("Blast off!")

Challenge: Add a short delay between each number using import time and time.sleep(1).