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"


Control Flow If / Else Conditions in Python

What are Conditions?

So far your programs run line by line, top to bottom — every single line executes no matter what.

But real programs need to make decisions. Like:

  • If user is above 18 → allow access, else → deny
  • If score is above 90 → grade A, else → grade B
  • If it's raining → take umbrella, else → don't

This is called Control Flow — controlling which lines of code run based on conditions.


Real Life Analogy

Think of it like this:

If it's raining:
    Take an umbrella
Else:
    Wear sunglasses

Python does the exact same thing, just in code.


Basic Syntax


    if condition:
        # code runs if condition is True
    else:
        # code runs if condition is False

Very Important — Indentation: The code inside if and else must be indented (pushed inward with spaces or tab). Python uses indentation to understand which code belongs inside the if block.

VS Code does this automatically when you press Enter after the colon :.


Your First if/else Program


    age = int(input("Enter your age: "))

    if age >= 18:
        print("You are an adult")
        print("You can vote")
    else:
        print("You are a minor")
        print("You cannot vote yet")

Run it twice — once with age 20, once with age 15:

Enter your age: 20
You are an adult
You can vote

Enter your age: 15
You are a minor
You cannot vote yet

Comparison Operators

These are used to compare values inside conditions:

Operator

Meaning

Example

Result

==

Equal to

5 == 5

True

!=

Not equal to

5 != 3

True

> 

Greater than

10 > 5

True

< 

Less than

3 < 7

True

>=

Greater than or equal

5 >= 5

True

<=

Less than or equal

4 <= 6

True

Common beginner mistake:

  • = is for assigning a value → age = 22
  • == is for comparing values → age == 22

These are completely different. Don't mix them up!

age = 22          # storing value 22 in age
print(age == 22)  # comparing — prints True
print(age == 25)  # comparing — prints False

elif — Multiple Conditions

What if you have more than two possibilities? Use elif (short for "else if"):


    score = int(input("Enter your score: "))

    if score >= 90:
        print("Grade: A")
    elif score >= 80:
        print("Grade: B")
    elif score >= 70:
        print("Grade: C")
    elif score >= 60:
        print("Grade: D")
    else:
        print("Grade: F — Please study harder!")

Output:

Enter your score: 85
Grade: B

Enter your score: 72
Grade: C

Enter your score: 45
Grade: F — Please study harder!

Python checks conditions from top to bottom and stops at the first one that is True. So order matters!


How Python Reads elif

Let's trace through what happens when score is 85:

Is 85 >= 90?  → No, skip
Is 85 >= 80?  → Yes! → Print "Grade: B" → Stop here

It never even checks the remaining elif and else blocks. Once a match is found, Python exits the whole if/elif/else chain.


if Without else

else is optional. Sometimes you only want to do something if a condition is true, and do nothing otherwise:


    temperature = int(input("Enter temperature: "))

    if temperature > 40:
        print("Warning: Extreme heat!")

    print("Have a nice day!")   # this always runs

Output when temp is 45:

Warning: Extreme heat!
Have a nice day!

Output when temp is 30:

Have a nice day!

Logical Operators — and, or, not

Sometimes one condition is not enough. You need to combine conditions:

and — Both conditions must be True


    age = int(input("Enter age: "))
    has_id = input("Do you have ID? (yes/no): ")

    if age >= 18 and has_id == "yes":
        print("Entry allowed")
    else:
        print("Entry denied")

Both age >= 18 AND has_id == "yes" must be true. If even one is false — entry denied.


or — At least one condition must be True


    day = input("Enter day: ")

    if day == "Saturday" or day == "Sunday":
        print("It's the weekend!")
    else:
        print("It's a weekday")


not — Reverses True to False and vice versa


    is_raining = False

    if not is_raining:
        print("Great weather for a walk!")
    else:
        print("Stay inside")

not False becomes True so the first block runs.


Nested if — if inside if

You can put an if block inside another if block:


    age = int(input("Enter age: "))
    income = int(input("Enter monthly income: "))

    if age >= 18:
        print("Age requirement met")
        if income >= 25000:
            print("Income requirement met")
            print("Loan approved!")
        else:
            print("Income too low")
            print("Loan rejected")
    else:
        print("Must be 18 or older")
        print("Loan rejected")

Output:

Enter age: 25
Enter monthly income: 30000
Age requirement met
Income requirement met
Loan approved!

Don't nest too deep though — more than 2-3 levels becomes hard to read.


Real World Example — Login System


    print("=== Login System ===")

    correct_username = "gagan"
    correct_password = "python123"

    username = input("Enter username: ")
    password = input("Enter password: ")

    if username == correct_username and password == correct_password:
        print("Login successful! Welcome back!")
    elif username == correct_username and password != correct_password:
        print("Wrong password. Please try again.")
    else:
        print("Username not found.")

Output:

Enter username: gagan
Enter password: python123
Login successful! Welcome back!

Enter username: gagan
Enter password: wrongpass
Wrong password. Please try again.

Common Mistakes to Avoid

Mistake 1 — Using = instead of ==

if age = 18:    # WRONG — this is assignment
if age == 18:   # CORRECT — this is comparison

Mistake 2 — Forgetting the colon

if age >= 18    # WRONG — missing colon
if age >= 18:   # CORRECT

Mistake 3 — Wrong indentation

if age >= 18:
print("Adult")    # WRONG — not indented

if age >= 18:
    print("Adult")  # CORRECT

Exercise 🏋️

Build an ATM Program:

  1. Set a variable balance = 10000 and pin = 1234
  2. Ask user to enter their PIN
  3. If PIN is wrong → print "Wrong PIN. Access denied."
  4. If PIN is correct → ask "How much do you want to withdraw?"
  5. If withdrawal amount is more than balance → print "Insufficient balance"
  6. If withdrawal amount is 0 or negative → print "Invalid amount"
  7. If everything is fine → subtract amount from balance and print "Withdrawal successful. Remaining balance: Rs.XXXX"

This will test everything you learned — input, math, and conditions!


Taking Input from User

What is User Input?

So far, all the values in your programs were hardcoded — meaning you wrote them directly in the code like name = "Gagan".

But real programs ask the user to enter data. Like when an app asks "Enter your name" or "Enter your password". That's user input.

In Python, we use the input() function for this.


Basic Syntax


    name = input("Enter your name: ")
    print(f"Hello, {name}!")

Run this program. It will:

  1. Show the message Enter your name: on screen
  2. Wait for you to type something
  3. When you press Enter — it stores what you typed in the name variable
  4. Then prints the greeting

Try it! Type your name and press Enter. Output will be:

Enter your name: Gagan
Hello, Gagan!

How input() Works

variable = input("Message to show user: ")
  • Whatever you write inside the quotes is shown to the user as a prompt
  • Whatever the user types gets stored in the variable
  • User input is always stored as a String — this is very important, we'll come back to this

More Examples


    name = input("What is your name? ")
    city = input("Which city are you from? ")
    language = input("Which language are you learning? ")

    print(f"Hi {name}!")
    print(f"So you are from {city}")
    print(f"Great choice learning {language}!")

Output:

What is your name? Gagan
Which city are you from? Delhi
Which language are you learning? Python
Hi Gagan!
So you are from Delhi
Great choice learning Python!

IMPORTANT — Input is Always a String

This is where beginners get confused. Let's see the problem:


    age = input("Enter your age: ")
    print(type(age))

Output:

Enter your age: 22
<class 'str'>

Even though you typed 22 (a number), Python stored it as "22" (a string). So if you try to do math with it:


    age = input("Enter your age: ")
    next_year_age = age + 1   # ERROR!
    print(next_year_age)

This will give you a TypeError because you can't add a string and a number.


Solution — Convert Input to Number

Use int() or float() to convert:


    age = input("Enter your age: ")
    age = int(age)                    # convert string to integer

    next_year_age = age + 1
    print(f"Next year you will be {next_year_age} years old")

Output:

Enter your age: 22
Next year you will be 23 years old

Shortcut — do it in one line:


    age = int(input("Enter your age: "))       # integer
    price = float(input("Enter price: "))      # decimal number

This is the most common way you'll see it written in real code.


When to Use int() vs float()


    # Use int() when you expect a whole number
    age = int(input("Enter your age: "))
    quantity = int(input("Enter quantity: "))

    # Use float() when you expect a decimal number
    price = float(input("Enter price: "))
    height = float(input("Enter your height: "))

    # Use nothing (plain input) when you expect text
    name = input("Enter your name: ")
    city = input("Enter your city: ")


Real World Example — Simple Calculator

Let's build your first interactive program!


    print("=== Simple Calculator ===")

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

    addition = num1 + num2
    subtraction = num1 - num2
    multiplication = num1 * num2
    division = num1 / num2

    print(f"\nResults:")
    print(f"{num1} + {num2} = {addition}")
    print(f"{num1} - {num2} = {subtraction}")
    print(f"{num1} * {num2} = {multiplication}")
    print(f"{num1} / {num2} = {division}")

Output:

=== Simple Calculator ===
Enter first number: 10
Enter second number: 4

Results:
10.0 + 4.0 = 14.0
10.0 - 4.0 = 6.0
10.0 * 4.0 = 40.0
10.0 / 4.0 = 2.5

Notice the \n in print(f"\nResults:") — this prints a blank line before "Results". \n means new line. Useful for spacing output nicely.


Another Example — Bill Splitter


    print("=== Bill Splitter ===")

    total_bill = float(input("Enter total bill amount: "))
    num_people = int(input("How many people? "))

    each_person = total_bill / num_people

    print(f"\nTotal bill: Rs.{total_bill}")
    print(f"Number of people: {num_people}")
    print(f"Each person pays: Rs.{each_person}")

Output:

=== Bill Splitter ===
Enter total bill amount: 1200
How many people? 4

Total bill: Rs.1200.0
Number of people: 4
Each person pays: Rs.300.0

Formatting Decimal Output

Sometimes the output looks messy with too many decimal places:


    result = 10 / 3
    print(result)   # 3.3333333333333335  — too many decimals

You can control how many decimal places to show using :.2f inside f-strings:


    result = 10 / 3
    print(f"{result:.2f}")    # 3.33  — only 2 decimal places
    print(f"{result:.1f}")    # 3.3   — only 1 decimal place
    print(f"{result:.0f}")    # 3     — no decimal places

Update the bill splitter:


    print(f"Each person pays: Rs.{each_person:.2f}")   # Rs.300.00

Much cleaner!


Quick Summary of What You've Learned So Far

You now know:

  • print() — display output
  • Variables and data types (str, int, float, bool)
  • Math operations
  • input() — take user input
  • int(), float(), str() — type conversion
  • f-strings — combine variables with text

These are the absolute foundations of Python. Everything else builds on top of this.


Exercise 🏋️

Build a Personal Info Card program:

  1. Ask the user for: name, age, city, and favorite hobby
  2. Calculate: what year they were born (hint: 2025 - age)
  3. Print a nicely formatted info card like this:
=============================
        PERSONAL INFO CARD
=============================
Name     : Gagan
Age      : 22
City     : Delhi
Hobby    : Coding
Born in  : 2003
=============================

This combines everything — input, variables, math, and f-strings. Give it a try!

Phase 3 — Components Deep Dive

Chapter 1 — What We Are Going to Learn and Why In Phase 2 you learned what a component is and how to create one. You know that a component h...