Tutorials Logic, IN info@tutorialslogic.com

Python Loops for, while, range, enumerate

Loop Basics

Loops repeat work without copying the same line many times.

A for loop is best when you already have a sequence to process, while a while loop is best when repetition depends on a condition becoming false.

Good loop code has a clear stop point, a small body, and names that reveal what each item represents.

Python Loops

Loops let you execute a block of code repeatedly. Python has two loop types: for (iterate over a sequence) and while (repeat while a condition is true).

for Loop

Iterates over any iterable - list, tuple, string, range, dict, etc.

Loop Through Lists, Strings, and Ranges

Loop Through Lists, Strings, and Ranges
# Iterate over a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
    print(fruit)

# Iterate over a string
for char in "Python":
    print(char, end=" ")  # P y t h o n

# Iterate over a range
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):     # 1, 2, 3, 4, 5
    print(i)

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

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

for Loop Patterns

enumerate, zip, items

enumerate, zip, items
fruits = ["apple", "banana", "mango"]

# enumerate - get index and value
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: mango

# enumerate with custom start
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

# zip - iterate two lists together
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

# Iterate dict items
person = {"name": "Alice", "age": 25}
for key, value in person.items():
    print(f"{key} = {value}")

# Nested loops
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i}x{j}={i*j}", end="  ")
    print()

while Loop

Repeats as long as a condition is True. Use when you don't know the number of iterations in advance.

Repeat Until a Counter Stops

Repeat Until a Counter Stops
count = 0
while count < 5:
    print(count)
    count += 1   # IMPORTANT: always update the condition variable

# User input loop
while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break
    print(f"You typed: {answer}")

# Countdown
n = 10
while n > 0:
    print(n, end=" ")
    n -= 1
print("Go!")

Loop Control

Use break, continue, and pass

Use break, continue, and pass
# break - exit the loop immediately
for i in range(10):
    if i == 5:
        break
    print(i)   # prints 0 1 2 3 4

# continue - skip current iteration, go to next
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)   # prints 1 3 5 7 9 (odd numbers only)

# pass - keep this branch intentionally empty
for i in range(5):
    if i == 3:
        pass   # reserved for special handling later
    print(i)   # prints all 0 1 2 3 4

# for-else / while-else
# else block runs only if loop completed without break
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            break
    else:
        print(f"{n} is prime")  # 2 3 5 7

List Comprehensions

A concise way to create lists using a single line. Much more Pythonic than a for loop with append().

Comprehensions

Comprehensions
# List comprehension: [expression for item in iterable if condition]
squares = [x**2 for x in range(1, 6)]
print(squares)   # [1, 4, 9, 16, 25]

evens = [x for x in range(20) if x % 2 == 0]
print(evens)     # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
print(upper)     # ['HELLO', 'WORLD', 'PYTHON']

# Nested comprehension (flatten a 2D list)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)      # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Dict comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Set comprehension
unique_lengths = {len(w) for w in words}
print(unique_lengths)  # {5, 6}
Loop checkpoint

Can You Repeat Work Safely?

5 checks
  • Loops let you execute a block of code repeatedly.
  • Python has two loop types: for (iterate over a sequence) and while (repeat while a condition is true).
  • A for loop consumes values from any iterable, including a list, tuple, string, range, or dictionary.
  • Repeats as long as a condition is True.
  • Use when you don't know the number of iterations in advance.

Loop Decisions

0 of 2 checked

Q1. When is for usually clearer than while?

Q2. What usually causes an accidental infinite while loop?

Loop Bugs That Waste Time

  • Using while when for is clearer

    Use for when looping through a known collection or range. Use while for unknown repeat counts.
  • Forgetting to update a while condition

    Change the value that controls the loop, or the loop may never stop.
  • Using indexes when values are enough

    Loop directly over items unless you truly need the position.

Try this next

Repeat Until It Works

0 of 2 completed

  1. Use while to keep reading commands until the user types quit.
  2. Print each task with a human-friendly number starting at 1.

Questions About Loop Control

Choose for when you are looping over known items. Choose while when repetition depends on a condition changing over time.

A while loop becomes infinite when its condition never becomes false. Update the controlling value inside the loop.

Use break when the loop has found what it needed or continuing would be wrong. Keep the reason easy to see.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.