Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Python Loops Tutorial - for, while, range, enumerate Examples

What are 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.

for Loop
# 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)

Useful for Loop Patterns

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.

while Loop
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!")

break, continue, pass

Loop Control
# 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 - do nothing (placeholder)
for i in range(5):
    if i == 3:
        pass   # TODO: handle this case 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
# 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}

Ready to Level Up Your Skills?

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