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.
Table of Contents
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
age = 20
if age >= 18:
print("You are an adult.")
Explanation:
age = 20
: We assign the value20
to the variableage
.if age >= 18:
: This line checks ifage
is greater than or equal to18
.- If
age
is20
(which it is), this condition isTrue
.
- If
print("You are an adult.")
: Since the condition in theif
statement isTrue
, 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
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Explanation:
if age >= 18:
: The program checks ifage
is 18 or more.- If
True
, it executes the next line. - If
False
, it skips to theelse:
block.
- If
print("You are an adult.")
: This line is executed ifage
is 18 or more.else:
: This line is a fallback if theif
condition is not met.print("You are a minor.")
: This line is executed if theif
condition isFalse
, meaningage
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
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Explanation:
if age < 13:
: Checks ifage
is less than 13.- If
True
, prints “You are a child.” and skips the rest of the conditions.
- If
elif age < 18:
: If the firstif
isFalse
, it checks this condition.- If
True
, prints “You are a teenager.”
- If
else:
: If all above conditions areFalse
, this block is executed.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
if age >= 18:
if age >= 65:
print("You are a senior.")
else:
print("You are an adult.")
else:
print("You are a minor.")
Explanation:
if age >= 18:
: First checks ifage
is 18 or more.if age >= 65:
: If the first condition isTrue
, it then checks ifage
is 65 or more.- If
True
, prints “You are a senior.”
- If
else:
: If the secondif
isFalse
, this block is executed.- Prints “You are an adult.”
else:
: If the very firstif
isFalse
, 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
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:
temperature = 30
: Assigns30
totemperature
.raining = True
: AssignsTrue
toraining
.if temperature > 25 and not raining:
: Checks two conditions:- Is
temperature
greater than25
? - Is it
not raining
? (i.e., israining
False
?) - If both are
True
, prints “Let’s go to the beach!”
- Is
elif temperature > 25 and raining:
: If the first condition isFalse
, checks:- Is
temperature
greater than25
? - Is it
raining
? - If both are
True
, prints “It’s a good day for a museum.”
- Is
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 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 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
orsunday
). 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!