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
A for loop is the most commonly used loop in Python. It 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 truthy. The loop stops once the condition becomes falsy, which may happen on the very first check.
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
Course
Mastering While Loops
Master indefinite iteration using the Python "while" loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.
For additional information on related topics, take a look at the following resources:
- Break Out of Loops With Python's break Keyword (Course)
- Python for Loops: The Pythonic Way (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- How to Write Pythonic Loops (Course)
- How to Exit Loops Early With the Python break Keyword (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- How Can You Emulate Do-While Loops in Python? (Tutorial)
- Python for Loops: The Pythonic Way (Quiz)
- How to Exit Loops Early With the Python break Keyword (Quiz)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.