Conditional Statements (`if`, `elif`, `else`)

Conditional statements are a cornerstone of programming logic — they allow your code to **make decisions** based on data or user input. In Python, these decisions are handled through the keywords `if`, `elif`, and `else`, which control the **flow of execution**.

Chapter 2: Control Structures and Functions

Sub-chapter: Conditional Statements (if, elif, else)

Conditional statements are a cornerstone of programming logic — they allow your code to make decisions based on data or user input. In Python, these decisions are handled through the keywords if, elif, and else, which control the flow of execution.


🧠 Why Use Conditionals?

Programs often need to behave differently depending on input or context — for example:

Conditional statements let your program evaluate expressions and execute specific blocks of code when conditions are met.


🔹 The if Statement

The if statement checks a condition and runs a block of code if that condition evaluates to True.

Syntax:

if condition:
    # code executes only if condition is True

Example — Checking age eligibility:

age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")

✅ If age >= 18, the message appears; otherwise, the program skips that code block.


⚙️ How Python Evaluates Conditions

Any expression that returns a Boolean (True or False) can be used in an if statement. Python automatically considers these values False:

Everything else is True.

Example:

name = ""
if name:
    print("Name entered!")
else:
    print("No name provided.")

Output:

No name provided.

🔹 The if and else Combination

When you want to run one block for a true condition and another for false, use else.

Syntax:

if condition:
    # executes if True
else:
    # executes if False

Example — Voting eligibility:

age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")

Output examples:

Enter your age: 22
You are eligible to vote.

Enter your age: 15
You are not eligible to vote yet.

🔹 The elif (Else If) Chain

When multiple conditions are possible, you can chain them using elif.

Syntax:

if condition1:
    # executes if condition1 is True
elif condition2:
    # executes if condition2 is True
else:
    # executes if none are True

Example — Grading system:

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")

💡 Python executes only the first condition that is True and skips the rest.


🧮 Nested if Statements

You can place one if statement inside another to check multiple layers of logic.

Example:

age = int(input("Enter your age: "))
citizen = input("Are you a citizen? (yes/no): ").lower()

if age >= 18:
    if citizen == "yes":
        print("You can vote!")
    else:
        print("You must be a citizen to vote.")
else:
    print("You are not old enough to vote.")

⚠️ Avoid too many nested conditionals — they make code harder to read. Consider using logical operators instead.


🧩 Logical Operators

Python allows you to combine multiple conditions in one statement using logical operators.

OperatorDescriptionExample
andTrue if both conditions are Truex > 0 and x < 10
orTrue if at least one condition is Truex < 0 or x > 100
notInverts the resultnot is_logged_in

Example — Work eligibility:

age = int(input("Enter your age: "))
if age >= 18 and age <= 65:
    print("You are eligible to work.")
else:
    print("You are not eligible to work.")

Another example — Login logic:

username = "admin"
password = "1234"

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

🔀 Combining Comparison and Logical Operators

Python supports relational operators like >, <, >=, <=, ==, and !=.
You can combine them with logical operators for complex conditions.

Example — Bank loan eligibility:

age = int(input("Enter your age: "))
income = float(input("Enter your monthly income: "))

if (age >= 21 and age <= 60) and income >= 3000:
    print("Loan Approved ✅")
else:
    print("Loan Denied ❌")

🧮 Ternary (One-Line) if Statement

Python allows compact conditional assignments using the ternary operator syntax:

message = "Adult" if age >= 18 else "Minor"
print(message)

This is perfect for quick, inline decisions.


🧠 Truthy and Falsy in Python

You don’t always need explicit comparisons — Python can evaluate truthiness directly.

data = []
if data:
    print("List has items!")
else:
    print("List is empty.")

Output:

List is empty.

💡 Best Practices

Example of clean code:

if is_logged_in and has_permission:
    print("Access granted.")
else:
    print("Access denied.")

🧾 Key Takeaways


By mastering conditional statements, you unlock the power to make your programs dynamic, responsive, and intelligent — capable of adapting to user input and real-world scenarios.