Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 2: Control Flow & Iteration
PYTHON ⏱ 10 min read

Conditional Statements (if, elif, else)

Conditional statements allow your Python program to evaluate situations and take different execution paths.

What is it?

Conditionals in Python are written with `if`, `elif` (short for else if), and `else`, followed by a colon `:` and an indented block of code.

Why is it used?

Controls decision making, admission criteria, discounts, validations, and game logic.

Detailed Explanation

Indentation Rule: Unlike C, C++, or Java which use curly braces `{ ... }`, Python requires consistent indentation (standard 4 spaces). All lines indented at the same level belong to that conditional block. Short-circuit evaluation: With `and`, if the first condition is False, Python stops checking. With `or`, if the first condition is True, Python stops checking.

Syntax Structure

Syntax Blueprint
if condition:
    # 4 spaces indentation
    do_something()
elif another_condition:
    do_another_thing()
else:
    fallback()

Code Example

PYTHON Code
# Course Grading & Certification System
def evaluate_student_performance(score, attendance_pct):
    if attendance_pct < 75:
        return "Ineligible for Certificate: Attendance under 75%"
    
    if score >= 90:
        grade = "Grade A+ (Distinction)"
    elif score >= 80:
        grade = "Grade A (Excellent)"
    elif score >= 65:
        grade = "Grade B (Good)"
    elif score >= 50:
        grade = "Grade C (Pass)"
    else:
        grade = "Fail (Needs Retake)"
        
    return f"Status: Certified | {grade}"

print(evaluate_student_performance(88, 90))
print(evaluate_student_performance(95, 60)) # Fails attendance
print(evaluate_student_performance(45, 80)) # Fails score

Explanation of the Code

• Evaluates attendance threshold first with early return pattern. • Chains `elif` blocks for descending grade brackets. • Returns cleanly formatted performance feedback.

Expected Output

Status: Certified | Grade A (Excellent) Ineligible for Certificate: Attendance under 75% Status: Certified | Fail (Needs Retake)

Real-World Application

Used in Flask and Django route handlers to check user authentication, permissions, and request validation.

Common Mistakes to Avoid

• Forgetting the colon `:` at the end of the `if` or `elif` line (causes syntax error). • Inconsistent indentation (mixing 2 spaces, 4 spaces, or tabs throws `IndentationError`).

Quick Practice Challenge

Write an if-else check that determines if a number is positive, negative, or zero.

Key Takeaways

• Python uses `if`, `elif`, `else` followed by a colon `:`. • Indentation defines the code block boundary. • Use early returns to simplify deeply nested conditionals.