Control Flow
If/Else Statements
In this lesson, we’ll learn how to make decisions and repeat actions in Python using If/Else Statements
What are if/else statements?
In Python (or programming in general), if/else statements are decision-making tools that allow a program to take different actions based on certain conditions. Think of them as a way to make the program think and decide what to do in various situations.
- The if part checks a condition: "Is this true?"
- The else part defines what happens if the condition is not true.
Why do we need if/else statements? Programs need to handle different scenarios and make decisions just like humans do in everyday life. Without if/else statements, the program would not be able to adapt to different situations or conditions dynamically.
Key reasons:
- Decision Making: To allow the program to choose between multiple courses of action.
- Dynamic Responses: To react to different inputs or changing conditions in real-time.
- Error Handling: To guide the program when something unexpected happens.
Real-world examples (without code):
-
- Traffic Light Decision If the traffic light is green, then you go. Else (if it's red), you stop.
-
- Weather-based Dressing If it's raining, then carry an umbrella. Else (if it's sunny), wear sunglasses.
-
- Restaurant Ordering If you are vegetarian, then order a veggie dish. Else (if you eat meat), order a non-veg dish.
-
- Shopping Discounts If your total bill is above $100, then you get a 10% discount. Else, you pay the full amount.
-
- Airline Boarding If your boarding pass is valid, then you can board the plane. Else, you are denied boarding.
How would the world look without if/else decisions?
Imagine trying to follow the same routine every day without adapting to different circumstances:
- You'd carry an umbrella every day, even when it's sunny.
- You'd try to drive through a red light because there's no decision-making involved.
- Restaurants would serve you random food because they can't decide based on your preference.
In essence, if/else statements bring logic, adaptability, and intelligence to programs, just like critical thinking brings adaptability to our lives!
Syntax:
if condition:
# code to run if condition is true
elif another_condition:
# code to run if another_condition is true
else:
# code to run if all conditions are false
Example:
age = 18
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
1. Basic if Statement
The if statement is the simplest form of conditional in Python. It checks if a condition is true, and if it is, the block of code inside the if statement is executed.
Example 1: Basic if Statement
# Example: Checking if a number is positive
number = 5
if number > 0:
print("The number is positive.")
Explanation:
- The condition number > 0 is checked.
- If it is True, the message "The number is positive." is printed.
2. if with else Statement
The if-else statement allows you to execute one block of code if the condition is true, and a different block if the condition is false.
Example 2: if with else
# Example: Checking if a number is positive or not
number = -3
if number > 0:
print("The number is positive.")
else:
print("The number is not positive.")
Explanation:
- If number > 0, it prints "The number is positive.".
- Otherwise, it prints "The number is not positive.".
3. if-elif-else Statement
The if-elif-else statement allows checking multiple conditions. Only the first True condition is executed, and the rest are skipped.
Example 3: if-elif-else Statement
# Example: Categorizing a number
number = 0
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Explanation:
- If number > 0, it prints "The number is positive.".
- If number < 0, it prints "The number is negative.".
- If neither condition is true, it prints "The number is zero.".
##if-elif-else: Grade categorization
# Change the value of variable marks and see what output is printed.
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")
Now that we have learnt the basics of if-elif-else conditional statement, its time to practice.
# Problem 1: Check if a number is positive.
# Write a program that asks the user to input a number.
# Print "The number is positive." if the number is greater than zero.
# Problem 2: Check if a person is eligible to vote.
# Ask the user to input their age.
# Print "You are eligible to vote." if the age is 18 or more.
MIN_VOTING_AGE = 18
# Problem 3: Even or Odd Number
# Write a program that asks the user to input a number.
# Print "The number is even." if it is divisible by 2, otherwise print "The number is odd.".
# Problem 4: Check String Length
# Ask the user to input two strings and print the one that is longer
# Problem 5: Check Username Validity
# Ask the user to input a username.
# Check if it meets these requirements:
# At least 5 characters long.
# Contains no spaces.
# Starts with an uppercase letter.
#If the username is invalid inform the user why the username is invalid:
#print("Invalid username: Must be at least 5 characters long.")
#print("Invalid username: Must start with an uppercase letter.")
#print("Invalid username: Must not contain spaces.")
#Else inform the user that username is valid'
#print("Valid username.")
Nested If Statements
You can also nest if statements inside another if block.
Example:
age = 20
if age >= 18:
print("You can vote.")
if age >= 21:
print("You can drink alcohol in the US.")
else:
print("You are not old enough to vote.")
Example: Determining Delivery Cost
A store offers delivery services based on the total order value and the delivery distance. The delivery cost is calculated as follows:
-
If the order value is greater than 100:
- delivery is free
-
If the order value is less than 100:
- If the delivery distance is less than 5 km, delivery is free.
- Otherwise, delivery costs $10.
Here’s the code:
# Inputs
order_value = 80 # Example: Order value in dollars
delivery_distance = 3 # Example: Delivery distance in kilometers
# Nested if-else to determine delivery cost
if order_value > 100:
delivery_cost = 0 # Free delivery for orders over $100
else: # order_value <= 100
if delivery_distance <= 5:
delivery_cost = 0 # Free delivery within 5 km for orders under $100
else:
delivery_cost = 10 # Delivery cost if distance is greater than 5 km
# Output
print(f"Order value: ${order_value}")
print(f"Delivery distance: {delivery_distance} km")
print(f"Delivery cost: ${delivery_cost}")