Loops, Break and Continue in Python

What are Loops?

Imagine you want to print "Hello" 100 times. Will you write print("Hello") 100 times? Obviously not.

That's where loops come in. Loops let you run the same code multiple times without repeating yourself.

Python has two types of loops:

  • for loop — when you know how many times to repeat
  • while loop — when you repeat until a condition becomes False

Part 1 — For Loop

Basic Syntax

for variable in something:
    # code to repeat

Simplest Example


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

Output:

Hello
Hello
Hello
Hello
Hello

It printed "Hello" 5 times. That's it. Simple.


Understanding range()

range() generates a sequence of numbers. It's used with for loops all the time.


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

Output:

0
1
2
3
4

Important: range(5) gives numbers 0 to 4 — not 1 to 5. It always starts from 0 by default and the end number is not included.


range() — Three Ways to Use It

range(stop) — starts from 0


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

range(start, stop) — custom start


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

range(start, stop, step) — custom step/jump


    for i in range(0, 10, 2):
        print(i)
    # prints: 0, 2, 4, 6, 8  (jumps by 2)


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


Using i Inside the Loop

The loop variable i holds the current number on each iteration. You can use it:


    for i in range(1, 6):
        print(f"{i} x 2 = {i * 2}")

Output:

1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5 x 2 = 10

Let's make a full multiplication table:


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

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

Output when num is 5:

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

Looping Through a String

For loops work on strings too — they go through each character one by one:


    name = "Gagan"

    for letter in name:
        print(letter)

Output:

G
a
g
a
n

For Loop with if — Combining What You Know


    for i in range(1, 21):
        if i % 2 == 0:
            print(f"{i} is even")
        else:
            print(f"{i} is odd")

Output:

1 is odd
2 is even
3 is odd
4 is even
...

This is where things start getting powerful — combining loops with conditions.


Accumulator Pattern — Very Important

One of the most common patterns in programming — using a variable to accumulate (collect/add up) values inside a loop:


    # Sum of numbers from 1 to 10
    total = 0

    for i in range(1, 11):
        total = total + i    # add current number to total
        # or shorthand: total += i

    print(f"Sum = {total}")   # Sum = 55

What happens step by step:

i=1  → total = 0 + 1 = 1
i=2  → total = 1 + 2 = 3
i=3  → total = 3 + 3 = 6
i=4  → total = 6 + 4 = 10
...
i=10 → total = 45 + 10 = 55

What is a While Loop?

A while loop keeps running as long as a condition is True. When the condition becomes False, it stops.

while condition:
    # code to repeat

Basic Example


    count = 1

    while count <= 5:
        print(f"Count is {count}")
        count += 1    # VERY IMPORTANT — update the variable

    print("Done!")

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Done!

How While Loop Works Step by Step

count = 1
Is 1 <= 5? Yes → print "Count is 1" → count becomes 2
Is 2 <= 5? Yes → print "Count is 2" → count becomes 3
Is 3 <= 5? Yes → print "Count is 3" → count becomes 4
Is 4 <= 5? Yes → print "Count is 4" → count becomes 5
Is 5 <= 5? Yes → print "Count is 5" → count becomes 6
Is 6 <= 5? No  → exit loop
print "Done!"

DANGER — Infinite Loop

If you forget to update the variable, the condition never becomes False and the loop runs forever. This is called an infinite loop and it will freeze your program:


    count = 1

    while count <= 5:
        print(count)
        # forgot count += 1 !!

This will print 1 forever and never stop. If this happens press Ctrl + C in the terminal to force stop the program.

Always make sure something inside the while loop moves it closer to the exit condition.


When to Use While vs For

Use for loop when you know exactly how many times to repeat:


    # Print 10 times — use for
    for i in range(10):
        print(i)

Use while loop when you don't know how many times — you repeat until something happens:


    # Keep asking until user types correct password — use while
    password = ""
    while password != "python123":
        password = input("Enter password: ")
    print("Access granted!")


Real World Example — Guessing Game


    secret_number = 7
    guess = 0
    attempts = 0

    print("=== Number Guessing Game ===")
    print("I'm thinking of a number between 1 and 10")

    while guess != secret_number:
        guess = int(input("Your guess: "))
        attempts += 1

        if guess < secret_number:
            print("Too low! Try again")
        elif guess > secret_number:
            print("Too high! Try again")
        else:
            print(f"Correct! You got it in {attempts} attempts!")

Output:

=== Number Guessing Game ===
I'm thinking of a number between 1 and 10
Your guess: 3
Too low! Try again
Your guess: 8
Too high! Try again
Your guess: 7
Correct! You got it in 3 attempts!

Break and Continue

break — Exit the Loop Immediately


    for i in range(1, 11):
        if i == 5:
            break        # stop the loop when i is 5
        print(i)

    print("Loop ended")

Output:

1
2
3
4
Loop ended

It never printed 5 or anything after — break exits the loop completely.


continue — Skip Current Iteration


    for i in range(1, 11):
        if i % 2 == 0:
            continue     # skip even numbers
        print(i)

Output:

1
3
5
7
9

continue skips the rest of the current loop cycle and jumps to the next one. Even numbers were skipped.


break in While Loop — Very Common Pattern


    print("=== ATM Machine ===")

    while True:              # loop runs forever...
        amount = int(input("Enter amount to withdraw (0 to exit): "))

        if amount == 0:
            print("Thank you. Goodbye!")
            break            # ...until user enters 0
        elif amount < 0:
            print("Invalid amount")
        else:
            print(f"Dispensing Rs.{amount}")
            print("Please collect your cash")

while True creates an intentional infinite loop, and break is used to exit it when needed. This is a very common and useful pattern.


Nested Loops — Loop Inside a Loop


    for i in range(1, 4):
        for j in range(1, 4):
            print(f"{i} x {j} = {i * j}")
        print("---")

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---

The outer loop runs 3 times. For each outer loop run, the inner loop runs 3 times completely. So total iterations = 3 x 3 = 9.


Exercise 🏋️

Two exercises — try both:

Exercise 1 — FizzBuzz (Classic Programming Challenge)

Print numbers from 1 to 30, but:

  • If the number is divisible by 3 → print "Fizz" instead of the number
  • If the number is divisible by 5 → print "Buzz" instead of the number
  • If divisible by both 3 and 5 → print "FizzBuzz"
  • Otherwise → print the number

Expected output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...

Hint: Use % operator and check divisible by 15 first for FizzBuzz case.

Exercise 2 — Simple Menu

Build a program with a menu that keeps showing until user exits:

=== Menu ===
1. Say Hello
2. Show current count
3. Exit

Enter choice: 
  • Choice 1 → print "Hello there!"
  • Choice 2 → print how many times menu has been shown
  • Choice 3 → exit the loop and print "Goodbye!"
  • Any other input → print "Invalid choice"


No comments:

Post a Comment

Loops, Break and Continue in Python

What are Loops? Imagine you want to print "Hello" 100 times. Will you write print("Hello") 100 times? Obviously not. ...