🐍
Syllabus / Python Programming / Phase 1: Python Basics, Variables, Data Types (Days 1–5)
Beginner

Conditional Statements: if, elif, else

📂 Phase 1: Python Basics, Variables, Data Types (Days 1–5) · Python Programming

Conditional statements let a program branch and make decisions based on whether something is true or false — the foundation of all program logic, just as in any other language, but with Python's own distinct syntax built entirely on indentation rather than braces.

Basic if Statement

age = 20

if age >= 18:
    print("You are an adult")

Notice there are no parentheses around the condition and no curly braces around the block — just a colon, followed by an indented block.

if-else

age = 15

if age >= 18:
    print("You can vote")
else:
    print("You cannot vote yet")

if-elif-else Chains

marks = 75

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 50:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")   # Grade: B

Python uses elif — a contraction of "else if" — instead of writing else if as two separate words like Java does.

Nested Conditionals

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Entry denied — underage")

Indentation Errors — The Most Common Beginner Mistake

# INCORRECT — inconsistent indentation raises an IndentationError
if True:
    print("Line one")
      print("Line two")   # extra space breaks the block

# CORRECT — every line in the block must align exactly
if True:
    print("Line one")
    print("Line two")

Truthy and Falsy Values in Conditions

Python does not require a condition to be a strict boolean — it evaluates many values as either "truthy" or "falsy" automatically.

Falsy ValuesTruthy Values
0, 0.0, "", [], {}, None, FalseAny non-zero number, any non-empty string/list/dict, True
name = ""

if name:
    print(f"Hello, {name}")
else:
    print("No name provided")   # this runs, since "" is falsy

The Ternary (Conditional) Expression

A compact one-line shorthand for simple if-else assignments:

a, b = 10, 20
max_value = a if a > b else b
print(max_value)   # 20

Combining Conditions

age = 25
income = 50000

if age >= 18 and income >= 30000:
    print("Eligible for the loan")
Interview tip: A favorite question is "What's the difference between elif and writing nested if-else blocks?" — functionally they can achieve the same result, but elif keeps the logic flat and far more readable once you have more than two or three branches; deeply nested if-else chains are a common code-smell interviewers will ask you to refactor on the spot.