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!


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