The Ultimate Guide to Python ‘for’ Loops and ‘while’ Loops

3D isometric visualization of Python loops, showing a conveyor belt for 'for loops' and a spinning gear for 'while loops'.

In programming, one of our main goals is to automate repetitive tasks. This is where loops come in. They are one of the most powerful concepts you’ll learn, allowing you to run the same block of code over and over again.

This guide is the next logical step after our Python Variables & Data Types post. Once you know how to store data, you need to know how to work with it.

If you’re just starting, all of this is part of our Complete Guide to Learning Python.

This tutorial will teach you the two main types of loops in Python: for loops and while loops, and how to control them.

Part 1: The for Loop (Looping Over a Sequence)

The for loop is used when you want to iterate over a sequence. This means “for each item in this collection, do this action.”

A “sequence” can be:

  • A List
  • A Tuple
  • A String
  • A Dictionary
  • A range() of numbers

Example 1: Looping Through a List

This is the most common use case.

# Our list of fruits
fruits = ["apple", "banana", "cherry"]

# The for loop
print("My fruits:")
for fruit in fruits:
  print(fruit)

# Output:
# My fruits:
# apple
# banana
# cherry

What’s happening: Python goes through the fruits list, one item at a time. In the first loop, the variable fruit is "apple". In the second, fruit is "banana", and so on.

Example 2: Looping Through a String

A string is just a sequence of characters.

for letter in "Hello":
  print(letter)

# Output:
# H
# e
# l
# l
# o

The range() Function

What if you just want to do something 5 times? You use the range() function to create a sequence of numbers.

# range(5) generates numbers 0, 1, 2, 3, 4
for number in range(5):
  print(f"Loop number: {number}")

# Output:
# Loop number: 0
# Loop number: 1
# Loop number: 2
# Loop number: 3
# Loop number: 4

You can also give range() a start, stop, and step:

  • range(1, 6) gives 1, 2, 3, 4, 5
  • range(0, 10, 2) gives 0, 2, 4, 6, 8 (counts by 2)

Part 2: The while Loop (Looping on a Condition)

We use a for loop when we know how many times to loop (e.g., the length of a list). We use a while loop when we want to loop as long as a condition is True.

The loop will check the condition, run the code, and then check the condition again. It repeats this until the condition becomes False.

Example 1: A Simple Counter

count = 0
while count < 5:
  print(f"The count is: {count}")
  count = count + 1  # Or count += 1
print("Loop finished!")
# Output:
# The count is: 0
# The count is: 1
# The count is: 2
# The count is: 3
# The count is: 4
# Loop finished!

CRITICAL: Look at count = count + 1. This line is what eventually makes the condition count < 5 false. If you forget this, you create an infinite loop, and your program will crash!

Example 2: User Input

A while loop is perfect for asking a user for input until they give you what you want.

password = ""

while password != "secret":
  password = input("What's the password? ")

print("Welcome in!")

# Output:
# What's the password? hello
# What's the password? 123
# What's the password? secret
# Welcome in!

Part 3: Loop Control (break and continue)

Sometimes you need to change a loop’s behavior. Python gives you two keywords for this.

break: How to Exit a Loop Early

The break keyword stops the loop immediately, no matter what.

Example: Find the first person named “Bob” in a list.

names = ["Alice", "John", "Bob", "Carol"]

for name in names:
  print(f"Checking {name}...")
  if name == "Bob":
    print("Found Bob!")
    break  # Stop the loop

# Output:
# Checking Alice...
# Checking John...
# Checking Bob...
# Found Bob!
# (It never checks Carol)

continue: How to Skip an Iteration

The continue keyword skips the rest of the code for the current iteration and jumps to the next one.

Example: Print all numbers from 0 to 10, but skip odd numbers.

for number in range(11):  # 0 through 10
  if number % 2 != 0:  # If the number is odd
    continue  # Skip to the next number
  
  print(number)  # This line only runs for even numbers

# Output:
# 0
# 2
# 4
# 6
# 8
# 10

Part 4: A Better Way (List Comprehensions)

List comprehensions are a “Pythonic” shortcut for a for loop that builds a list.

The “Old” Way:

# Get a list of the squares of numbers from 0 to 9
squares = []  # 1. Create an empty list
for number in range(10):  # 2. Loop
  squares.append(number * number)  # 3. Append

print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The “Pythonic” Way (List Comprehension):

# Do the same thing in one line
squares = [number * number for number in range(10)]

print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

It’s cleaner, easier to read (once you’re used to it), and faster!

Conclusion

You’ve just learned one of the most important parts of programming:

  • Use a for loop to iterate over a known sequence (lists, strings, ranges).
  • Use a while loop to repeat code as long as a condition is True.
  • Use break to exit a loop and continue to skip an iteration.

Now that you can store data and loop over it, the next step is to choose the right type of collection for your data. Read our next guide: Python Lists vs. Tuples vs. Dictionaries.

Similar Posts

Leave a Reply