šŸ“ Python

Loops in Python: while and for šŸ”„

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
šŸ“…
Published
30.03.2026
ā±ļø
Reading time
8 min
šŸ‘ļø
Views
97
🌱
Level
Beginner

Imagine: you need to print numbers from 1 to 1000. Write 1000 print() calls? 😱

Loops are the superpower of programming! They let you repeat actions as many times as you like.

šŸ¤” Why do we need loops?

Without loops (100 lines):

print(1)
print(2)
print(3)
print(4)
print(5)
# ... 95 more lines
print(100)

With loops (2 lines):

for i in range(1, 101):
    print(i)

The difference is obvious! šŸš€

šŸ” Two types of loops in Python

Python provides two main loop types:

  1. while — repeat while a condition holds (unknown count)
  2. for — iterate over each element (known count)

Let’s look at both!


1ļøāƒ£ The WHILE loop — “as long as”

Syntax:

while condition:
    code to execute

Logic: While the condition is True → run the code. When it’s False → stop.

Simple example — countdown:

count = 10

while count > 0:
    print(count)
    count -= 1  # count = count - 1

print("šŸš€ Liftoff!")

What happens:
1. count = 10 → 10 > 0 → True → prints 10, sets count to 9
2. count = 9 → 9 > 0 → True → prints 9, sets count to 8
3. … continues …
4. count = 0 → 0 > 0 → False → loop stops!

āš ļø Beware of infinite loops:

# āŒ NEVER DO THIS:
count = 10
while count > 0:
    print(count)
    # Forgot count -= 1 !
    # This loop runs forever! 😱

Stuck in an infinite loop? Press Ctrl+C to stop the program.

Example — keep asking until the correct password:

password = ""

while password != "python123":
    password = input("Enter password: ")
    if password != "python123":
        print("āŒ Wrong, try again")

print("āœ… Access granted!")

The loop continues while the password is wrong.

Example — game with while:

health = 100

while health > 0:
    action = input("Action (attack/defend/run): ")

    if action == "attack":
        print("āš”ļø You attacked!")
        health -= 20
    elif action == "defend":
        print("šŸ›”ļø You're defending!")
    elif action == "run":
        print("šŸƒ You ran away!")
        break  # Exit the loop

    print(f"šŸ’š Health: {health}")

if health <= 0:
    print("ā˜ ļø Game over")

2ļøāƒ£ The FOR loop — “for each”

Syntax:

for element in sequence:
    code to execute

for is more convenient when you know how many times to repeat or what to iterate over.

šŸ“ Option 1: for with range()

range(n) generates a sequence of numbers from 0 to n-1

for i in range(5):
    print(f"Iteration {i}")

# Prints:
# Iteration 0
# Iteration 1
# Iteration 2
# Iteration 3
# Iteration 4

range() has 3 forms:

range(5)          # 0, 1, 2, 3, 4
range(1, 6)       # 1, 2, 3, 4, 5 (from start up to stop-1)
range(0, 10, 2)   # 0, 2, 4, 6, 8 (step of 2)
range(10, 0, -1)  # 10, 9, 8...1 (counting down)

Example — multiplication table:

number = int(input("Enter a number: "))

for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")

šŸ“ Option 2: for with a list

fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(f"I love {fruit}! šŸŽ")

Python automatically picks each element from the list!

šŸ“ Option 3: for with a string

word = "PYTHON"

for letter in word:
    print(letter)

# P
# Y
# T
# H
# O
# N

Each character is processed individually!

Example — count vowels:

text = input("Enter text: ")
vowels = "aeiou"
count = 0

for char in text.lower():
    if char in vowels:
        count += 1

print(f"Number of vowels: {count}")

šŸ›‘ BREAK — early exit

break immediately stops the loop.

Example — find a number:

numbers = [3, 7, 12, 5, 18, 9]

for num in numbers:
    if num > 10:
        print(f"Found a large number: {num}")
        break  # Found it, exit!
    print(f"Checking {num}...")

# Prints:
# Checking 3...
# Checking 7...
# Found a large number: 12

After break the loop terminates entirely, even if elements remain.

Example — exit an infinite loop:

while True:  # Infinite loop!
    answer = input("Continue? (yes/no): ")

    if answer == "no":
        break  # Exit

    print("Continuing...")

print("Program finished")

ā­ļø CONTINUE — skip an iteration

continue skips the current iteration and moves to the next one.

Example — print only even numbers:

for i in range(10):
    if i % 2 != 0:  # If odd
        continue     # Skip it

    print(i)  # Only even numbers reach here

# Prints: 0, 2, 4, 6, 8

Difference between break and continue:

# BREAK — exits entirely:
for i in range(5):
    if i == 3:
        break
    print(i)
# Prints: 0, 1, 2 (stopped at 3)

# CONTINUE — skips one iteration:
for i in range(5):
    if i == 3:
        continue
    print(i)
# Prints: 0, 1, 2, 4 (skipped 3, kept going)

Example — filter a list:

names = ["Anna", "Bob", "Alice", "Boris", "Andrew"]

print("Names starting with A:")
for name in names:
    if not name.startswith("A"):
        continue  # Skip names that don't start with A

    print(name)

# Prints: Anna, Alice, Andrew

šŸŽÆ Nested loops — a loop inside a loop

A loop can contain another loop!

Example — grid of stars:

size = 5

for row in range(size):
    for col in range(size):
        print("⭐", end="")
    print()  # New line

# ⭐⭐⭐⭐⭐
# ⭐⭐⭐⭐⭐
# ⭐⭐⭐⭐⭐
# ⭐⭐⭐⭐⭐
# ⭐⭐⭐⭐⭐

What happens:
- The outer loop (row) runs 5 times
- For each row → the inner loop (col) runs 5 times
- Total: 5 Ɨ 5 = 25 iterations!

Example — triangle:

for row in range(1, 6):
    for col in range(row):
        print("ā–²", end="")
    print()

# ā–²
# ▲▲
# ▲▲▲
# ▲▲▲▲
# ▲▲▲▲▲

Example — Pythagorean multiplication table:

print("   ", end="")
for i in range(1, 6):
    print(f"{i:3}", end="")
print()

for i in range(1, 6):
    print(f"{i:2} |", end="")
    for j in range(1, 6):
        print(f"{i*j:3}", end="")
    print()

#      1  2  3  4  5
#  1 |  1  2  3  4  5
#  2 |  2  4  6  8 10
#  3 |  3  6  9 12 15
#  4 |  4  8 12 16 20
#  5 |  5 10 15 20 25

šŸ“Š while vs for comparison

Criterion while for
When to use Unknown iteration count Known count
Condition Checked each iteration Iterates over a sequence
Risk Infinite loop Safer
Examples Game loops, user input Iterating lists, range()
Readability Flexible Concise

Choosing which to use:

Use WHILE when:
- You don’t know how many iterations are needed
- The condition depends on what happens inside the loop
- You need an infinite loop with a break

Use FOR when:
- You’re iterating over a list / string / range
- You know the exact number of iterations
- You need to visit every element


šŸ’” Useful techniques

1. enumerate() — index + element:

fruits = ["apple", "banana", "orange"]

for index, fruit in enumerate(fruits):
    print(f"{index+1}. {fruit}")

# 1. apple
# 2. banana
# 3. orange

2. Iterating over a dictionary:

student = {"name": "Anna", "age": 20, "year": 2}

for key, value in student.items():
    print(f"{key}: {value}")

# name: Anna
# age: 20
# year: 2

3. else after a loop:

for i in range(5):
    if i == 10:  # Never True
        break
else:
    print("Loop completed without break")

else runs only if the loop was not interrupted by break.

4. Range with a step:

# Even numbers:
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# Reverse order:
for i in range(10, 0, -1):
    print(i)  # 10, 9, 8...1

šŸŽ® Practical examples

1. Calculator with a loop:

while True:
    print("\n🧮 Calculator")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")
    print("5. Exit")

    choice = input("Choice: ")

    if choice == "5":
        print("Goodbye!")
        break

    if choice in ["1", "2", "3", "4"]:
        a = float(input("First number: "))
        b = float(input("Second number: "))

        if choice == "1":
            print(f"Result: {a + b}")
        elif choice == "2":
            print(f"Result: {a - b}")
        elif choice == "3":
            print(f"Result: {a * b}")
        elif choice == "4":
            if b != 0:
                print(f"Result: {a / b}")
            else:
                print("āŒ Division by zero!")
    else:
        print("āŒ Invalid choice")

2. FizzBuzz — the classic exercise:

for i in range(1, 101):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

3. Password generator:

import random
import string

length = int(input("Password length: "))
password = ""

for i in range(length):
    char = random.choice(string.ascii_letters + string.digits)
    password += char

print(f"Your password: {password}")

4. Find prime numbers:

n = int(input("Find primes up to: "))

for num in range(2, n+1):
    is_prime = True

    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break

    if is_prime:
        print(num, end=" ")

āš ļø Common mistakes

1. Missing indentation:

# āŒ Wrong:
for i in range(5):
print(i)  # SyntaxError!

# āœ… Correct:
for i in range(5):
    print(i)

2. Modifying the loop counter inside a for loop:

# āŒ Don't do this:
for i in range(5):
    print(i)
    i = 10  # Has no effect on the loop!

# āœ… Use while instead:
i = 0
while i < 5:
    print(i)
    i += 1  # Works correctly

3. Forgetting to update the variable in while:

# āŒ Infinite loop:
i = 0
while i < 5:
    print(i)
    # Forgot i += 1

# āœ… Correct:
i = 0
while i < 5:
    print(i)
    i += 1

4. Wrong range:

# āŒ range(5, 1) — prints nothing:
for i in range(5, 1):
    print(i)

# āœ… Need a step of -1:
for i in range(5, 1, -1):
    print(i)  # 5, 4, 3, 2

šŸš€ Summary

Loops are a fundamental building block of programming!

You’ve learned to:

āœ… Use while for condition-based loops
āœ… Use for to iterate over sequences
āœ… Work with range() for numbers
āœ… Apply break to exit early
āœ… Apply continue to skip iterations
āœ… Create nested loops
āœ… Avoid infinite loops

With loops you can:
- Process large amounts of data
- Build games with repeating actions
- Automate repetitive tasks
- Implement complex algorithms


Practice in CodeHS! Write several programs using loops. Experiment with while, for, break, continue. Mix different techniques! šŸ’Ŗ

Next step: Learn about functions to organize your code even better! šŸŽÆ

Your reaction to the article

šŸ’¬ Comments (0)

šŸ” Sign in to leave a comment
🚪 Login
šŸ’­

No comments yet

Be the first to share your opinion about this article!

šŸ”— Similar

Similar articles

Continue learning with these materials

šŸ“

Setting Up Your Environment: Python, pip, and VS …

Before writing code locally, you need to set up three tools: Python, pip, and VS...

šŸ“… 04.06.2026 šŸ‘ļø 17
šŸ“

Anthropic SDK: Getting Started with the Claude API

Anthropic Python SDK is the official library for working with Claude. It hides the complexity...

šŸ“… 04.06.2026 šŸ‘ļø 17
šŸ“

The datetime Module: Working with Dates and Times

datetime is Python's standard module for working with dates and times. It's part of the...

šŸ“… 08.05.2026 šŸ‘ļø 67

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!