No history yet

For and While Loops

The For Loop: Iterating Over Sequences

When you have a collection of items and you want to do something with each one, the for loop is your tool. Think of it as working your way through a list, one item at a time. This collection could be a list of strings, a range of numbers, or the characters in a word.

The structure is straightforward. You declare a temporary variable to hold each item as the loop runs, and you specify the sequence you want to iterate over.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I have a {fruit}.")

In this example, the loop runs three times. In the first run, fruit is "apple". In the second, it's "banana", and in the third, it's "cherry". The loop automatically stops when it runs out of items.

Often, you'll want to repeat an action a specific number of times. For this, Python's range() function is perfect. It generates a sequence of numbers that the for loop can iterate over. Note that range(5) generates numbers from 0 up to, but not including, 5.

# This will print numbers 0, 1, 2, 3, 4
for i in range(5):
    print(f"This is repetition number {i}")

The While Loop: Repeating Until a Condition is Met

A while loop is different. Instead of iterating over a sequence, it keeps running as long as a certain condition remains true. It's like telling your program, "Keep doing this until I say stop," where "stop" is the condition becoming false.

The key is to ensure that something inside the loop eventually changes the condition to false. If you don't, you create an infinite loop, and your program will get stuck.

count = 0

# This loop will run as long as 'count' is less than 5
while count < 5:
    print(f"The count is {count}")
    count = count + 1  # Incrementing the count is crucial!

print("Loop finished.")

Here, count = count + 1 is the critical line. Without it, count would always be 0, the condition count < 5 would always be true, and the loop would never end.

while loops are ideal when you don't know in advance how many times you need to repeat. A common use case is processing user input until the user decides to quit.

command = ""

# The loop continues as long as the user hasn't typed 'quit'
while command.lower() != "quit":
    command = input("Enter a command (or 'quit' to exit): ")
    print(f"You entered: {command}")

For vs. While: Which to Choose?

Choosing the right loop simplifies your code and makes your intent clearer. A for loop is for definite iteration—when you have a known set of items to go through. A while loop is for indefinite iteration—when you need to repeat something until a condition changes.

FeatureFor LoopWhile Loop
Best Use CaseIterating over a known sequence (list, string, range)Looping until a specific condition becomes false
Iteration TypeDefinite (fixed number of runs)Indefinite (number of runs is unknown)
Structurefor item in sequence:while condition:
RiskGenerally saferCan cause infinite loops if the condition never changes

Let's look at a final practical example. Say we want to find the first multiple of 7 in a list of numbers. A for loop works, but we can also use a while loop if we only care about processing the list until we find our answer.

numbers = [11, 23, 49, 50, 71, 84]

# Using a for loop
for num in numbers:
    if num % 7 == 0:
        print(f"Found a multiple of 7: {num}")
        break  # 'break' exits the loop immediately

# Using a while loop
index = 0
found = False
while index < len(numbers) and not found:
    num = numbers[index]
    if num % 7 == 0:
        print(f"Found a multiple of 7: {num}")
        found = True
    index += 1

Both loops achieve the same result, but the for loop with break is often considered more direct and readable in Python for this specific task.

Time to test your understanding of these essential looping constructs.

Quiz Questions 1/5

What is the primary difference between a for loop and a while loop?

Quiz Questions 2/5

What will be the output of the following Python code?

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

Mastering loops is a fundamental step in programming. They allow you to automate repetitive tasks and write powerful, efficient code.