Conditional Statements in Python (if, else, elif) with Examples

Python Conditional Statements

🐍 Python Conditional
Statements Explained

if · if-else · if-elif-else · Nested if · Short if · Real-Life Examples

Section 01
What is a Conditional Statement?

A conditional statement in Python is used to make decisions in a program. It checks a condition and runs a specific block of code only if that condition is True. If the condition is False, Python skips that block or runs an alternative. Conditional statements make programs smart and responsive to inputs.

How Conditional Logic Works
Start
Check Condition
✅ True → Run Block
/
❌ False → Skip
End
πŸ’‘ Key Idea: Conditional statements are Python's way of making decisions — just like humans decide based on a situation.
Section 02
if Statement

The if statement is the most basic conditional statement. It checks a condition — if True, the code block inside runs. If False, Python skips it completely. The if statement uses a colon : at the end and the code inside must be indented (4 spaces). Indentation is mandatory in Python — missing it causes an IndentationError. The if statement checks only one condition at a time and runs the block only once when the condition is met.

πŸ“‹ Syntax:
if condition: # runs only if True statement
πŸ’» Example 1 — Age Check:
Python
age = 20

if age >= 18:

    print("You are an adult.")
πŸ‘† Output:
You are an adult.
πŸ’» Example 2 — False condition:
Python
marks = 40

if marks >= 50:

    print("Passed!")

# marks = 40, NOT >= 50 → nothing printed
πŸ‘† Output:
(no output — condition was False)
πŸ“ Important Notes:
Condition must be followed by colon :
Code inside must be indented (4 spaces)
If False, the block is completely skipped
Multiple lines can be written inside one if block
Section 03
if-else Statement

The if-else adds an alternative path when the condition is False. When if is True, the if block runs. When False, the else block runs instead. One of the two blocks always executes — never both, never neither. This makes if-else perfect for binary decisions like pass/fail, yes/no, or login/deny. The else keyword takes no condition — it handles all False cases automatically from the if above it.

πŸ“‹ Syntax:
if condition: statement_1 # True → runs this else: statement_2 # False → runs this
πŸ’» Example 1 — Pass or Fail:
Python
marks = 75

if marks >= 50:

    print("Passed!")

else:

    print("Failed!")
πŸ‘† Output:
Passed!
πŸ’» Example 2 — Even or Odd:
Python
num = 7

if num % 2 == 0:

    print(num, "is Even")

else:

    print(num, "is Odd")
πŸ‘† Output:
7 is Odd
πŸ“ Important Notes:
else never takes a condition
Exactly ONE block runs — if OR else, never both
else must be aligned with its matching if
Best for all binary (two-option) decisions
Section 04
if-elif-else Statement

The elif (else if) is used to check multiple conditions one by one. Python checks the first if — if True it runs that block and skips the rest. If False, it checks the next elif. This continues until a True condition is found. If none match, the final else runs. You can use as many elif blocks as needed. This is the standard way to handle multiple choices like grades, menus, or categories in Python programs.

πŸ“‹ Syntax:
if condition_1: statement_1 elif condition_2: statement_2 elif condition_3: statement_3 else: statement_4 # none matched
πŸ’» Example — Grade System:
Python
marks = 72

if marks >= 90:

    print("Grade: A+")

elif marks >= 80:

    print("Grade: A")

elif marks >= 70:

    print("Grade: B")

elif marks >= 60:

    print("Grade: C")

else:

    print("Grade: F")
πŸ‘† Output:
Grade: B
πŸ“ Important Notes:
Checks conditions top to bottom — stops at first True
You can use as many elif blocks as needed
Only one block ever runs — the first matching one
Final else is optional but always recommended
Section 05
Nested if Statement

A nested if is an if statement written inside another if. It checks a second condition only after the first condition is already True. The outer if runs first — if True, Python enters and then checks the inner if. This is useful for multi-level decisions like checking age first then gender, or verifying username then password. Proper indentation is critical — each inner level must be indented further to the right.

πŸ“‹ Syntax:
if outer_condition: if inner_condition: inner_block else: inner_else else: outer_else
πŸ’» Example — Voter Check:
Python
age    = 20

has_id = True

if age >= 18:

    print("Age OK.")

    if has_id:

        print("You can vote!")

    else:

        print("No ID. Cannot vote.")

else:

    print("Too young to vote.")
πŸ‘† Output:
Age OK.
You can vote!
πŸ“ Important Notes:
Inner if runs only when outer if is True
Each nested level needs more indentation
Avoid too many levels — code becomes unreadable
Use and operator instead of nested if for simple cases
Section 06
Short if (One-line / Ternary)

The short if — also called the ternary operator — lets you write a complete if-else in just one single line. It is used when the condition and result are simple. The syntax puts the true value first, then the condition with if, then the false value with else. It is not suitable for complex logic but is very useful for quick assignments. It makes code compact, clean, and easy to read for simple decisions.

πŸ“‹ Syntax:
value = true_val if condition else false_val
πŸ’» Example 1 — Adult or Minor:
Python
age    = 20

status = "Adult" if age >= 18 else "Minor"

print(status)
πŸ‘† Output:
Adult
πŸ’» Example 2 — Max number:
Python
a   = 15

b   = 22

big = a if a > b else b

print("Bigger:", big)
πŸ‘† Output:
Bigger: 22
πŸ’» Example 3 — Even or Odd in print:
Python
num = 8

print("Even" if num % 2 == 0 else "Odd")
πŸ‘† Output:
Even
πŸ“ Important Notes:
Order: true_value → if condition → else → false_value
Perfect for simple one-condition assignments
Can be used directly inside print()
Do NOT use for complex multi-statement logic
Section 07
πŸ“Œ Important Notes

These are the most important rules you must always remember when using conditional statements in Python.

πŸ“ Rule 1 — Indentation is Mandatory
Python
# ✅ Correct

if True:

    print("OK!")

# ❌ Wrong — causes IndentationError

# if True:

# print("Error!")
πŸ“ Rule 2 — Colon is Required
Python
# ✅ Correct

if x > 5:           # ← colon needed!

    print("Yes")

# ❌ Wrong — SyntaxError

# if x > 5

# print("Yes")
πŸ“ Rule 3 — Truthy and Falsy Values
Python
# Falsy: 0, "", [], {}, None, False

if 0:

    print("runs")     # ← never runs

if 1:

    print("runs!")    # ← always runs
Always use == to compare, NOT = (assignment)
Python checks conditions top to bottom — first True wins
Avoid deeply nested ifs — use and/or to simplify
else and elif blocks are always optional
You can compare strings: if name == "Ali":
Section 08
🌍 Real-Life Examples

Here are real-world scenarios showing how conditional statements are used in actual Python programs.

🏧 1. ATM Withdrawal
Python
balance  = 5000

withdraw = 3000

if withdraw <= balance:

    balance -= withdraw

    print("Withdrawn!")

    print("Balance:", balance)

else:

    print("Insufficient balance!")
πŸ‘† Output:
Withdrawn!
Balance: 2000
πŸ” 2. Login System
Python
username = "admin"

password = "1234"

if username == "admin" and password == "1234":

    print("Login successful!")

else:

    print("Wrong credentials.")
πŸ‘† Output:
Login successful!
🌑️ 3. Temperature Checker
Python
temp = 38

if temp >= 40:

    print("Very Hot!")

elif temp >= 30:

    print("Hot day.")

elif temp >= 20:

    print("Pleasant.")

else:

    print("Cold day.")
πŸ‘† Output:
Hot day.
πŸ›’ 4. Shopping Discount
Python
total = 1500

if total >= 2000:

    discount = 20

elif total >= 1000:

    discount = 10

else:

    discount = 0

print(f"Discount: {discount}%")

pay = total - (total * discount // 100)

print(f"Pay: {pay}")
πŸ‘† Output:
Discount: 10%
Pay: 1350
🌟 Key Takeaway: Conditional statements are in every real program — banking, login systems, shopping apps, and games. Mastering them is the most important step in Python!
Summary
πŸ“‹ All Conditional Statements
if — runs block only when condition is True
if-else — if True → if block, if False → else block
if-elif-else — checks multiple conditions one by one
Nested if — if inside another if (multi-level check)
Short if — complete if-else in one single line
πŸ’‘ Always remember:
✅ Every if/elif needs a colon :
✅ Code inside must be indented
✅ Use == to compare, not =
✅ Only the first True condition ever runs
Python Conditional if-else Beginner
Python Conditional Statements — Make Your Programs Smart!

Comments