Loops (for & while)

When you need to perform the same operation on many items, or repeat a block of code until a condition changes, what's Python's most efficient tool? Python's for and while loops provide concise ways to automate repetitive tasks and iterate over data efficiently.

Iterating with for Loops

The for loop in Python is designed for iterating over sequences, such as lists, tuples, strings, or other iterable objects. It allows you to execute a block of code once for each item in the sequence. This is particularly useful when you know in advance how many times you need to repeat an action, or when you need to process every element within a collection.

pythonIterating Over a List of Numbers
Check Your Understanding
What will be printed by the following for loop?
pythonIterating Over Strings and Ranges
Try It Yourself
Modify the code to calculate the sum of all numbers in the prices list and print the total.
python

Conditional Repetition with while Loops

A while loop executes a block of code repeatedly as long as a specified condition remains true. Unlike for loops, which iterate over a fixed sequence, while loops are ideal when the number of repetitions is not known beforehand. You might use a while loop when waiting for user input, processing data until a certain threshold is met, or when implementing retry logic.

pythonBasic `while` Loop for Countdown
Flow of a `while` Loop
Loading diagram...
The `while` loop continuously checks its condition; if true, it executes its block and then re-evaluates the condition.
Check Your Understanding
When is a while loop generally preferred over a for loop?

Controlling Loop Flow: break and continue

Sometimes, you need more granular control over loop execution than simply letting it run to completion. Python provides two statements, break and continue, to alter the normal flow of a loop. The break statement immediately terminates the entire loop, while continue skips the rest of the current iteration and moves to the next one.

pythonExiting a Loop Early with `break`
pythonSkipping Iterations with `continue`
Check Your Understanding
What will be the output of this code snippet?

Avoiding Common Loop Traps

⚠️ Infinite Loops

A critical pitfall with while loops is creating an infinite loop. This occurs when the loop's condition never becomes False, causing the program to execute indefinitely. Always ensure that within your while loop, there is a statement that will eventually change the condition to False, allowing the loop to terminate.

pythonDemonstrating an Infinite Loop (Concept)
Key Takeaways
  • for loops are used to iterate over known sequences like lists, strings, or ranges, executing a block of code for each item.

  • while loops repeat a block of code as long as a specified condition remains True, making them suitable when the number of iterations is unknown.

  • The break statement immediately terminates the entire loop, regardless of the loop's condition.

  • The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.

  • Always ensure that the condition in a while loop will eventually become False to prevent infinite loops, ensuring efficient and controlled program execution.

← All lessons in Python Basics & Syntax

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free