⚖️ Python If…Else Statements – Master Conditions Like a Pro | TechTown.in

In Python, conditional statements help your code make decisions. Want your program to respond differently based on user input, data values, or system status? That’s exactly what if, elif, and else are made for.

Let’s break down how conditions work in Python, explore syntax, and look at real-life examples to help you use them in actual projects.


🔰 What Are Conditional Statements?

Conditional statements check whether an expression is true or false, and execute code accordingly.


✅ Basic if Statement

age = 20
if age >= 18:
    print("You are eligible to vote.")

🧠 If the condition is true, the indented code runs.


🔁 if...else Statement

age = 16
if age >= 18:
    print("You are eligible to vote.")
else:
    print("Sorry, you are underage.")

🎯 Use else to handle what happens when the if condition is not met.


🔄 if...elif...else Chain

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 75:
    print("Grade: B")
elif score >= 60:
    print("Grade: C")
else:
    print("Grade: D")

✅ Use elif to check multiple conditions in sequence.


🔗 Comparison Operators in Conditions

OperatorDescriptionExample (a = 10, b = 20)
==Equalsa == b → False
!=Not equalsa != b → True
>Greater thana > b → False
<Less thana < b → True
>=Greater than or equala >= 10 → True
<=Less than or equala <= 5 → False

🔁 Logical Operators in Conditions

OperatorDescriptionExample
andBoth conditions are trueage > 18 and score > 50
orAt least one is trueage > 18 or score > 50
notInverts the resultnot (age > 18)

🧠 Real-World Use Case

Login Example:

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Login successful!")
else:
    print("Invalid credentials.")

🧪 Nested if Statements

age = 22
if age > 18:
    if age < 60:
        print("You are an adult.")

✅ Use nested conditions when one check depends on another.


📝 Summary – Python If/Else Cheat Sheet

SyntaxPurpose
if condition:Runs when true
if...elseEither one of two branches runs
if...elif...elseMulti-branch conditions
and, or, notCombine multiple checks
==, !=, >=, etc.Comparison logic

🏁 Final Thoughts

Python’s conditional statements are your first step toward making your code smart and dynamic. They let your programs react to input, data, and real-world logic — just like a brain does.

Practice writing if, elif, and else with both simple and complex conditions. Soon, you’ll be handling user validation, game logic, and decision trees with ease.


📘 Continue learning with more Python basics at TechTown.in