Imagine you need to perform the same task 100 times. Would you copy and paste the code 100 times? Of course not! This is where loops come in. Python provides two main looping constructs, the while
loop and the for
loop, which allow you to execute a block of code multiple times efficiently.
🔄 The While Loop: Repeat as Long as a Condition is True
A while
loop will execute a block of code as long as a specified condition evaluates to True. It’s like an `if` statement that keeps repeating. The loop checks the condition, and if it’s True, it runs the indented body. Once the body is finished, it goes back to the top and checks the condition again. This continues until the condition becomes False. This type of loop is perfect when you don’t know in advance how many times you need to repeat, for example, when waiting for a user to enter a specific value to quit.
🔢 The For Loop: Iterate Over a Collection of Items
A for
loop is designed to execute once for each item in a collection. This collection could be a list of values, the characters in a string, or a range of numbers. The most common way to use it for a set number of repetitions is with the range()
function. For example, for i in range(5):
will execute the loop body exactly five times, with the variable `i` taking on the values 0, 1, 2, 3, and 4 in sequence.
🤔 Which Loop Should You Choose?
The choice between a `while` and a `for` loop usually comes down to what you’re trying to do. If you know exactly how many times you need to loop (e.g., 10 times, or once for every item in a list), a for
loop is almost always the cleaner and better choice. If you need to loop based on a condition that can change during execution (e.g., keep running until the user enters ‘quit’ or until a certain value is reached), then a while
loop is the way to go.
Both loops are fundamental tools for automating repetitive tasks. Understanding the difference between them will help you write more efficient and readable Python code.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python