Dev In The Mountain Header
A Developer In The mountains having fun

Conditional Statements in Python

Conditional statements allow your programs to make decisions and execute different code based on certain conditions. They're like the decision-making brain of your program, enabling it to respond differently to various situations.

What are Conditional Statements?

Conditional statements check whether a condition is True or False and execute code accordingly. Think of them like real-world decisions:

  • "If it's raining, I'll take an umbrella"
  • "If I'm hungry, I'll eat something"
  • "If it's a weekend, I'll sleep in"

In Python, we use if, elif, and else statements to create these decision points.

The Basic if Statement

The simplest conditional statement is the if statement:

age = 18

if age >= 18:
    print("You are an adult!")
    print("You can vote.")

Syntax Breakdown

  • if keyword starts the conditional
  • age >= 18 is the condition being tested
  • : (colon) ends the condition line
  • Indented code block executes if condition is True

Important: Indentation Matters!

Python uses indentation (spaces or tabs) to group code. Everything indented under the if statement runs when the condition is True:

temperature = 75

if temperature > 70:
    print("It's warm outside!")
    print("Perfect weather for a walk.")
    print("Don't forget sunscreen.")

print("This always prints, regardless of temperature.")

Comparison Operators

To create conditions, you need comparison operators:

x = 10
y = 5

# Equality
print(x == y)    # False (equal to)
print(x != y)    # True (not equal to)

# Comparison
print(x > y)     # True (greater than)
print(x < y)     # False (less than)
print(x >= y)    # True (greater than or equal to)
print(x <= y)    # False (less than or equal to)

# Membership (for strings, lists, etc.)
name = "Alice"
print("A" in name)      # True
print("z" in name)      # False

The else Statement

Use else to handle cases when the if condition is False:

age = 16

if age >= 18:
    print("You can vote!")
else:
    print("You're not old enough to vote yet.")
    print(f"Wait {18 - age} more years.")

The elif Statement

Use elif (else if) to check multiple conditions:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is: {grade}")

How elif Works

  • Python checks each condition in order
  • When it finds the first True condition, it executes that block
  • It skips all remaining elif and else blocks
  • If no condition is True, the else block executes (if present)

Logical Operators

Combine multiple conditions using logical operators:

and Operator

Both conditions must be True:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")
else:
    print("You cannot drive.")

or Operator

At least one condition must be True:

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
else:
    print("It's a weekday.")

not Operator

Reverses the condition:

is_raining = False

if not is_raining:
    print("Great day for a picnic!")
else:
    print("Maybe stay indoors today.")

Combining Logical Operators

age = 25
has_job = True
has_car = False

if (age >= 18 and has_job) or has_car:
    print("You seem independent!")
else:
    print("Still working on independence.")

Nested Conditionals

You can put if statements inside other if statements:

weather = "sunny"
temperature = 75

if weather == "sunny":
    print("It's sunny!")
    if temperature > 80:
        print("Perfect beach weather!")
    elif temperature > 60:
        print("Great for outdoor activities!")
    else:
        print("A bit chilly, but still nice.")
else:
    print("Not sunny today.")

Practical Examples

Example 1: Login System

username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "secret123":
    print("Welcome, administrator!")
    print("Access granted to admin panel.")
elif username == "user" and password == "password":
    print("Welcome, user!")
    print("Access granted to user dashboard.")
else:
    print("Invalid credentials!")
    print("Access denied.")

Example 2: Grade Calculator

print("=== Grade Calculator ===")

# Get scores
math_score = float(input("Enter math score: "))
english_score = float(input("Enter English score: "))
science_score = float(input("Enter science score: "))

# Calculate average
average = (math_score + english_score + science_score) / 3

# Determine grade and status
if average >= 90:
    grade = "A"
    status = "Excellent!"
elif average >= 80:
    grade = "B"
    status = "Good job!"
elif average >= 70:
    grade = "C"
    status = "Satisfactory."
elif average >= 60:
    grade = "D"
    status = "Needs improvement."
else:
    grade = "F"
    status = "Please see teacher."

print(f"\nYour average: {average:.1f}")
print(f"Grade: {grade}")
print(f"Status: {status}")

Example 3: Simple Calculator with Validation

print("=== Simple Calculator ===")

num1 = float(input("Enter first number: "))
operation = input("Enter operation (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operation == "+":
    result = num1 + num2
    print(f"{num1} + {num2} = {result}")
elif operation == "-":
    result = num1 - num2
    print(f"{num1} - {num2} = {result}")
elif operation == "*":
    result = num1 * num2
    print(f"{num1} * {num2} = {result}")
elif operation == "/":
    if num2 != 0:
        result = num1 / num2
        print(f"{num1} / {num2} = {result}")
    else:
        print("Error: Cannot divide by zero!")
else:
    print("Error: Invalid operation!")

Conditional Expressions (Ternary Operator)

Python offers a shorthand for simple if-else statements:

# Regular if-else
age = 20
if age >= 18:
    status = "adult"
else:
    status = "minor"

# Conditional expression (ternary operator)
status = "adult" if age >= 18 else "minor"

# More examples
temperature = 75
clothing = "shorts" if temperature > 70 else "jacket"

score = 85
passed = "Yes" if score >= 60 else "No"

Common Patterns and Idioms

Checking for Empty Values

name = input("Enter your name: ")

if name:  # True if name is not empty
    print(f"Hello, {name}!")
else:
    print("You didn't enter a name.")

# Alternative ways to check
if name != "":
    print(f"Hello, {name}!")

if len(name) > 0:
    print(f"Hello, {name}!")

Checking Multiple Values

day = input("Enter day of week: ").lower()

# Method 1: Multiple or conditions
if day == "saturday" or day == "sunday":
    print("Weekend!")

# Method 2: Using 'in' with a list (more elegant)
if day in ["saturday", "sunday"]:
    print("Weekend!")

# Method 3: Using a tuple
weekend_days = ("saturday", "sunday")
if day in weekend_days:
    print("Weekend!")

Common Mistakes and How to Avoid Them

1. Using = Instead of ==

# Wrong - this assigns 5 to x
if x = 5:
    print("x is 5")

# Correct - this compares x to 5
if x == 5:
    print("x is 5")

2. Forgetting the Colon

# Wrong
if x > 5
    print("x is greater than 5")

# Correct
if x > 5:
    print("x is greater than 5")

3. Incorrect Indentation

# Wrong
if x > 5:
print("This should be indented")

# Correct
if x > 5:
    print("This is properly indented")

4. Chaining Comparisons Incorrectly

# This doesn't work as expected
if x == 1 or 2 or 3:  # Always True!

# Correct ways
if x == 1 or x == 2 or x == 3:
if x in [1, 2, 3]:
if 1 <= x <= 3:  # Only works for ranges

Practice Exercises

Exercise 1: Age Classifier

Write a program that classifies people into age groups:

  • Child: 0-12
  • Teenager: 13-19
  • Adult: 20-64
  • Senior: 65+

Exercise 2: Password Validator

Create a password validator that checks:

  • Length is at least 8 characters
  • Contains at least one number
  • Contains at least one uppercase letter

Exercise 3: Restaurant Recommendation

Build a program that recommends restaurants based on:

  • Cuisine preference (Italian, Chinese, Mexican)
  • Budget (Low, Medium, High)
  • Distance (Near, Far)

Sample Solutions

Exercise 1:

age = int(input("Enter your age: "))

if age < 0:
    print("Invalid age!")
elif age <= 12:
    print("You are a child.")
elif age <= 19:
    print("You are a teenager.")
elif age <= 64:
    print("You are an adult.")
else:
    print("You are a senior.")

Exercise 2:

password = input("Enter a password: ")

# Check length
if len(password) < 8:
    print("Password must be at least 8 characters long.")
elif not any(char.isdigit() for char in password):
    print("Password must contain at least one number.")
elif not any(char.isupper() for char in password):
    print("Password must contain at least one uppercase letter.")
else:
    print("Password is valid!")

Exercise 3:

print("=== Restaurant Recommendation ===")
cuisine = input("Preferred cuisine (Italian/Chinese/Mexican): ").lower()
budget = input("Budget (Low/Medium/High): ").lower()
distance = input("Distance (Near/Far): ").lower()

if cuisine == "italian":
    if budget == "high" and distance == "near":
        print("Recommendation: Bella Vista (Upscale Italian nearby)")
    elif budget == "low":
        print("Recommendation: Mario's Pizza (Affordable Italian)")
    else:
        print("Recommendation: Olive Garden (Mid-range Italian)")
elif cuisine == "chinese":
    if budget == "high":
        print("Recommendation: Golden Dragon (Premium Chinese)")
    else:
        print("Recommendation: Panda Express (Casual Chinese)")
elif cuisine == "mexican":
    if distance == "near":
        print("Recommendation: Local Taco Shop")
    else:
        print("Recommendation: Chipotle (Reliable Mexican chain)")
else:
    print("Sorry, no recommendations for that cuisine type.")

Key Takeaways

  • Use if, elif, and else to create decision points in your code
  • Conditions must evaluate to True or False (boolean values)
  • Indentation is crucial - all code at the same level must be indented equally
  • Use comparison operators (==, !=, >, <, >=, <=) to create conditions
  • Combine conditions with logical operators (and, or, not)
  • Python evaluates conditions in order and stops at the first True condition
  • Conditional expressions provide a shorthand for simple if-else statements

What's Next?

Now that you understand conditional statements, you're ready to learn about:


Conditional statements are fundamental to programming logic. Practice with different scenarios to build your problem-solving skills!

More places to find me
Mental Health
follow me on Mastodon