⚖️ 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
| Operator | Description | Example (a = 10, b = 20) |
|---|---|---|
== | Equals | a == b → False |
!= | Not equals | a != b → True |
> | Greater than | a > b → False |
< | Less than | a < b → True |
>= | Greater than or equal | a >= 10 → True |
<= | Less than or equal | a <= 5 → False |
🔁 Logical Operators in Conditions
| Operator | Description | Example |
|---|---|---|
and | Both conditions are true | age > 18 and score > 50 |
or | At least one is true | age > 18 or score > 50 |
not | Inverts the result | not (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
| Syntax | Purpose |
|---|---|
if condition: | Runs when true |
if...else | Either one of two branches runs |
if...elif...else | Multi-branch conditions |
and, or, not | Combine 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

