Prerequisites:

  • Basic understanding of Python syntax
  • Knowledge of variables and data types
  • Familiarity with lists in Python
  • Using IDLE or any Python programming environment

Learning Objectives

By the end of this lesson, you will be able to:

  1. Understand what loops are and explain why they are essential in programming
  2. Write for loops using the range() function with different parameters
  3. Create while loops with proper initialization, condition, and increment
  4. Differentiate between for loops and while loops and choose the appropriate one
  5. Use counters effectively to control loop execution
  6. Implement nested loops (loops within loops) for complex tasks
  7. Iterate through lists using for loops
  8. Apply custom increment and decrement values in loops
  9. Control loop behavior using break and continue statements
  10. Solve real-world problems using loops, such as calculating factorials and printing patterns

Why Learn About Loops?

Imagine you have to send a “Happy New Year!” message to at least 50 of your friends on WhatsApp. Would you want to type the same message 50 times, once for each friend? Or imagine your teacher assigns ask you to create 225 holiday homework worksheets for all the students in your batch. Would you want to manually write each one?

That’s exactly what loops do in programming – they allow us to write instructions once and have the computer repeat them as many times as needed.

Real-Life Examples of Loops We Encounter Every Day

Think about these everyday situations:

  • Running laps around a field: When your PE teacher asks you to run 5 laps, you’re essentially performing the same action (running around the field) 5 times. You keep count mentally: “That’s lap 1… lap 2…” and so on.
  • Climbing stairs: If someone tells you to climb 10 steps, you repeat the action of stepping up exactly 10 times. Or if they say “climb until you reach the first floor,” you keep climbing regardless of how many steps there are, until you reach your destination.
  • Checking items on a shopping list: You go through each item on your list one by one until you’ve checked everything.

In all these examples, you’re repeating an action – either a fixed number of times or until a certain condition is met. This is exactly what loops help us do in programming!

Why Are Loops Important?

Loops are powerful because they offer several advantages:

  1. Save Time and Effort: Write the code once, let the computer repeat it hundreds or thousands of times.
  2. Reduce Errors: Humans make mistakes when doing repetitive tasks. Computers don’t – they’ll execute the same instruction perfectly every single time.
  3. Make Code Shorter: Instead of writing the same code 100 times, you write it once inside a loop.
  4. Handle Unknown Quantities: Sometimes you don’t know in advance how many times something needs to be done. Loops can handle that too!

Without loops, programming would be extremely tedious and inefficient. Let’s dive in and learn how to harness this powerful tool!

What Are Loops?

Definition

In Python (and in any programming language), loops are structures that allow you to repeat a set of instructions multiple times. The word “loop” itself suggests going around in circles – and that’s exactly what happens in programming. The computer keeps going back to the beginning of a block of code to execute it again and again.

The Basic Structure

Every loop has three essential components:

  1. Initialization: Setting up where the loop starts (like standing at the starting line)
  2. Condition: Deciding when the loop should stop (like knowing you need to run 5 laps)
  3. Update/Increment: Moving forward with each repetition (like counting “1st lap, 2nd lap, 3rd lap…”)

Understanding Counters

Let’s go back to our field example. If someone asks you to run around the field 3 times, how do you keep track? You count!

  • First round: “I’ve completed 1 lap”
  • Second round: “I’ve completed 2 laps”
  • Third round: “I’ve completed 3 laps”
  • Stop running!

In programming, we use a special variable called a counter to keep track of how many times the loop has run. The counter is like your mental note that remembers which lap you’re on.

# Think of it this way:
# lap_number is our counter
# We start at lap 1
# We continue until we've done 3 laps
# After each lap, we increase the counter by 1

The counter:

  • Starts at a specific value (often 0 or 1)
  • Changes with each loop iteration (usually increases by 1)
  • Helps determine when the loop should stop

Types of Loops in Python

Python provides us with three main ways to create loops:

  1. for loop: Use this when you know how many times you want to repeat something
    • Example: “Print ‘Hello’ 10 times”
    • Example: “Go through each item in a list”
  2. while loop: Use this when you don’t know exactly how many times you’ll repeat, but you know the condition for stopping
    • Example: “Keep asking for input until the user types ‘quit'”
    • Example: “Keep climbing stairs until you reach the first floor”
  3. Nested loops: This is when you have one loop running inside another loop
    • Example: “For each row, print each column” (useful for patterns and tables)

In the following sections, we’ll explore each type in detail with examples and practice exercises.

The for Loop

The for loop is used when you know in advance how many times you want to repeat a set of instructions. It’s like being told “climb exactly 10 steps” – you know the exact number beforehand.

Basic Syntax

Here’s the structure of a for loop in Python:

for counter_variable in range(n):
    # statement(s) to be repeated
    # these must be indented

Let’s break down each part:

  • for: This is a keyword that tells Python we’re starting a loop
  • counter_variable: This is a variable name (you can choose any valid name like i, num, count, etc.)
  • in: Another keyword
  • range(n): This specifies how many times to repeat
  • :: The colon is MANDATORY – it marks the end of the loop header
  • Indentation: Everything that should repeat must be indented (usually 4 spaces)

Understanding range()

The range() function is crucial for for loops. It can be used in three ways:

1. range(stop) – Single Parameter

for i in range(5):
    print("Hello World")

What is happening here:

  • The counter i starts at 0 (this is the default)
  • It goes up to 4 (which is 5 – 1)
  • The loop runs 5 times in total
  • Values of i: 0, 1, 2, 3, 4

Output:

Hello World
Hello World
Hello World
Hello World
Hello World

Important: When you write range(5), the loop runs 5 times, but the counter goes from 0 to 4, NOT 0 to 5!

2. range(start, stop) – Two Parameters

for num in range(1, 6):
    print(num)

What is happening here:

  • The counter num starts at 1 (the start value)
  • It goes up to 5 (which is 6 – 1, the stop value minus 1)
  • The loop runs 5 times
  • Values of num: 1, 2, 3, 4, 5

Output:

1
2
3
4
5

3. range(start, stop, step) – Three Parameters

We’ll cover this in detail later, but here’s a preview:

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

This prints even numbers from 2 to 20. The third parameter (2) tells Python to increase the counter by 2 each time instead of 1.

How the for Loop Works: Step-by-Step

Let’s trace through this simple program:

for i in range(3):
    print("Loop number:", i)

Execution trace:

  1. First iteration:i = 0
    • Print “Loop number: 0”
    • Control goes back to the beginning of the loop
    • i automatically increases to 1
  2. Second iteration:i = 1
    • Print “Loop number: 1”
    • Control goes back to the beginning
    • i automatically increases to 2
  3. Third iteration:i = 2
    • Print “Loop number: 2”
    • Control goes back to the beginning
    • i would become 3, but 3 is not less than 3, so…
  4. Loop ends
    • Control moves to the next statement after the loop

Output:

Loop number: 0
Loop number: 1
Loop number: 2

Key Feature: Automatic Increment

Notice something important: You don’t have to manually increase the counter in a for loop! Python does it automatically. This is one of the biggest advantages of for loops.

Example 1: Printing Numbers 1 to 5

for num in range(1, 6):
    print(num)

Output:

1
2
3
4
5

Example 2: Calculating Factorial

Let’s write a program to find the factorial of a number. Remember, 5! (5 factorial) = 1 × 2 × 3 × 4 × 5 = 120

# Program to calculate factorial
number = int(input("Enter a number: "))
factorial = 1

for i in range(1, number + 1):
    factorial = factorial * i

print("Factorial of", number, "is", factorial)

How it works:

  • We initialize factorial = 1 (because multiplying by 1 doesn’t change the result)
  • For each value from 1 to number, we multiply factorial by that value
  • Finally, we print the result

Sample Run:

Enter a number: 5
Factorial of 5 is 120

Another Sample Run:

Enter a number: 10
Factorial of 10 is 3628800

✏️ Try It Yourself!

  1. Write a program that prints “Python is fun!” 7 times.
  2. Write a program that prints numbers from 10 to 20.
  3. Modify the factorial program to calculate the factorial of 6. What result do you get?

💡 Common Mistakes to Avoid:

  1. Forgetting the colon (:) – Python will give you a syntax error for i in range(5) due to Missing colon after print(i)
  2. Forgetting to indent – The code inside the loop must be indented for i in range(5): print(i) # ❌ Not indented
  3. Confusing the range – Remember range(5) goes from 0 to 4, not 0 to 5!

The while Loop

The while loop is used when you don’t know exactly how many times you need to repeat something, but you know the condition that should be true for the loop to continue running. It’s like being told “climb stairs until you reach the first floor” – you don’t count the steps, you just keep going until you reach your destination.

Basic Syntax

Here’s the structure of a while loop in Python:

counter_variable = initial_value    # Initialization
while condition:                     # Condition check
    # statement(s) to be repeated
    counter_variable = counter_variable + 1    # Update/Increment

Let’s break down each part:

  • Initialization: You must set the counter variable before the loop starts
  • while: Keyword that starts the loop
  • condition: A condition that evaluates to True or False
  • :: The mandatory colon
  • Loop body: Indented statements that repeat
  • Update: You must manually update the counter inside the loop (unlike for loops!)

The Staircase Analogy

Let’s understand the difference between for and while using stairs:

Scenario 1: Using for loop (Fixed steps)

"Climb 10 steps"
  • You know exactly how many steps to climb
  • Even if the first floor is at step 7, you’ll climb all 10 steps
  • Use for loop when the number of repetitions is fixed

Scenario 2: Using while loop (Condition-based)

"Climb until you reach the first floor"
  • You don’t know how many steps are there
  • You stop as soon as you reach the first floor
  • If there are 7 steps, you climb 7; if there are 50 steps, you climb 50
  • Use while loop when you continue until a condition is met

How the while Loop Works: Step-by-Step

Let’s trace through this program:

x = 1
while x <= 3:
    print("Number:", x)
    x = x + 1

Execution trace:

  1. Before the loop:
    • Initialize x = 1
  2. First iteration:
    • Check condition: Is x <= 3? Is 1 <= 3? Yes → Enter loop
    • Print “Number: 1”
    • Update: x = 1 + 1 = 2
  3. Second iteration:
    • Check condition: Is 2 <= 3? Yes → Continue loop
    • Print “Number: 2”
    • Update: x = 2 + 1 = 3
  4. Third iteration:
    • Check condition: Is 3 <= 3? Yes → Continue loop
    • Print “Number: 3”
    • Update: x = 3 + 1 = 4
  5. Fourth check:
    • Check condition: Is 4 <= 3? No → Exit loop
    • Move to next statement after the loop

Output:

Number: 1
Number: 2
Number: 3

Key Differences: for vs while

Featurefor Loopwhile Loop
When to useKnow the number of iterationsDon’t know the number of iterations
Counter incrementAutomaticManual (you must write it)
InitializationInside the loop statementBefore the loop
Best forFixed repetitions, iterating through listsCondition-based repetitions

Example 1: Printing Numbers 1 to 5

num = 1
while num <= 5:
    print(num)
    num = num + 1

Output:

1
2
3
4
5

Notice the three parts clearly:

  • Initialization: num = 1 (before the loop)
  • Condition: num <= 5 (in the while statement)
  • Update: num = num + 1 (inside the loop)

Example 2: Password Checker

Here’s a practical example where while is more suitable than for:

correct_password = "python123"
user_input = ""

while user_input != correct_password:
    user_input = input("Enter password: ")
    if user_input != correct_password:
        print("Wrong password! Try again.")

print("Access granted!")

Why while is better here:

  • We don’t know how many attempts the user will need
  • The loop continues until the correct password is entered
  • It could run 1 time or 100 times – we can’t predict

Example 3: Counting Down

countdown = 5
while countdown > 0:
    print(countdown)
    countdown = countdown - 1
print("Blast off!")

Output:

5
4
3
2
1
Blast off!

⚠️ Warning: The Infinite Loop Problem

The most common mistake with while loops is forgetting to update the counter. This creates an infinite loop – a loop that never stops!

Bad Example (Don’t do this!):

x = 1
while x <= 5:
    print(x)
    # Forgot to write: x = x + 1

This loop will print 1 forever because x never changes, so the condition x <= 5 is always true!

If you accidentally create an infinite loop: Press Ctrl + C in your terminal to stop the program.

Shortcut: The += Operator

Instead of writing x = x + 1, Python allows a shortcut:

x += 1    # Same as x = x + 1
x += 2    # Same as x = x + 2
x -= 1    # Same as x = x - 1

So our earlier example can be written as:

num = 1
while num <= 5:
    print(num)
    num += 1

This makes the code cleaner and easier to read!

✏️ Try It Yourself!

  1. Write a while loop that prints numbers from 10 down to 1.
  2. Create a program that keeps asking the user to enter a number until they enter 0.
  3. Write a program that prints all multiples of 3 from 3 to 30 using a while loop.

💡 Remember:

  • Always initialize the counter before the while loop
  • Always update the counter inside the loop (or you’ll get an infinite loop!)
  • Use while when the number of iterations depends on a condition
  • Use for when you know exactly how many times to repeat

Looping Through Lists

One of the most powerful features of the for loop is its ability to automatically go through each item in a list. This is extremely useful and makes Python code very clean and readable.

What You Need to Know About Lists

Before we dive into looping through lists, let’s quickly recap what a list is:

fruits = ["Apple", "Banana", "Mango"]
  • A list is a collection of items enclosed in square brackets [ ]
  • Items are separated by commas
  • Each item has a position (index) starting from 0
Index:    0         1         2
       ["Apple", "Banana", "Mango"]

Traditional Way (Using Index)

If you wanted to print all fruits, you could do this:

fruits = ["Apple", "Banana", "Mango"]
print(fruits[0])
print(fruits[1])
print(fruits[2]ˀ

But what if you had 100 fruits? This would be very tedious!

You could also use a counter:

fruits = ["Apple", "Banana", "Mango"]
for i in range(3):
    print(fruits[i])

This works, but there’s a much better way!

The Pythonic Way: Direct Iteration

Python allows you to loop through a list directly without using indices:

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

How It Works

Let’s understand what’s happening step-by-step:

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

Execution trace:

  1. First iteration:
    • fruit takes the value of the first item: "Apple"
    • Print “Apple”
    • Control goes back to the loop
  2. Second iteration:
    • fruit takes the value of the second item: "Banana"
    • Print “Banana”
    • Control goes back to the loop
  3. Third iteration:
    • fruit takes the value of the third item: "Mango"
    • Print “Mango”
    • Control goes back to the loop
  4. Loop ends:
    • No more items in the list
    • Control moves to the next statement after the loop

Understanding the Counter Variable

In this type of loop, the counter variable (fruit in our example) is not a number – it actually holds the value of each item in the list!

Think of it this way:

  • First time: fruit = "Apple" (the actual string, not index 0)
  • Second time: fruit = "Banana" (the actual string, not index 1)
  • Third time: fruit = "Mango" (the actual string, not index 2)

You can name this variable anything you want, but it’s good practice to use meaningful names:

colors = ["Red", "Blue", "Green", "Yellow"]
for color in colors:
    print(color)
numbers = [10, 20, 30, 40, 50]
for num in numbers:
    print(num)

The Best Part: No Need to Know List Length!

The beauty of this approach is that Python automatically knows how long your list is:

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

Now add more fruits:

fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes", "Pineapple"]
for fruit in fruits:
    print(fruit)

The same loop code works perfectly! You don’t need to change range(3) to range(6) or anything like that. Python handles it automatically.

Output:

Apple
Banana
Mango
Orange
Grapes
Pineapple

Example 1: List of Numbers

marks = [85, 92, 78, 95, 88]
for mark in marks:
    print("You scored:", mark)

Output:

You scored: 85
You scored: 92
You scored: 78
You scored: 95
You scored: 88

Example 2: Performing Calculations

numbers = [2, 4, 6, 8, 10]
total = 0

for num in numbers:
    total = total + num

print("Sum of all numbers:", total)

Output:

Sum of all numbers: 30

Example 3: Checking Weather Conditions

temperatures = [25, 30, 35, 28, 22]

for temp in temperatures:
    if temp > 30:
        print(temp, "degrees - It's hot!")
    else:
        print(temp, "degrees - Pleasant weather")

Output:

25 degrees - Pleasant weather
30 degrees - Pleasant weather
35 degrees - It's hot!
28 degrees - Pleasant weather
22 degrees - Pleasant weather

Lists of Different Data Types

You can loop through lists containing different types of data:

Strings:

subjects = ["Math", "Science", "English", "Hindi"]
for subject in subjects:
    print("I study", subject)

Numbers:

ages = [13, 14, 13, 15, 14]
for age in ages:
    print("Age:", age)

Mixed (not common, but possible):

mixed_list = ["Python", 100, "Programming", 50]
for item in mixed_list:
    print(item)

✏️ Try It Yourself!

  1. Create a list of your 5 favorite movies and print each one with the message “I love watching [movie name]”
  2. Create a list of numbers from 1 to 10 and print only the even numbers.
  3. Create a list of 5 cities you want to visit. Use a loop to print: “I want to visit [city name]”
  4. Challenge: Create a list of numbers and calculate their average using a loop.

Comparing Both Approaches

Using index (more complicated):

fruits = ["Apple", "Banana", "Mango"]
for i in range(len(fruits)):
    print(fruits[i])

Direct iteration (simpler and more Pythonic):

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

Both give the same output, but the second method is cleaner and easier to read!

💡 Key Takeaways:

  • Use for item in list_name: to loop through lists
  • The counter variable holds the actual item value, not the index
  • Python automatically knows when to stop (when the list ends)
  • This works for lists of any length
  • Choose meaningful variable names for better code readability

Nested Loops

A nested loop is simply a loop inside another loop. Just like you can have a box inside another box, you can have a loop inside another loop. This might sound complicated, but it’s actually quite logical once you understand how it works!

What Are Nested Loops?

When we say “nested,” we mean one loop is placed completely inside another loop. The loop that contains another loop is called the outer loop, and the loop inside it is called the inner loop.

Basic Structure:

for outer_counter in range(n):        # Outer loop
    for inner_counter in range(m):    # Inner loop
        # statements to execute

Real-Life Analogy

Think of a weekly class schedule:

  • Outer loop: Days of the week (Monday to Friday) – 5 iterations
  • Inner loop: Periods in each day (1st to 6th period) – 6 iterations
  • Total: 5 days × 6 periods = 30 periods in a week

For each day (outer loop), you go through all periods (inner loop).

How Nested Loops Work

Here’s the most important thing to understand:

The inner loop completes ALL its iterations for EACH iteration of the outer loop.

Let’s see a simple example:

for i in range(1, 4):           # Outer loop: i = 1, 2, 3
    for j in range(1, 3):       # Inner loop: j = 1, 2
        print(i, j)

Step-by-Step Execution Trace

Let’s trace through this program carefully:

Step 1: Outer loop starts

  • i = 1
  • Enter the outer loop
  • Now go to the inner loop

Step 2: Inner loop runs completely for i = 1

  • j = 1 → Print: 1 1
  • j = 2 → Print: 1 2
  • Inner loop ends (j reaches 3, which is not < 3)
  • Go back to outer loop

Step 3: Outer loop continues

  • i = 2
  • Enter inner loop again

Step 4: Inner loop runs completely for i = 2

  • j = 1 → Print: 2 1
  • j = 2 → Print: 2 2
  • Inner loop ends
  • Go back to outer loop

Step 5: Outer loop continues

  • i = 3
  • Enter inner loop again

Step 6: Inner loop runs completely for i = 3

  • j = 1 → Print: 3 1
  • j = 2 → Print: 3 2
  • Inner loop ends
  • Go back to outer loop

Step 7: Both loops end

  • i would become 4, but 4 is not < 4
  • Outer loop ends
  • Program continues after the nested loops

Complete Output:

1 1
1 2
2 1
2 2
3 1
3 2

Key Observation: The inner loop ran 2 times for each value of the outer loop. Since the outer loop ran 3 times, the inner statements executed 3 × 2 = 6 times total.

Visual Representation

Outer Loop (i)          Inner Loop (j)
    i = 1    ──────►    j = 1 (print 1 1)
                        j = 2 (print 1 2)

    i = 2    ──────►    j = 1 (print 2 1)
                        j = 2 (print 2 2)

    i = 3    ──────►    j = 1 (print 3 1)
                        j = 2 (print 3 2)

Example 1: Multiplication Table

Let’s create multiplication tables from 1 to 3:

for table_num in range(1, 4):           # Tables 1, 2, 3
    print("Table of", table_num)
    for multiplier in range(1, 11):     # 1 to 10
        result = table_num * multiplier
        print(table_num, "×", multiplier, "=", result)
    print()  # Blank line after each table

Output:

Table of 1
1 × 1 = 1
1 × 2 = 2
1 × 3 = 3
...
1 × 10 = 10

Table of 2
2 × 1 = 2
2 × 2 = 4
2 × 3 = 6
...
2 × 10 = 20

Table of 3
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
...
3 × 10 = 30

Example 2: Simple Pattern

Let’s print a simple pattern:

for row in range(1, 5):
    for col in range(1, 4):
        print("*", end=" ")
    print()  # Move to next line after each row

Output:

* * *
* * *
* * *
* * *

Explanation:

  • Outer loop runs 4 times (4 rows)
  • For each row, inner loop prints 3 stars
  • end=" " keeps stars on the same line with a space
  • print() at the end moves to the next line

Different Types of Nested Loops

You can nest different types of loops together:

1. for inside for (most common)

for i in range(3):
    for j in range(2):
        print(i, j)

2. while inside for

for round_num in range(1, 4):
    print("Round", round_num)
    position = 1
    while position <= 3:
        print("  Position", position)
        position += 1

Output:

Round 1
  Position 1
  Position 2
  Position 3
Round 2
  Position 1
  Position 2
  Position 3
Round 3
  Position 1
  Position 2
  Position 3

3. for inside while

round_num = 1
while round_num <= 2:
    print("Round", round_num, "results:")
    for position in range(1, 4):
        print("  Position", position)
    round_num += 1

Output:

Round 1 results:
  Position 1
  Position 2
  Position 3
Round 2 results:
  Position 1
  Position 2
  Position 3

Example 3: Student Marks Table

students = ["Amit", "Priya", "Rahul"]
subjects = ["Math", "Science", "English"]

for student in students:
    print("Marks for", student)
    for subject in subjects:
        marks = int(input("  Enter marks in " + subject + ": "))
    print()  # Blank line

This will ask for marks for each subject for each student!

Understanding Depth of Nesting

You can have more than two levels of nesting (though it’s rare and can make code hard to read):

for i in range(2):              # Level 1
    for j in range(2):          # Level 2
        for k in range(2):      # Level 3
            print(i, j, k)

This has three loops nested! It will print all combinations of i, j, and k.

✏️ Try It Yourself!

  1. Simple Pattern: Write a program to print this pattern: 1 1 2 1 2 3 1 2 3 4 Hint: The number of items in each row equals the row number
  2. Rectangle Pattern: Create a program that prints a rectangle of 5 rows and 7 stars in each row.
  3. Multiplication Practice: Write a program that prints multiplication tables from 2 to 5.
  4. Challenge: Print this pattern: * * * * * * * * * * * * * * *

Common Mistakes to Avoid

  1. Incorrect Indentation: for i in range(3): for j in range(2): print(i, j) # ❌ Wrong! Should be indented more
  2. Using the Same Counter Variable: for i in range(3): for i in range(2): # ❌ Don't reuse 'i'! print(i) Use different variable names: i and j, or row and col
  3. Forgetting What Loop You’re In:
    • Keep track of which counter belongs to which loop
    • Use meaningful names: Say, row and col instead of i and j when appropriate

💡 Key Takeaways:

  • The inner loop completes ALL iterations for EACH iteration of the outer loop
  • Total iterations = (outer loop iterations) × (inner loop iterations)
  • You can nest any type of loop inside any other type
  • Use proper indentation to show the nesting structure
  • Choose descriptive variable names for clarity
  • Nested loops are perfect for patterns, tables, and multi-dimensional data

Custom Increments

So far, we’ve been using loops where the counter increases by 1 each time (1, 2, 3, 4…). But what if you want to count by 2s, or 5s, or even count backwards? Python makes this easy!

The Three-Parameter range() Function

Remember that range() can take three parameters:

range(start, stop, step)
  • start: Where to begin counting
  • stop: Where to stop (remember: stop value is NOT included)
  • step: How much to increase (or decrease) each time

We’ve already seen:

  • range(5) → starts at 0, stops before 5, step is 1 (default)
  • range(1, 6) → starts at 1, stops before 6, step is 1 (default)

Now let’s explore the step parameter!

Incrementing by 2 (Even Numbers)

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

What happens:

  • Start at 2
  • Stop before 21
  • Increase by 2 each time

Output:

2
4
6
8
10
12
14
16
18
20

These are all the even numbers from 2 to 20!

Odd Numbers

To print odd numbers, start at 1 and increment by 2:

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

Output:

1
3
5
7
9
11
13
15
17
19

Understanding How It Works

Let’s trace range(2, 11, 3):

for num in range(2, 11, 3):
    print(num)

Execution:

  1. num = 2 (start value) → Print 2
  2. num = 2 + 3 = 5 → Print 5
  3. num = 5 + 3 = 8 → Print 8
  4. num = 8 + 3 = 11 → 11 is NOT less than 11, so stop

Output:

2
5
8

Counting Backwards (Negative Step)

You can use a negative step to count backwards!

for i in range(10, 0, -1):
    print(i)

Important: When counting backwards:

  • Start value must be GREATER than stop value
  • Step must be NEGATIVE

Output:

10
9
8
7
6
5
4
3
2
1

Note: We wrote range(10, 0, -1), so it prints from 10 down to 1 (stops before 0).

Example: Countdown Timer

print("Rocket launch countdown:")
for count in range(10, 0, -1):
    print(count)
print("Blast off! 🚀")

Output:

Rocket launch countdown:
10
9
8
7
6
5
4
3
2
1
Blast off! 🚀

Example: Printing Every 5th Number

for num in range(5, 51, 5):
    print(num, "is a multiple of 5")

Output:

5 is a multiple of 5
10 is a multiple of 5
15 is a multiple of 5
20 is a multiple of 5
25 is a multiple of 5
30 is a multiple of 5
35 is a multiple of 5
40 is a multiple of 5
45 is a multiple of 5
50 is a multiple of 5

Custom Increments in while Loops

You can also use custom increments in while loops by changing how you update the counter:

Incrementing by 2:

num = 2
while num <= 20:
    print(num)
    num += 2  # Same as num = num + 2

Output: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20

Incrementing by 3:

num = 2
while num <= 20:
    print(num)
    num += 3

Output:

2
5
8
11
14
17
20

Counting Down:

num = 10
while num >= 1:
    print(num)
    num -= 1  # Same as num = num - 1

Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

The += and = Operators (Shortcuts)

Python provides shortcut operators for incrementing and decrementing:

ShortcutFull FormMeaning
x += 1x = x + 1Increase x by 1
x += 2x = x + 2Increase x by 2
x += 5x = x + 5Increase x by 5
x -= 1x = x - 1Decrease x by 1
x -= 3x = x - 3Decrease x by 3
x *= 2x = x * 2Multiply x by 2
x /= 2x = x / 2Divide x by 2

Example:

score = 10
score += 5    # score becomes 15
score -= 3    # score becomes 12
score *= 2    # score becomes 24

Practical Examples

Example 1: Years Display

Print every 5th year from 2000 to 2025:

for year in range(2000, 2026, 5):
    print("Year:", year)

Output:

Year: 2000
Year: 2005
Year: 2010
Year: 2015
Year: 2020
Year: 2025

Example 2: Temperature Readings

Print temperatures from 100°C down to 0°C in steps of 10:

print("Temperature readings:")
for temp in range(100, -10, -10):
    print(temp, "°C")

Output:

Temperature readings:
100 °C
90 °C
80 °C
70 °C
60 °C
50 °C
40 °C
30 °C
20 °C
10 °C
0 °C

Example 3: Doubling Pattern

Print powers of 2 using a while loop:

num = 1
while num <= 100:
    print(num)
    num *= 2  # Double the value

Output:

1
2
4
8
16
32
64

Comparison: for vs while with Custom Increments

Using for loop (cleaner for regular increments):

for i in range(10, 0, -2):
    print(i)

Using while loop (more flexible):

i = 10
while i > 0:
    print(i)
    i -= 2

Both produce the same output: 10, 8, 6, 4, 2

✏️ Try It Yourself!

  1. Write a program to print all multiples of 7 from 7 to 70.
  2. Create a countdown from 50 to 10, decreasing by 5 each time.
  3. Print all odd numbers from 1 to 50.
  4. Challenge: Print the first 10 multiples of any number entered by the user. Enter a number: 6 6 12 18 24 30 36 42 48 54 60
  5. Challenge: Print numbers from 1 to 20, but skip multiples of 3. (Hint: You’ll need an if statement inside the loop!)

Common Mistakes to Avoid

  1. Wrong direction when counting backwards: for i in range(10, 0, 1): # ❌ Won't print anything! print(i) When start > stop, you MUST use a negative step.
  2. Forgetting to update in while loops: num = 2 while num <= 10: print(num) # ❌ Forgot num += 2, creates infinite loop!
  3. Step of 0: for i in range(1, 10, 0): # ❌ Error! Step cannot be 0 print(i)

💡 Key Takeaways:

  • Use range(start, stop, step) to control increment size
  • Positive step = counting up, Negative step = counting down
  • When counting down, start must be greater than stop
  • Use += and = for cleaner code
  • for loops handle regular increments automatically
  • while loops require manual increment/decrement

Loop Control: break and continue

Sometimes you need more control over how your loops run. You might want to:

  • Stop a loop completely when a certain condition is met
  • Skip a particular iteration and move to the next one

Python provides two powerful statements for this: break and continue.

The break Statement

The break statement immediately stops the loop and exits it completely. The program then continues with the next statement after the loop.

Syntax:

for/while condition:
    # some code
    if some_condition:
        break  # Exit the loop immediately
    # more code (won't run if break is executed)

Real-Life Analogy: Finding a Book

Imagine you’re in a library looking for a specific book on a shelf. You check books one by one:

  • Book 1: Not the one? Keep looking
  • Book 2: Not the one? Keep looking
  • Book 3: Found it! Stop searching (you don’t need to check the remaining books)

This is exactly what break does – once you find what you’re looking for, you stop the loop.

Example 1: Finding a Book

books = ["Math", "Science", "Python", "History", "Geography"]

for book in books:
    print("Checking", book)
    if book == "Python":
        print("Found my Python book!")
        break

print("Done searching!")

Output:

Checking Math
Checking Science
Checking Python
Found my Python book!
Done searching!

Notice: The loop stopped immediately after finding “Python”. It didn’t check “History” or “Geography”.

Example 2: Number Guessing Game

secret_number = 7
attempts = 0

while attempts < 5:
    guess = int(input("Guess the number (1-10): "))
    attempts += 1

    if guess == secret_number:
        print("Correct! You guessed it in", attempts, "attempts!")
        break
    else:
        print("Wrong! Try again.")
else:
    print("Sorry, you've run out of attempts!")

Sample Output:

Guess the number (1-10): 3
Wrong! Try again.
Guess the number (1-10): 7
Correct! You guessed it in 2 attempts!

The loop breaks as soon as the correct number is guessed, even if attempts are remaining.

Example 3: Stopping at a Condition

for num in range(1, 11):
    if num == 6:
        print("Reached 6, stopping!")
        break
    print(num)

Output:

1
2
3
4
5
Reached 6, stopping!

The continue Statement

The continue statement skips the rest of the current iteration and moves directly to the next iteration of the loop. Unlike break, it doesn’t exit the loop – it just skips to the next cycle.

Syntax:

for/while condition:
    # some code
    if some_condition:
        continue  # Skip rest and go to next iteration
    # this code is skipped if continue is executed

Real-Life Analogy: Checking Homework

A teacher is checking homework copies:

  • Copy 1: Complete ✓ – Grade it
  • Copy 2: Incomplete ✗ – Skip it, move to next
  • Copy 3: Complete ✓ – Grade it
  • Copy 4: Incomplete ✗ – Skip it, move to next

The teacher doesn’t stop checking completely (that would be break), but skips incomplete copies (that’s continue).

Example 1: Skipping a Number

for i in range(1, 6):
    if i == 3:
        continue  # Skip when i is 3
    print(i)

Output:

1
2
4
5

Notice: The number 3 is missing! When i == 3, the continue statement skipped the print(i) and went directly to the next iteration.

Example 2: Printing Only Even Numbers

for num in range(1, 11):
    if num % 2 != 0:  # If odd number
        continue      # Skip this iteration
    print(num, "is even")

Output:

2 is even
4 is even
6 is even
8 is even
10 is even

How it works:

  • For odd numbers (1, 3, 5, 7, 9), continue skips the print statement
  • For even numbers (2, 4, 6, 8, 10), the print statement executes

Example 3: Skipping Negative Numbers

numbers = [5, -2, 8, -7, 3, -1, 9]

print("Positive numbers only:")
for num in numbers:
    if num < 0:
        continue  # Skip negative numbers
    print(num)

Output:

Positive numbers only:
5
8
3
9

Key Differences: break vs continue

Featurebreakcontinue
ActionExits the loop completelySkips current iteration only
Loop continues?No – loop endsYes – moves to next iteration
When to useWhen you’ve found what you needWhen you want to skip certain cases
Code after itNot executed (in that loop)Not executed (in that iteration)

Visual Comparison

Using break:

for i in range(1, 6):
    if i == 3:
        break
    print(i)
print("After loop")

Output:

1
2
After loop

Loop stopped completely at 3.

Using continue:

for i in range(1, 6):
    if i == 3:
        continue
    print(i)
print("After loop")

Output:

1
2
4
5
After loop

Loop skipped 3 but continued with 4 and 5.

break and continue in Nested Loops

When used in nested loops, break and continue only affect the innermost loop they’re in.

Example: break in Nested Loop

for i in range(1, 4):
    print("Outer loop:", i)
    for j in range(1, 4):
        if j == 2:
            break  # Only breaks the inner loop
        print("  Inner loop:", j)

Output:

Outer loop: 1
  Inner loop: 1
Outer loop: 2
  Inner loop: 1
Outer loop: 3
  Inner loop: 1

The break only exits the inner loop, not the outer one.

Example: continue in Nested Loop

for i in range(1, 4):
    for j in range(1, 4):
        if j == 2:
            continue  # Only skips in inner loop
        print(i, j)

Output:

1 1
1 3
2 1
2 3
3 1
3 3

All combinations are printed except when j = 2.

Practical Applications

Example 1: Input Validation

while True:
    age = int(input("Enter your age (1-120): "))
    if age < 1 or age > 120:
        print("Invalid age! Try again.")
        continue  # Skip to next iteration
    else:
        print("Age accepted:", age)
        break  # Exit the loop

Example 2: Menu System

while True:
    print("\\n--- Menu ---")
    print("1. Play")
    print("2. Settings")
    print("3. Exit")

    choice = input("Enter choice: ")

    if choice == "1":
        print("Starting game...")
    elif choice == "2":
        print("Opening settings...")
    elif choice == "3":
        print("Goodbye!")
        break  # Exit the menu loop
    else:
        print("Invalid choice!")
        continue  # Skip to show menu again

Example 3: Processing Valid Data

marks = [85, -5, 92, 150, 78, 88]  # Some invalid marks

print("Valid marks:")
for mark in marks:
    if mark < 0 or mark > 100:
        continue  # Skip invalid marks
    print(mark)

Output:

Valid marks:
85
92
78
88

✏️ Try It Yourself!

  1. Write a program that prints numbers from 1 to 10 but skips 5.
  2. Create a program that asks the user to enter numbers. If the user enters 0, stop the program. Use break.
  3. Print all numbers from 1 to 20 except multiples of 3. Use continue.
  4. Challenge: Write a program that searches for a specific name in a list. If found, print “Found!” and stop. If not found after checking all names, print “Not found.”
  5. Challenge: Create a simple ATM program that keeps asking for a PIN until the correct one is entered (use break when correct, continue when wrong).

⚠️ Important Notes and Best Practices

  1. Don’t Overuse break and continue
    • They can make code harder to read and understand
    • Often, a well-designed condition is better
    • Use them when they genuinely make code clearer
  2. Good Use Case: # Finding an item - good use of break for item in large_list: if item == target: print("Found!") break
  3. Could Be Avoided: # This could be written without continue for num in range(10): if num != 5: # Just use a normal if instead print(num)
  4. Avoid in Nested Loops When Possible:
    • Can make code confusing
    • Consider restructuring or using functions

💡 Key Takeaways:

  • break exits the loop completely
  • continue skips the current iteration and moves to the next
  • Both only affect the innermost loop they’re in
  • Use them to make your code more efficient and readable
  • Don’t overuse – sometimes a simple if statement is better
  • They work with both for and while loops

Tips and Best Practices

Now that you’ve learned about loops, let’s look at some helpful tips and best practices that will make you a better programmer!

1. Choose Meaningful Variable Names

Bad Examples:

for x in range(10):
    print(x)

for a in students:
    print(a)

Good Examples:

for count in range(10):
    print(count)

for student in students:
    print(student)

Why it matters: Good variable names make your code easier to read and understand, especially when you come back to it later!

Tips:

  • For simple counters: i, j, k are acceptable
  • For lists: Use singular form of the list name
    • for student in students
    • for book in books
    • for number in numbers
  • For meaningful counters: day, month, row, column, attempt

2. Remember the range() Rules

Important Facts:

  • range(5) gives you: 0, 1, 2, 3, 4 (NOT 5!)
  • range(1, 6) gives you: 1, 2, 3, 4, 5 (stops BEFORE 6)
  • Always: stop value is excluded

Common Mistake:

# Want to print 1 to 10
for i in range(1, 10):  # ❌ This only goes to 9!
    print(i)

Correct Way:

# Want to print 1 to 10
for i in range(1, 11):  # ✓ Correct!
    print(i)

Helpful Trick: If you want numbers 1 to N, use range(1, N+1)

3. Don’t Forget the Colon!

Common Error:

for i in range(5)  # ❌ Missing colon
    print(i)

Correct:

for i in range(5):  # ✓ Colon is here
    print(i)

Memory Tip: Think of the colon as saying “here’s what to do:”

4. Indentation is Critical

Python uses indentation (spaces) to know what’s inside the loop and what’s outside.

Wrong Indentation:

for i in range(3):
print(i)  # ❌ Not indented - will cause error

Correct Indentation:

for i in range(3):
    print(i)  # ✓ Properly indented (4 spaces)

With Multiple Statements:

for i in range(3):
    print("Number:", i)      # Inside loop
    print("Square:", i * i)  # Inside loop
print("Loop finished")       # Outside loop

Tip: Use 4 spaces for indentation (most Python editors do this automatically when you press Tab).

5. Choose the Right Loop

Use for loop when:

  • You know the exact number of iterations
  • You’re iterating through a list
  • You’re working with a range of numbers

Examples:

# Print 10 times - use for
for i in range(10):
    print("Hello")

# Go through a list - use for
for fruit in fruits:
    print(fruit)

Use while loop when:

  • You don’t know how many iterations you’ll need
  • The loop depends on a condition that might change
  • You’re waiting for user input

Examples:

# Keep asking until correct - use while
while password != "correct":
    password = input("Enter password: ")

# Continue until a condition is met - use while
while balance > 0:
    # do something
    balance -= 100

6. Avoid Infinite Loops in while

The Problem:

count = 1
while count <= 5:
    print(count)
    # ❌ Forgot to increment count!
    # This will print 1 forever!

The Solution:

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

Safety Check: Always ask yourself: “Is the counter changing inside the loop?”

Emergency Exit: If you accidentally create an infinite loop, press Ctrl + C to stop the program.

7. Be Careful with Nested Loops

Keep It Simple:

  • Don’t nest more than 2-3 levels deep
  • Use meaningful variable names
  • Add comments to explain what each loop does

Good Example:

# Print a multiplication table
for table_number in range(1, 4):      # Which table
    for multiplier in range(1, 11):   # 1 to 10
        result = table_number * multiplier
        print(table_number, "×", multiplier, "=", result)

Tip: If your nested loops are getting confusing, consider breaking them into separate functions (you’ll learn about functions in the next lesson!).

8. Test with Small Numbers First

When writing a new loop, test it with small values first!

Example:

# Instead of starting with this:
for i in range(1, 1001):  # 1000 iterations!
    print(i)

# First test with this:
for i in range(1, 6):  # Just 5 iterations
    print(i)
# If it works correctly, then increase the range

Why? It’s easier to spot errors with less output!

9. Use break and continue Wisely

Good Use of break:

# Searching for something specific
for student in students:
    if student == "Rahul":
        print("Found Rahul!")
        break  # No need to continue searching

Overusing continue:

# Unnecessary continue
for i in range(10):
    if i == 5:
        continue
    print(i)

# Better way - just use if
for i in range(10):
    if i != 5:
        print(i)

Tip: If you find yourself using too many break and continue statements, think about redesigning your loop logic.

10. Add Comments for Complex Loops

Without Comments:

for i in range(1, 11):
    for j in range(1, 11):
        print(i * j, end=" ")
    print()

With Comments:

# Print a multiplication table grid (1-10)
for i in range(1, 11):      # Rows
    for j in range(1, 11):  # Columns
        print(i * j, end=" ")
    print()  # New line after each row

Tip: Comments help others (and future you!) understand what your code does.

11. Don’t Modify the List You’re Iterating Over

Dangerous:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        numbers.remove(num)  # ❌ Don't do this!

Safe Alternative:

numbers = [1, 2, 3, 4, 5]
new_numbers = []
for num in numbers:
    if num != 3:
        new_numbers.append(num)  # ✓ Create a new list

Why? Modifying a list while looping through it can cause unexpected behavior and errors.

12. Practice, Practice, Practice!

The Best Way to Learn Loops:

  1. Type the code yourself (don’t just read it)
  2. Experiment by changing values
  3. Try to predict the output before running
  4. Make mistakes and learn from them
  5. Solve different types of problems

Remember: Everyone makes mistakes when learning! Syntax errors are completely normal. Don’t get discouraged – each error teaches you something!

13. Use print() for Debugging

When your loop isn’t working as expected, add print() statements to see what’s happening:

Example:

for i in range(1, 4):
    print("i is:", i)  # Debug statement
    for j in range(1, 3):
        print("  j is:", j)  # Debug statement
        print("  Product:", i * j)

This helps you understand how the counters are changing!

14. Learn from Your Errors

Common Error Messages and What They Mean:

1. IndentationError:

IndentationError: expected an indented block

Fix: Add proper indentation after the colon

2. SyntaxError:

SyntaxError: invalid syntax

Fix: Check for missing colons, parentheses, or quotes

3. NameError:

NameError: name 'x' is not defined

Fix: Make sure you’ve initialized your variables

Remember: Error messages are your friends! They tell you exactly what’s wrong.

💡 Golden Rules of Loops:

✓ Always initialize your counter (especially for while loops)

✓ Don’t forget the colon after the loop statement

✓ Indent everything that should be inside the loop

✓ Update the counter in while loops (or you’ll get an infinite loop!)

✓ Use meaningful variable names

✓ Test with small values first

✓ Comment your code when it gets complex

✓ Practice regularly to build confidence

Quick Reference Guide

This is your handy cheat sheet for loops! Refer to this section for quick reference while coding.

Loop Syntax at a Glance

for Loop

for counter_variable in range(start, stop, step):
    # statements to repeat
    # must be indented

Examples:

for i in range(5):           # 0, 1, 2, 3, 4
for i in range(1, 6):        # 1, 2, 3, 4, 5
for i in range(2, 11, 2):    # 2, 4, 6, 8, 10
for i in range(10, 0, -1):   # 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

while Loop

counter = initial_value          # Initialize
while condition:                 # Condition
    # statements to repeat
    counter = counter + 1        # Update (IMPORTANT!)

Example:

num = 1
while num <= 5:
    print(num)
    num += 1

Looping Through Lists

for item in list_name:
    # statements using item

Example:

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

Nested Loops

for outer_counter in range(n):
    for inner_counter in range(m):
        # statements

range() Function Quick Guide

SyntaxMeaningExampleOutput
range(stop)Start at 0, end before stop, step 1range(5)0, 1, 2, 3, 4
range(start, stop)Start at start, end before stop, step 1range(2, 6)2, 3, 4, 5
range(start, stop, step)Custom start, stop, and steprange(0, 10, 2)0, 2, 4, 6, 8

Important: The stop value is NEVER included!

Common Increment/Decrement Patterns

PatternCode
Count up by 1range(1, 11) → 1, 2, 3…10
Count down by 1range(10, 0, -1) → 10, 9, 8…1
Even numbersrange(2, 21, 2) → 2, 4, 6…20
Odd numbersrange(1, 21, 2) → 1, 3, 5…19
Multiples of 5range(5, 51, 5) → 5, 10, 15…50

Shortcut Operators

OperatorLong FormMeaning
x += 1x = x + 1Increase by 1
x += 5x = x + 5Increase by 5
x -= 1x = x - 1Decrease by 1
x -= 3x = x - 3Decrease by 3
x *= 2x = x * 2Multiply by 2
x /= 2x = x / 2Divide by 2

Loop Control Statements

break – Exit the Loop

for i in range(10):
    if i == 5:
        break  # Stop the loop completely
    print(i)
# Output: 0, 1, 2, 3, 4

continue – Skip Current Iteration

for i in range(5):
    if i == 2:
        continue  # Skip this iteration
    print(i)
# Output: 0, 1, 3, 4

When to Use Which Loop?

Use for Loop When…Use while Loop When…
✓ You know the exact number of iterations✓ You don’t know how many iterations needed
✓ Iterating through a list✓ Waiting for a condition to become false
✓ Working with a range of numbers✓ Taking repeated user input
✓ Counting with regular increments✓ The loop depends on changing conditions

Examples:

  • Print 1 to 100 → Use for
  • Go through a shopping list → Use for
  • Keep asking for password until correct → Use while
  • Continue until user types “quit” → Use while

Common Mistakes Checklist

❌ Mistake✓ Correct
for i in range(5) (missing colon)for i in range(5):
Not indenting loop bodyIndent with 4 spaces
range(1, 5) expecting 1-5Use range(1, 6) for 1-5
Forgetting to update while counterAlways include counter += 1
Using same variable in nested loopsUse different names: i, j, k

Comparison: for vs while

Printing 1 to 5

Using for:

for num in range(1, 6):
    print(num)

Using while:

num = 1
while num <= 5:
    print(num)
    num += 1

Both produce the same output: 1, 2, 3, 4, 5

Key Difference:

  • for loop: Counter increments automatically
  • while loop: You must increment the counter manually

Essential Loop Patterns

Pattern 1: Accumulating a Sum

numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
    total += num
print("Sum:", total)  # 150

Pattern 2: Counting Items

fruits = ["Apple", "Banana", "Mango", "Apple"]
count = 0
for fruit in fruits:
    if fruit == "Apple":
        count += 1
print("Apples:", count)  # 2

Pattern 3: Finding Maximum

numbers = [45, 78, 23, 89, 56]
maximum = numbers[0]
for num in numbers:
    if num > maximum:
        maximum = num
print("Max:", maximum)  # 89

Pattern 4: Building a New List

numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
    squares.append(num * num)
print(squares)  # [1, 4, 9, 16, 25]

Nested Loop Pattern

Printing a Grid:

for row in range(3):
    for col in range(4):
        print("*", end=" ")
    print()  # New line after each row

Output:

* * * *
* * * *
* * * *

Quick Decision Tree

Do you know how many times to repeat?
    |
    ├── YES → Use for loop
    |         |
    |         ├── Iterating through a list? → for item in list
    |         └── Using numbers? → for i in range(...)
    |
    └── NO → Use while loop
              (with proper initialization and increment!)

Key Formulas

Total iterations in nested loops:

Total iterations = Outer loop iterations × Inner loop iterations

Example:

for i in range(3):      # 3 iterations
    for j in range(4):  # 4 iterations
        print(i, j)
# Total: 3 × 4 = 12 times

Troubleshooting Guide

ProblemPossible CauseSolution
Loop runs foreverForgot to update counter in whileAdd counter += 1
Loop doesn’t run at allWrong range valuesCheck start < stop for positive step
Missing numbers in outputUsing wrong rangeRemember: range(5) gives 0-4, not 1-5
Indentation errorInconsistent spaces/tabsUse 4 spaces consistently
Loop stops too earlyUsing break incorrectlyReview break logic

Remember These Points!

🔑 Always use a colon (:) after loop statements

🔑 Indent code inside loops (4 spaces)

🔑 range(n) goes from 0 to n-1, not 0 to n

🔑 Update counters in while loops to avoid infinite loops

🔑 break exits the loop, continue skips to next iteration

🔑 Inner loop completes fully for each outer loop iteration

🔑 Use Ctrl+C to stop an infinite loop

Practice Exercises

Test your understanding of loops with these exercises. Try to answer them without looking at the answers first!


A. Fill in the Blanks

  1. A loop is a programming structure that allows you to __________ a set of instructions multiple times.
  2. The __________ loop is used when you know exactly how many times you want to repeat a task.
  3. In a while loop, you must manually __________ the counter variable to avoid an infinite loop.
  4. The range(5) function generates numbers from __________ to __________.
  5. The __________ statement is used to exit a loop immediately.
  6. The __________ statement skips the current iteration and moves to the next one.
  7. When looping through a list using for fruit in fruits:, the variable fruit holds the __________ of each item, not the index.
  8. In nested loops, the __________ loop completes all its iterations for each iteration of the __________ loop.
  9. The shortcut operator x += 3 is the same as writing __________.
  10. To count backwards from 10 to 1, you would use range(10, 0, __________).

B. True or False

  1. The range(1, 10) function will generate numbers from 1 to 10 including both 1 and 10.
  2. A for loop automatically increments the counter variable, while a while loop requires manual increment.
  3. You can use a negative step value in the range() function to count backwards.
  4. The continue statement completely exits the loop and moves to the next statement after the loop.
  5. Nested loops can only be created using two for loops; you cannot mix for and while loops.
  6. When you write for i in range(5):, the loop will execute exactly 5 times.
  7. An infinite loop occurs when the condition in a while loop never becomes false.
  8. The break statement only affects the innermost loop when used in nested loops.
  9. It is good programming practice to use meaningful variable names like student instead of x when looping through a list of students.
  10. The statement range(2, 20, 2) will generate all even numbers from 2 to 20 including 20.

C. Multiple Choice Questions

1. What will be the output of the following code?

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

a) 1 2 3

b) 0 1 2

c) 0 1 2 3

d) 1 2

2. Which loop should you use when you don’t know how many times the loop will run?

a) for loop

b) while loop

c) nested loop

d) infinite loop

3. What does the following code print?

for i in range(1, 6, 2):
    print(i, end=" ")

a) 1 2 3 4 5

b) 1 3 5

c) 2 4 6

d) 1 3 5 7

4. How many times will “Hello” be printed?

for i in range(2):
    for j in range(3):
        print("Hello")

a) 2

b) 3

c) 5

d) 6

5. What happens when a break statement is executed inside a loop?

a) The current iteration is skipped

b) The loop exits completely

c) The loop starts from the beginning

d) The program terminates

6. Which of the following will create an infinite loop?

a) for i in range(10):

b) while True:

c) for i in range(1, 5):

d) while i < 5: print(i); i += 1

7. What is the output of this code?

for i in range(5):
    if i == 3:
        continue
    print(i, end=" ")

a) 0 1 2 3 4

b) 0 1 2 4

c) 1 2 4 5

d) 0 1 2

8. To print numbers from 10 down to 1, which range() would you use?

a) range(10, 1)

b) range(10, 0, -1)

c) range(1, 10, -1)

d) range(10, 1, -1)


D. Short Answer Questions (Answer in not more than 40 words)

  1. What is the difference between a for loop and a while loop? When would you use each?
  2. Explain what happens when you write for fruit in fruits: where fruits is a list.
  3. Why is it important to update the counter variable in a while loop?
  4. What is a nested loop? Give one example of when you might need to use it.
  5. Explain the difference between the break and continue statements.
  6. What does range(2, 11, 3) produce? List all the numbers.
  7. Why does range(5) give you numbers 0 to 4 instead of 1 to 5?
  8. What is the purpose of using meaningful variable names in loops?

E. Descriptive Questions (Answer in not more than 70 words)

  1. Explain how a for loop works with the help of an example. Include the three main components: initialization, condition, and increment.
  2. Write a short note on infinite loops. What causes them and how can they be prevented? What should you do if you accidentally create one?
  3. Describe how nested loops work. Use the example of printing a multiplication table to explain how the outer and inner loops interact.
  4. Explain the concept of loop control using break and continue. Provide scenarios where each would be appropriately used.
  5. Compare and contrast for loops and while loops. Discuss their syntax differences and explain with examples when each should be used.
  6. Explain how you can use loops to iterate through a list in Python. What are the advantages of using for item in list instead of using indices?
  7. Describe the range() function and its three parameters. Provide examples showing how different parameter combinations produce different sequences.
  8. Discuss three common mistakes beginners make when writing loops and explain how to avoid them.

Answer Key

A. Fill in the Blanks – Answers

Question 1: A loop is a programming structure that allows you to __________ a set of instructions multiple times.

Answer: repeat

Question 2: The __________ loop is used when you know exactly how many times you want to repeat a task.

Answer: for

Question 3: In a while loop, you must manually __________ the counter variable to avoid an infinite loop.

Answer: update / increment

Question 4: The range(5) function generates numbers from __________ to __________.

Answer: 0 to 4 (or 0, 4)

Question 5: The __________ statement is used to exit a loop immediately.

Answer: break

Question 6: The __________ statement skips the current iteration and moves to the next one.

Answer: continue

Question 7: When looping through a list using for fruit in fruits:, the variable fruit holds the __________ of each item, not the index.

Answer: value / actual value

Question 8: In nested loops, the __________ loop completes all its iterations for each iteration of the __________ loop.

Answer: inner, outer

Question 9: The shortcut operator x += 3 is the same as writing __________.

Answer: x = x + 3

Question 10: To count backwards from 10 to 1, you would use range(10, 0, __________).

Answer: -1


B. True or False – Answers

Question 1: The range(1, 10) function will generate numbers from 1 to 10 including both 1 and 10.

Answer: False

Explanation: range(1, 10) generates numbers from 1 to 9. The stop value (10) is excluded.

Question 2: A for loop automatically increments the counter variable, while a while loop requires manual increment.

Answer: True

Explanation: The for loop handles the counter automatically, but in a while loop, you must write the increment statement yourself.

Question 3: You can use a negative step value in the range() function to count backwards.

Answer: True

Explanation: Using a negative step like range(10, 0, -1) counts backwards from 10 to 1.

Question 4: The continue statement completely exits the loop and moves to the next statement after the loop.

Answer: False

Explanation: The continue statement only skips the current iteration and moves to the next iteration. It’s break that exits the loop completely.

Question 5: Nested loops can only be created using two for loops; you cannot mix for and while loops.

Answer: False

Explanation: You can nest any type of loop inside another. You can have a while inside a for, a for inside a while, or any combination.

Question 6: When you write for i in range(5):, the loop will execute exactly 5 times.

Answer: True

Explanation: range(5) generates 5 values (0, 1, 2, 3, 4), so the loop executes 5 times.

Question 7: An infinite loop occurs when the condition in a while loop never becomes false.

Answer: True

Explanation: If the condition remains true forever (usually because the counter isn’t updated), the loop runs infinitely.

Question 8: The break statement only affects the innermost loop when used in nested loops.

Answer: True

Explanation: When break is used in nested loops, it only exits the loop it’s directly in (the innermost one), not the outer loops.

Question 9: It is good programming practice to use meaningful variable names like student instead of x when looping through a list of students.

Answer: True

Explanation: Meaningful names make code more readable and easier to understand.

Question 10: The statement range(2, 20, 2) will generate all even numbers from 2 to 20 including 20.

Answer: True

Explanation: range(2, 20, 2) generates 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. The stop value is 20, but since the last value generated (18 + 2 = 20) equals the stop value, it is included.


C. Multiple Choice Questions – Answers

Question 1: What will be the output of the following code?

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

Answer: b) 0 1 2

Explanation: range(3) generates 0, 1, 2 (starting from 0 by default, stopping before 3).

Question 2: Which loop should you use when you don’t know how many times the loop will run?

Answer: b) while loop

Explanation: Use while loops when the number of iterations depends on a condition rather than a fixed count.

Question 3: What does the following code print?

for i in range(1, 6, 2):
    print(i, end=" ")

Answer: b) 1 3 5

Explanation: Starts at 1, stops before 6, increments by 2: 1, 3, 5.

Question 4: How many times will “Hello” be printed?

for i in range(2):
    for j in range(3):
        print("Hello")

Answer: d) 6

Explanation: Outer loop runs 2 times, inner loop runs 3 times. Total: 2 × 3 = 6 times.

Question 5: What happens when a break statement is executed inside a loop?

Answer: b) The loop exits completely

Explanation: break immediately terminates the loop and moves to the next statement after the loop.

Question 6: Which of the following will create an infinite loop?

Answer: b) while True:

Explanation: while True: creates an infinite loop because the condition is always true (unless there’s a break inside).

Question 7: What is the output of this code?

for i in range(5):
    if i == 3:
        continue
    print(i, end=" ")

Answer: b) 0 1 2 4

Explanation: When i equals 3, continue skips the print statement, so 3 is not printed.

Question 8: To print numbers from 10 down to 1, which range() would you use?

Answer: b) range(10, 0, -1)

Explanation: Start at 10, stop before 0, decrement by 1: prints 10, 9, 8, 7, 6, 5, 4, 3, 2, 1.


D. Short Answer Questions – Answers (Maximum 40 words)

Question 1: What is the difference between a for loop and a while loop? When would you use each?

Answer: A for loop is used when you know the exact number of iterations needed; it automatically handles the counter. A while loop is used when iterations depend on a condition; you must manually update the counter. Use for for fixed repetitions, while for condition-based repetitions.

Question 2: Explain what happens when you write for fruit in fruits: where fruits is a list.

Answer: Python automatically iterates through each element in the fruits list. The variable fruit takes the actual value of each item (not the index) one by one. The loop continues until all items have been processed, eliminating the need to use indices or know the list length.

Question 3: Why is it important to update the counter variable in a while loop?

Answer: Updating the counter is essential to eventually make the loop condition false. Without updating, the condition remains true forever, creating an infinite loop that never stops executing. The counter must change to ensure the loop terminates properly and the program continues.

Question 4: What is a nested loop? Give one example of when you might need to use it.

Answer: A nested loop is a loop inside another loop. The inner loop completes all iterations for each iteration of the outer loop. Example: Printing a multiplication table where the outer loop selects the table number and the inner loop multiplies it by numbers 1-10.

Question 5: Explain the difference between the break and continue statements.

Answer: break immediately exits the entire loop and moves to the next statement after the loop. continue skips only the current iteration and moves to the next iteration of the same loop. break ends the loop; continue just skips one cycle.

Question 6: What does range(2, 11, 3) produce? List all the numbers.

Answer: range(2, 11, 3) produces: 2, 5, 8. It starts at 2, stops before 11, and increments by 3 each time (2, 2+3=5, 5+3=8, 8+3=11 which is excluded).

Question 7: Why does range(5) give you numbers 0 to 4 instead of 1 to 5?

Answer: Python uses zero-based indexing, so range(5) starts at 0 by default and stops before 5, generating five numbers: 0, 1, 2, 3, 4. The stop value is always excluded. To get 1-5, use range(1, 6).

Question 8: What is the purpose of using meaningful variable names in loops?

Answer: Meaningful variable names make code easier to read, understand, and maintain. Instead of generic names like x or i, using descriptive names like student or day clearly shows what the variable represents, helping both you and others understand the code’s purpose quickly.


E. Descriptive Questions – Answers (Maximum 70 words)

Question 1: Explain how a for loop works with the help of an example. Include the three main components: initialization, condition, and increment.

Answer: A for loop repeats code a specific number of times. Example: for i in range(1, 4): Here, initialization sets i=1, the condition checks if i<4, and Python automatically increments i by 1 after each iteration. The loop prints 1, 2, 3. Unlike while loops, for loops handle initialization and increment automatically, making them ideal when you know exactly how many repetitions are needed beforehand.

Question 2: Write a short note on infinite loops. What causes them and how can they be prevented? What should you do if you accidentally create one?

Answer: An infinite loop runs forever because its condition never becomes false. Common cause: forgetting to update the counter in a while loop (e.g., while x < 5: without x += 1). Prevention: Always ensure the counter updates inside the loop. Another cause is while True: without a break statement. If you create one accidentally, press Ctrl+C to stop program execution immediately.

Question 3: Describe how nested loops work. Use the example of printing a multiplication table to explain how the outer and inner loops interact.

Answer: In nested loops, an inner loop runs completely for each iteration of the outer loop. For multiplication tables: the outer loop (for table in range(1, 4):) selects which table (1, 2, 3), and for each table, the inner loop (for num in range(1, 11):) multiplies it by 1-10. Total iterations = outer × inner (3 × 10 = 30). The inner loop fully completes before the outer loop advances.

Question 4: Explain the concept of loop control using break and continue. Provide scenarios where each would be appropriately used.

Answer: break exits a loop immediately when a condition is met, like finding a specific item in a list—once found, searching stops. continue skips the current iteration and proceeds to the next, useful for skipping invalid data (e.g., negative numbers). Use break when the task is complete and further iterations are unnecessary. Use continue when certain iterations should be ignored but the loop should continue processing remaining items.

Question 5: Compare and contrast for loops and while loops. Discuss their syntax differences and explain with examples when each should be used.

Answer: for loops automatically manage counters and are ideal for known iterations: for i in range(10):. while loops require manual counter initialization and updates, suited for condition-based repetitions: x=1; while x<=5: x+=1. Key difference: for handles increment automatically; while needs explicit updates. Use for for iterating through lists or fixed counts. Use while for password validation, user input loops, or when iteration count is unknown beforehand.

Question 6: Explain how you can use loops to iterate through a list in Python. What are the advantages of using for item in list instead of using indices?

Answer: Python allows direct iteration: for fruit in fruits: where fruit takes each list value automatically. Advantages over index-based iteration: cleaner, more readable code; no need to know list length; avoids index errors; more “Pythonic.” The variable holds actual values, not positions. This method is simpler than for i in range(len(fruits)): followed by fruits[i], reducing complexity and potential errors while improving code clarity.

Question 7: Describe the range() function and its three parameters. Provide examples showing how different parameter combinations produce different sequences.

Answer: range() generates number sequences with three parameters: range(start, stop, step). range(5) produces 0-4 (default start=0, step=1). range(1, 6) produces 1-5 (custom start). range(2, 11, 2) produces even numbers 2-10 (custom step). range(10, 0, -1) produces 10-1 backwards (negative step). The stop value is always excluded. These combinations enable counting forwards, backwards, by any increment, making range() extremely versatile for loop control.

Question 8: Discuss three common mistakes beginners make when writing loops and explain how to avoid them.

Answer: (1) Missing colon: for i in range(5) causes syntax error—always add colon after loop statements. (2) Forgetting counter update in while loops creates infinite loops—always include counter += 1. (3) Incorrect indentation: Python requires consistent 4-space indentation for loop bodies; inconsistent spacing causes IndentationError. Prevention: carefully check syntax, always update while counters, and use proper indentation. Testing with small values helps catch these errors early.

Pin It on Pinterest

Share This