loop
A loop is a programming construct that allows you to repeat a block of code multiple times. In Python, loops are essential for automating repetitive tasks, processing collections of data, and creating efficient, concise code. Rather than writing the same instructions over and over, loops let you write them once and execute them repeatedly based on specific conditions.
for
Loop
The most commonly used loop in Python. A for
loop iterates over a sequence (like a list, tuple, or string) or other iterable objects. It executes a block of code once for each item in the sequence.
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
while
Loop
A while
loop repeatedly executes a block of code as long as a given condition remains True
. The loop continues until the condition becomes False
.
count = 0
while count < 3:
print(count)
count += 1
Nested Loops
Loops can be placed inside other loops. The inner loop completes all its iterations for each single iteration of the outer loop.
for i in range(2):
for j in range(2):
print(f"i: {i}, j: {j}")
Loop Control Statements
Related Resources
Tutorial
Python "for" Loops (Definite Iteration)
In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.
For additional information on related topics, take a look at the following resources:
- Python "while" Loops (Indefinite Iteration) (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- The Python for Loop (Quiz)
- Mastering While Loops (Course)
- Python "while" Loops (Quiz)
By Dan Bader • Updated Jan. 8, 2025