Understanding Conditional Statements in Python

Python

Today, we will delve into one of the most fundamental aspects of programming: Conditional Statements.

These are akin to the decision-making processes in our daily lives.

Just as we make decisions based on certain conditions, in programming, we use if, else, and elif statements to direct the flow of our code based on certain conditions.

The Basics of if, else, and elif

The if Statement

The if statement is the most basic form of conditional logic in Python. It checks if a condition is true and, if so, executes a block of code.

Analogy: Think of an if statement as a road sign that says, “If this is true, go this way.”

Example 1: Basic if Statement

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

Explanation:

  1. age = 20: We assign the value 20 to the variable age.
  2. if age >= 18:: This line checks if age is greater than or equal to 18.
    • If age is 20 (which it is), this condition is True.
  3. print("You are an adult."): Since the condition in the if statement is True, this line is executed and “You are an adult.” is printed to the console.

The else Statement

The else statement follows an if statement and is executed if the if condition is false.

An else statement is like saying, “If the first condition isn’t met, then do this instead.”

Example 2: if with else

Python
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Explanation:

  1. if age >= 18:: The program checks if age is 18 or more.
    • If True, it executes the next line.
    • If False, it skips to the else: block.
  2. print("You are an adult."): This line is executed if age is 18 or more.
  3. else:: This line is a fallback if the if condition is not met.
  4. print("You are a minor."): This line is executed if the if condition is False, meaning age is less than 18.

The elif Statement

The elif (short for else if) is used to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

The elif is like adding more options to your decision-making: “If this isn’t true, then check if this other thing is true.”

Example 3: Using elif

Python
if age < 13:
    print("You are a child.")
elif age < 18:
    print("You are a teenager.")
else:
    print("You are an adult.")

Explanation:

  1. if age < 13:: Checks if age is less than 13.
    • If True, prints “You are a child.” and skips the rest of the conditions.
  2. elif age < 18:: If the first if is False, it checks this condition.
    • If True, prints “You are a teenager.”
  3. else:: If all above conditions are False, this block is executed.
  4. print("You are an adult."): This is the default action if none of the above conditions are met.

Advanced Conditional Statements

Nested if Statements

You can place an if statement inside another if statement to create more complex decision structures.

Example 4: Nested if Statement

Python
if age >= 18:
    if age >= 65:
        print("You are a senior.")
    else:
        print("You are an adult.")
else:
    print("You are a minor.")

Explanation:

  1. if age >= 18:: First checks if age is 18 or more.
  2. if age >= 65:: If the first condition is True, it then checks if age is 65 or more.
    • If True, prints “You are a senior.”
  3. else:: If the second if is False, this block is executed.
    • Prints “You are an adult.”
  4. else:: If the very first if is False, this block is executed.
    • Prints “You are a minor.”

Combining Conditions

You can combine multiple conditions in an if statement using and, or, and not.

Example 5: Combining Conditions

Python
temperature = 30
raining = True

if temperature > 25 and not raining:
    print("Let's go to the beach!")
elif temperature > 25 and raining:
    print("It's a good day for a museum.")
else:
    print("Let's stay home and read.")

Explanation:

  1. temperature = 30: Assigns 30 to temperature.
  2. raining = True: Assigns True to raining.
  3. if temperature > 25 and not raining:: Checks two conditions:
    • Is temperature greater than 25?
    • Is it not raining? (i.e., is raining False?)
    • If both are True, prints “Let’s go to the beach!”
  4. elif temperature > 25 and raining:: If the first condition is False, checks:
    • Is temperature greater than 25?
    • Is it raining?
    • If both are True, prints “It’s a good day for a museum.”
  5. else:: If neither of the above conditions are met, executes this block.
    • Prints “Let’s stay home and read.”

Python Exercise 1: Movie Ticker Pricing

Here is a simple exercise to test your knowledge in python conditional statements.

Instructions. Create a program that determines the price of a movie ticket based on the age of the customer and the day of the week. Here are the rules:

  • On weekdays (Monday to Friday):
    • Children (ages below 13) pay $5.
    • Teenagers (ages 13 to 17) pay $7.
    • Adults (ages 18 and above) pay $10.
  • On weekends (Saturday and Sunday):
    • All ages pay a flat rate of $8.

The program should ask the user for their age and the day of the week, then output the price of the movie ticket.

Python Program (for Readers to Solve)

Python
# Python program to calculate movie ticket prices

# Get user's age and day of the week
age = int(input("Enter your age: "))
day = input("Enter the day of the week: ").lower()

# Calculate and print ticket price
# [Your code goes here]

# Example input/output:
# Enter your age: 15
# Enter the day of the week: Saturday
# Your ticket price is $8.

Solution to Python Exercise 1

Python
# Python program to calculate movie ticket prices

# Get user's age and day of the week
age = int(input("Enter your age: "))
day = input("Enter the day of the week: ").lower()

# Calculate and print ticket price
if day in ["saturday", "sunday"]:
    print("Your ticket price is $8.")
else:
    if age < 13:
        print("Your ticket price is $5.")
    elif age <= 17:
        print("Your ticket price is $7.")
    else:
        print("Your ticket price is $10.")

Explanation of the Solution

  • The program first takes the user’s age and the day of the week as input.
  • It checks if the day is a weekend day (saturday or sunday). If so, it applies the flat rate of $8.
  • If it’s not a weekend, it checks the user’s age to determine the price based on the weekday pricing structure.
  • It then prints the appropriate ticket price.

This exercise helps in understanding the use of nested conditional statements (if, elif, else) and working with user input in Python.

Conclusion

Conditional statements are essential in Python for making decisions based on various conditions.

By understanding and effectively using if, elif, and else statements, you can control the flow of your Python programs and handle a wide range of scenarios.

Remember, the key to mastering these statements lies in practice and experimentation. Happy coding!