Python ยท Loops

Complete Guide to Python Loops

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.

1. What Is a Loop?

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.

Without a loop:

With a loop:

2. The 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

3. Using range() in Loops

range() generates a sequence of numbers.

3.1 Basic range

for i in range(5):
    print(i)

3.2 Start and stop

for i in range(2, 6):
    print(i)

Output:

2
3
4
5

3.3 Step value

for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9

4. Looping Through Lists

You can loop through each item in a list using a for loop.

5. Looping Through Strings

Strings are sequences of characters, so you can loop through each character in a string.

6. The 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:

7. Infinite Loops

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.

8. The break Statement

break immediately exits the loop, even if the loop condition is still true.

Output:

0
1
2
3
4

9. The continue Statement

continue skips the rest of the current loop iteration and moves on to the next one.

Output:

0
1
3
4

10. The 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.

11. Nested Loops

A loop inside another loop is called a nested loop.

Output:

0 0
0 1
1 0
1 1
2 0
2 1

12. Using else with Loops

Python allows an else block after loops, which runs when the loop finishes normally (not via break).

With for:

With while:

13. Looping with enumerate()

enumerate() lets you access both the index and value when looping over a sequence.

Output:

0 apple
1 banana
2 orange

14. Looping with zip()

zip() lets you loop through multiple sequences at the same time.

15. List Comprehensions (Advanced Loops)

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)

16. Filtering with Loops

Use loops to filter items based on conditions.

17. Loops with User Input

You can use loops to repeatedly ask for user input until a certain condition is met.

18. Real-World Example: Simple ATM Loop

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.

19. Common Loop Mistakes

MistakeWrongCorrect
Infinite loop (no update)
count = 0
while count < 5:
    print(count)  # no increment
count = 0
while count < 5:
    print(count)
    count += 1
Wrong indentation
for i in range(3):
print(i)
for i in range(3):
    print(i)
Misusing break
for i in range(5):
    break
    print(i)
for i in range(5):
    if some_condition:
        break
    print(i)

20. Summary

In this guide, you learned how to:

Loops are one of the most important tools in Python. Mastering them will help you iterate over data, automate tasks, and build powerful programs.