Back to blog
← View series: python tutorials

~/blog

Control Flow - Loops

Apr 1, 20265 min readBy Mohammed Vasim
PythonProgrammingTutorialBeginner

Introduction

In this tutorial, you'll learn how to use loops in Python. Loops allow you to repeat code multiple times without writing it over and over. This is essential for processing collections of data, automating repetitive tasks, and implementing algorithms.

What You'll Learn

  • The for loop for iterating over sequences
  • The while loop for conditional repetition
  • Loop control statements: break, continue, and else
  • The range() function
  • Nested loops

The for Loop

The for loop iterates over a sequence (like a list, string, or range):

Basic for Loop

python
# Iterating over a list
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple banana cherry

Iterating Over a String

python
# Each character in a string
for letter in "Python":
    print(letter)

Output:

P y t h o n

The range() Function

range() generates a sequence of numbers, perfect for counting loops:

range() Basics

python
# range(stop) - from 0 to stop-1
for i in range(5):
    print(i)

Output:

0 1 2 3 4

range() with Start and Step

python
# range(start, stop) - from start to stop-1
for i in range(2, 6):
    print(i)

Output:

2 3 4 5
python
# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)

Output:

0 2 4 6 8
python
# Negative step (counting backwards)
for i in range(5, 0, -1):
    print(i)

Output:

5 4 3 2 1

The while Loop

The while loop repeats as long as a condition is True:

Basic while Loop

python
# Count from 1 to 5
count = 1

while count <= 5:
    print(count)
    count += 1  # Don't forget this!

print("Done!")

Output:

1 2 3 4 5 Done!

while with User Input

python
# Keep asking until user enters 'quit'
while True:
    command = input("Enter command (type 'quit' to exit): ")
    
    if command == "quit":
        print("Goodbye!")
        break
    
    print(f"You entered: {command}")

Loop Control Statements

break - Exit the Loop

The break statement immediately exits the loop:

python
# Find first even number
numbers = [1, 3, 5, 6, 7, 9]

for num in numbers:
    if num % 2 == 0:
        print(f"Found even number: {num}")
        break  # Exit the loop

Output:

Found even number: 6

continue - Skip to Next Iteration

The continue statement skips the rest of the current iteration:

python
# Print only odd numbers
for i in range(1, 10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

Output:

1 3 5 7 9

else - Run When Loop Completes Normally

The else block runs when the loop finishes without hitting break:

python
# Search for a number
numbers = [1, 3, 5, 7, 9]
search = 6

for num in numbers:
    if num == search:
        print(f"Found {search}!")
        break
else:
    # This runs if break was never hit
    print(f"{search} not found in the list")

Output:

6 not found in the list

Practical Examples

Example 1: Sum of Numbers

python
# Calculate sum of 1 to 100
total = 0

for i in range(1, 101):
    total += i

print(f"Sum: {total}")  # Output: 5050

Example 2: Factorial

python
# Calculate factorial of 5
n = 5
factorial = 1

while n > 0:
    factorial *= n
    n -= 1

print(f"Factorial: {factorial}")  # Output: 120

Example 3: FizzBuzz

A classic programming problem:

python
# FizzBuzz: print 1-20, but fizz for multiples of 3,
# buzz for multiples of 5, fizzbuzz for both
for i in range(1, 21):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Example 4: Finding Maximum

python
# Find the largest number in a list
numbers = [12, 45, 67, 23, 89, 34]
max_num = numbers[0]  # Start with first number

for num in numbers:
    if num > max_num:
        max_num = num

print(f"Largest: {max_num}")  # Output: 89

Nested Loops

You can place loops inside other loops:

python
# Multiplication table (1-5)
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:3d}", end=" ")  # :3d formats as 3-digit
    print()  # New line after each row

Output:

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

⚠️ Warning: Nested loops can be slow. Avoid deep nesting (3+ levels).

for vs while - When to Use Which?

Use CaseLoop Type
Iterating over a sequence (list, string)for
Known number of iterationsfor with range()
Unknown number of iterationswhile
Loop until a condition changeswhile

Summary

In this tutorial, you learned:

  • ✅ The for loop for iterating over sequences
  • ✅ The range() function for generating number sequences
  • ✅ The while loop for conditional repetition
  • ✅ Loop control: break, continue, and else
  • ✅ Nested loops
  • ✅ Practical examples: sum, factorial, FizzBuzz

🧑‍💻 Practice Exercise

Create a program that:

  1. Asks the user for a number
  2. Prints a triangle pattern like this (for input 5):
* ** *** **** *****
  1. Also prints the multiplication table for that number (1-10)
Click to see solution
python
# Triangle pattern and multiplication table
num = int(input("Enter a number: "))

# Triangle pattern
print("\n--- Triangle ---")
for i in range(1, num + 1):
    print("*" * i)

# Multiplication table
print("\n--- Multiplication Table ---")
for i in range(1, 11):
    result = num * i
    print(f"{num} x {i} = {result}")

Sample Output for input 5:

--- Triangle --- * ** *** **** ***** --- Multiplication Table --- 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50

What's Next

In the next tutorial, we'll learn about Data Structures - Lists - how to work with collections of data.

Data Structures - Lists →

Comments (0)

No comments yet. Be the first to comment!

Leave a comment