Loops allow you to repeat code automatically instead of writing it many times.
In Python, the two main loop types are for loops and while loops.
A loop repeats a block of code until a condition is met. Without loops, you would have to copy-paste the same line many times.
for Loop
The for loop is used to iterate over sequences like lists, strings, ranges, dictionaries, and more.
Basic syntax:
for variable in sequence:
# code to repeat
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
range() in Loopsrange() generates a sequence of numbers.
for i in range(5):
print(i)
for i in range(2, 6):
print(i)
Output:
2
3
4
5
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
You can loop through each item in a list using a for loop.
Strings are sequences of characters, so you can loop through each character in a string.
while Loop
A while loop runs as long as its condition is True. When the condition becomes False, the loop stops.
Syntax:
while condition:
# code
Example:
An infinite loop runs forever because its condition is always True or never updated.
while True:
print("This never stops")
Use CTRL + C to stop it in the terminal, or add a break inside the loop when tested in any IDE.
break Statement
break immediately exits the loop, even if the loop condition is still true.
Output:
0
1
2
3
4
continue Statement
continue skips the rest of the current loop iteration and moves on to the next one.
Output:
0
1
3
4
pass Statement
pass is a placeholder that does nothing. It is useful when you need a loop or block that you plan to fill later.
A loop inside another loop is called a nested loop.
Output:
0 0
0 1
1 0
1 1
2 0
2 1
else with Loops
Python allows an else block after loops, which runs when the loop finishes normally (not via break).
for:while:enumerate()
enumerate() lets you access both the index and value when looping over a sequence.
Output:
0 apple
1 banana
2 orange
zip()
zip() lets you loop through multiple sequences at the same time.
List comprehensions provide a concise way to create lists using loops in a single line.
Equivalent to:
squares = []
for x in range(1, 6):
squares.append(x * x)
Use loops to filter items based on conditions.
You can use loops to repeatedly ask for user input until a certain condition is met.
This example simulates a simple ATM withdrawal process using a loop. It continues to ask for withdrawal amounts until the account is empty or an invalid amount is entered.
| Mistake | Wrong | Correct |
|---|---|---|
| Infinite loop (no update) | |
|
| Wrong indentation | |
|
Misusing break |
|
|
In this guide, you learned how to:
for and while loopsbreak, continue, and passrange(), enumerate(), and zip() in loopselseLoops are one of the most important tools in Python. Mastering them will help you iterate over data, automate tasks, and build powerful programs.