Python Tutorials

Python Conditional Statements : if, elif, else Tutorial

Up to this point, our Python scripts have executed in a straight line, running from the top of the file to the bottom, line by line. But real software is rarely a straight line. Software needs to make decisions.

Imagine a video game: If the player has 0 health, trigger the “Game Over” screen. Else, let them keep playing. Think about a banking app: If the password is correct, show the account balance. Else, show an error message.

To give our programs a “brain” capable of making these decisions, we use Conditional Statements. By mastering if, elif, and else, you can write dynamic code that reacts differently depending on the data it receives.

What is Conditional Statements?

In computer science, Conditional Statements (also known as conditional constructs or decision-making structures) are features of a programming language that perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to True or False.

This concept is the core of Control Flow—the order in which individual statements, instructions, or function calls are executed or evaluated within a script.

Syntax & Basic Usage

In Python, conditionals rely heavily on the Comparison and Logical operators we learned in previous chapters (==, >, <, and, or).

The syntax requires the keyword if, followed by a condition that evaluates to True or False, and ends with a colon :.

The Indentation Rule: In Python, the code that belongs inside the if statement must be indented (usually by 4 spaces or 1 Tab). This is how Python knows which lines of code to skip if the condition is False.

# A simple condition evaluating an integer
customer_age = 20
legal_voting_age = 18

# If the condition is True, the indented code runs
if customer_age >= legal_voting_age:
    print("This customer is eligible to vote.")

# Expected Output:
# This customer is eligible to vote.
Code language: PHP (php)

Exhaustive Exploration & Methods

Python gives us several tools to build complex decision trees. Let’s explore every variation of the conditional statement.

1. The if Statement (The Solo Check)

The if statement can exist entirely on its own. If the condition is True, the indented block runs. If the condition is False, Python completely ignores the indented block and moves on to the rest of the script.

# A standalone if statement
account_balance = 50.00
item_price = 100.00

if account_balance < item_price:
    print("Alert: Insufficient funds for this purchase.")

print("Returning to the main menu...")

# Expected Output:
# Alert: Insufficient funds for this purchase.
# Returning to the main menu...
Code language: PHP (php)

2. The else Statement (The Fallback)

What if you want a specific action to happen when the condition is False? We use the else keyword. It does not take a condition; it acts as a universal catch-all for anything that failed the if check.

# Using if and else together
is_password_correct = False

if is_password_correct:
    print("Login successful. Access granted.")
else:
    print("Error: Incorrect password. Access denied.")

# Expected Output:
# Error: Incorrect password. Access denied.
Code language: PHP (php)

3. The elif Statement (Multiple Conditions)

Often, a yes/no decision isn’t enough. You might have three, four, or fifty different scenarios. elif stands for “else if”. It allows you to chain multiple conditions together. Python evaluates them in order from top to bottom. As soon as one condition is True, it runs that block and skips the rest.

# Checking multiple potential conditions using elif
current_traffic_light = "Yellow"

if current_traffic_light == "Green":
    print("You can drive.")
elif current_traffic_light == "Yellow":
    print("Prepare to stop.")
elif current_traffic_light == "Red":
    print("Stop your vehicle.")
else:
    print("Invalid light color detected.")

# Expected Output:
# Prepare to stop.
Code language: PHP (php)

4. Nested Conditionals (Decisions Inside Decisions)

You can place an if statement inside another if statement. This is called nesting, and it requires you to indent the inner block an additional level.

# Nesting conditions for multi-step verification
user_has_ticket = True
user_is_vip = True

if user_has_ticket:
    print("Ticket verified. You may enter the venue.")
    
    # This check only happens IF they have a ticket
    if user_is_vip:
        print("Welcome to the VIP Lounge!")
else:
    print("Security: Please purchase a ticket first.")

# Expected Output:
# Ticket verified. You may enter the venue.
# Welcome to the VIP Lounge!
Code language: PHP (php)

5. The Ternary Operator (One-Line Conditionals)

For very simple, straightforward if/else checks, Python offers a shortcut called a Conditional Expression (often called a Ternary Operator). It allows you to write an entire if/else statement on a single line.

# Syntax: [Value if True] if [Condition] else [Value if False]
student_grade = 85

# A one-line conditional assignment
pass_or_fail = "Passed" if student_grade >= 60 else "Failed"

print(f"The student has {pass_or_fail} the exam.")

# Expected Output:
# The student has Passed the exam.
Code language: PHP (php)

6. The pass Keyword (Placeholders)

Sometimes you are designing your program’s structure but haven’t written the actual logic yet. Because Python relies on indentation, an empty if statement will crash your code. To fix this, use the pass keyword to tell Python to “do nothing and keep going.”

# Using 'pass' to avoid an IndentationError while building a script
is_server_down = True

if is_server_down:
    # TODO: Write code later to send an emergency email to the IT team
    pass 
else:
    print("Server is running normally.")

# Expected Output:
# (No output, the script safely bypassed the empty block)
Code language: PHP (php)

Real-World Practical Examples

Scenario 1: User Role Authorization

In web development, you frequently need to check a user’s permission level before granting access to an administration dashboard.

# User data loaded from a database
logged_in_user_role = "Moderator"
is_account_active = True

if not is_account_active:
    print("Your account is currently suspended.")
elif logged_in_user_role == "Admin":
    print("Loading full Admin Dashboard...")
elif logged_in_user_role == "Moderator":
    print("Loading partial Moderator Dashboard...")
else:
    print("Loading standard user homepage...")

# Expected Output:
# Loading partial Moderator Dashboard...
Code language: PHP (php)

Scenario 2: E-Commerce Tiered Discounts

Let’s calculate a customer’s final checkout total by applying different discount tiers based on how much money they are spending.

# Shopping cart data
cart_subtotal = 150.00
discount_applied = 0.0

# Determine the discount tier
if cart_subtotal >= 200.00:
    discount_applied = 0.20  # 20% off
    print("Applied Tier 1 Discount (20%)")
elif cart_subtotal >= 100.00:
    discount_applied = 0.10  # 10% off
    print("Applied Tier 2 Discount (10%)")
else:
    print("No bulk discounts applied.")

# Calculate the final total
discount_amount = cart_subtotal * discount_applied
final_checkout_price = cart_subtotal - discount_amount

print(f"Final Total: ${final_checkout_price:.2f}")

# Expected Output:
# Applied Tier 2 Discount (10%)
# Final Total: $135.00
Code language: PHP (php)

Best Practices & Common Pitfalls

  • The Assignment Operator Error (= vs ==): This is the most common beginner bug. if user_age = 18: will cause a SyntaxError because a single = tries to assign a value. Always use the double == to compare values in an if statement.
  • IndentationErrors: Python does not use curly braces {} to group code like Java or C++. It relies 100% on indentation. Mixing spaces and tabs, or forgetting to indent the line under an if statement, will immediately crash your script.
  • Order of elif Statements Matters: Python checks if/elif blocks from top to bottom and stops at the first True statement. Always put your most specific, restrictive conditions at the top, and your broader conditions at the bottom.
  • Avoid Deep Nesting: If you have an if inside an if inside an if inside an if, your code becomes incredibly difficult to read (often called the “Arrow Anti-Pattern”). Try to use logical operators (and / or) to combine conditions on a single line when possible.

Summary

  • Conditional Statements allow your code to make decisions and change its behavior based on data.
  • if checks a condition. If it evaluates to True, the indented code block runs.
  • elif (else if) allows you to check additional conditions if the previous ones were False.
  • else is the ultimate fallback that runs if absolutely every preceding condition was False.
  • You can nest conditionals inside one another, or write them on a single line using a Ternary Operator.
  • Always double-check your indentation and ensure you are using comparison operators (==) rather than assignment operators (=) in your checks.

Leave a Comment