Loop
In one line
A loop is a control structure that repeats a block of code, either a fixed number of times (for) or while a condition is true (while).
In simple words
A loop repeats a block of code. Python has two main loop types: for and while.
A for loop iterates over a sequence (list, string, range, etc.): for item in items:. It runs once for each item. The range() function is commonly used to loop a specific number of times.
A while loop repeats as long as a condition is true: while condition:. It is used when you don't know in advance how many iterations are needed. Be careful to ensure the condition eventually becomes false, or the loop runs forever.
break exits a loop immediately. continue skips to the next iteration. else on a loop runs if the loop completes without breaking.
Example
# for loop
for i in range(3):
print(i) # 0, 1, 2
# while loop
count = 0
while count < 3:
print(count)
count += 1
# break and continue
for i in range(5):
if i == 3:
break
if i == 1:
continue
print(i) # 0, 2for loops iterate over sequences, while loops repeat until a condition is false, and break/continue control flow.
Common confusions
Confused with: recursion
The difference: A loop repeats code iteratively. Recursion repeats by a function calling itself. Loops are usually more efficient in Python; recursion is more elegant for tree-structured problems but risks stack overflow.
Related terms
Related Resources
Related Lessons
- Conditions and Loops
Loops in Python.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.