Introduction:
Learning to code can be like solving a puzzle. Every piece you put together brings you closer to the bigger picture. One of the most important pieces in Python—and in programming in general—is understanding conditional statements. Mastering these “if,” “else,” and “elif” statements is key to writing smarter and more efficient code.
This blog post offers practical exercises designed to help you get a solid grasp of conditional statements in Python. Instead of focusing on theory alone, we’ll work through hands-on examples that demonstrate how these concepts play out in real-world scenarios. The goal is to make these exercises clear and engaging, so by the end, using conditional statements in your own projects will feel natural.
Curious about what Python can do, or looking to sharpen your coding skills? Stick around. You’ll walk away with practical knowledge you can apply right away. Let’s get started!
Simple If Statement Exercises
Exercise 1: Check If a Number is Positive, Negative, or Zero
# Prompt the user to enter a number
number = float(input("Enter a number: "))
# Check if the number is positive, negative, or zero
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Output:
Enter a number: 74
The number is positive.
Enter a number: -56
The number is negative.
Enter a number: 0
The number is zero.
Explanation:
- User Input: The program starts by asking the user to enter a number. The
input()
function is used to get this input, andfloat()
converts the input to a floating-point number, allowing the user to enter decimal numbers as well. - Conditional Checks:
- The first
if
statement checks if the number is greater than 0. If it is, the program prints “The number is positive.” - The
elif
(else if) statement checks if the number is less than 0. If this condition is true, the program prints “The number is negative.” - The final
else
statement catches all other cases—specifically when the number is neither positive nor negative, which must mean it’s zero. In this case, the program prints “The number is zero.”
- The first
This simple exercise demonstrates how conditional statements in Python work to handle different possible outcomes based on user input. It’s a basic yet essential concept that forms the foundation for more complex decision-making in programming.
Exercise 2: Determine Even or Odd Numbers
# Prompt the user to enter a number
number = int(input("Enter an integer: "))
# Check if the number is even or odd
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
Output:
Enter an integer: 10
10 is an even number.
Enter an integer: 7
7 is an odd number.
Explanation:
- User Input: The program begins by asking the user to enter an integer. The
input()
function captures this input as a string, andint()
converts it to an integer. - Modulus Operator
%
: This operator is key to determining whether a number is even or odd. The expressionnumber % 2
computes the remainder whennumber
is divided by 2.- If the remainder is
0
(number % 2 == 0
), it means the number is evenly divisible by 2, making it an even number. - If the remainder is not
0
, the number is odd.
- If the remainder is
- Conditional Check:
- The
if
statement checks whether the number is even. If it is, the program prints a message stating that the number is even. - The
else
statement catches the remaining case where the number is odd, and it prints a corresponding message.
- The
This exercise is a simple yet practical example of how conditional statements can be used to classify numbers based on their properties. Understanding how to use the modulus operator and conditional checks is essential for performing these types of basic yet powerful operations in Python.
Exercise 3: Basic Password Validation
# Set a predefined password
correct_password = "EmiTechLogic"
# Prompt the user to enter the password
entered_password = input("Enter the password: ")
# Check if the entered password matches the predefined password
if entered_password == correct_password:
print("Access granted.")
else:
print("Access denied.")
Output:
Enter the password: EmiTechLogic
Access granted.
Enter the password: wrongpassword
Access denied.
Explanation:
- Predefined Password: The program starts by setting a predefined password,
"EmiTechLogic"
, which represents the correct password that users need to enter. - User Input: The program then prompts the user to enter a password using the
input()
function. The user’s input is stored in the variableentered_password
. - Conditional Check:
- The
if
statement compares theentered_password
with thecorrect_password
using the==
operator, which checks for equality. - If the entered password matches the predefined password, the program prints “Access granted.”
- If the entered password does not match, the
else
statement is executed, and the program prints “Access denied.”
- The
This basic password validation exercise demonstrates how conditional statements can be used to perform security checks. It introduces the concept of comparing strings and making decisions based on user input, which is fundamental in many real-world applications.
Exercise 4: Check Eligibility to Vote
# Prompt the user to enter their age
age = int(input("Enter your age: "))
# Check if the user is eligible to vote
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Output:
Enter your age: 20
You are eligible to vote.
Enter your age: 16
You are not eligible to vote yet.
Explanation:
- User Input: The program starts by asking the user to enter their age. The
input()
function captures this input as a string, andint()
converts it to an integer. - Conditional Check:
- The
if
statement checks whether the user’s age is 18 or older (age >= 18
). If this condition is met, the program prints “You are eligible to vote.” - The
else
statement handles the case where the user is younger than 18, printing “You are not eligible to vote yet.”
- The
This exercise is a simple example of using conditional statements to determine eligibility based on a given criterion—in this case, age. It highlights how programming logic can be used to make decisions and provide feedback to the user based on their input.
Elif Statement Exercises
Exercise 5: Determine the Type of Triangle
# Prompt the user to enter the lengths of the three sides of the triangle
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
# Check if the sides form a valid triangle
if side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1:
# Check for the type of triangle
if side1 == side2 == side3:
print("The triangle is an equilateral triangle.")
elif side1 == side2 or side1 == side3 or side2 == side3:
print("The triangle is an isosceles triangle.")
else:
print("The triangle is a scalene triangle.")
else:
print("The given sides do not form a valid triangle.")
Output:
Enter the length of the first side: 5
Enter the length of the second side: 5
Enter the length of the third side: 5
The triangle is an equilateral triangle.
Enter the length of the first side: 5
Enter the length of the second side: 5
Enter the length of the third side: 8
The triangle is an isosceles triangle.
Enter the length of the first side: 3
Enter the length of the second side: 4
Enter the length of the third side: 5
The triangle is a scalene triangle.
Enter the length of the first side: 1
Enter the length of the second side: 2
Enter the length of the third side: 3
The given sides do not form a valid triangle.
Explanation:
- User Input: The program prompts the user to enter the lengths of the three sides of a triangle. The
input()
function is used to capture these values, andfloat()
converts them to floating-point numbers to allow for non-integer inputs. - Triangle Validity Check:
- The first
if
statement checks if the entered side lengths can form a valid triangle. This is based on the triangle inequality theorem, which states that the sum of the lengths of any two sides must be greater than the length of the remaining side. If the sides don’t satisfy this condition, the program prints “The given sides do not form a valid triangle.”
- The first
- Type of Triangle:
- If the triangle is valid, the program checks for the type of triangle:
- Equilateral Triangle: If all three sides are equal (
side1 == side2 == side3
), the triangle is equilateral. - Isosceles Triangle: If exactly two sides are equal (
side1 == side2 or side1 == side3 or side2 == side3
), the triangle is isosceles. - Scalene Triangle: If none of the sides are equal, the triangle is scalene.
- Equilateral Triangle: If all three sides are equal (
- If the triangle is valid, the program checks for the type of triangle:
This exercise combines multiple conditional statements to classify the type of triangle based on user input. It demonstrates how logical conditions can be applied to solve real-world problems, providing a solid example of decision-making in programming.
Exercise 7: Simple Weather Forecast System
# Prompt the user to enter the weather condition
weather = input("Enter the current weather (sunny, rainy, cloudy, snowy): ").lower()
# Simple weather forecast system using conditional statements
if weather == "sunny":
print("It's a bright and beautiful day! Don't forget your sunglasses.")
elif weather == "rainy":
print("It's raining outside. You might want to carry an umbrella.")
elif weather == "cloudy":
print("It's cloudy today. The sun might peek out later.")
elif weather == "snowy":
print("It's snowing! Stay warm and drive safely.")
else:
print("Sorry, I don't recognize that weather condition.")
Output:
Enter the current weather (sunny, rainy, cloudy, snowy): sunny
It's a bright and beautiful day! Don't forget your sunglasses.
Enter the current weather (sunny, rainy, cloudy, snowy): rainy
It's raining outside. You might want to carry an umbrella.
Enter the current weather (sunny, rainy, cloudy, snowy): foggy
Sorry, I don't recognize that weather condition.
Explanation:
- User Input: The program prompts the user to enter the current weather condition (e.g., sunny, rainy, cloudy, snowy). The
input()
function captures the input as a string, and thelower()
method is used to convert the input to lowercase, making the program case-insensitive. - Conditional Weather Responses:
- The
if
andelif
statements check the value ofweather
to match it against predefined conditions:- Sunny: If the user enters “sunny,” the program responds with a message about enjoying the bright day and a reminder to wear sunglasses.
- Rainy: If the user enters “rainy,” the program advises carrying an umbrella.
- Cloudy: If the user enters “cloudy,” the program suggests that the sun might come out later.
- Snowy: If the user enters “snowy,” the program advises staying warm and driving safely.
- The
- Unrecognized Input:
- If the user enters a weather condition that isn’t recognized by the program, the
else
statement is triggered, and it prints a message indicating that the condition isn’t recognized.
- If the user enters a weather condition that isn’t recognized by the program, the
This simple weather forecast system is a great example of how conditional statements can be used to provide customized responses based on user input. It introduces basic decision-making logic and shows how to handle different cases, including unrecognized inputs.
Exercise 7: Identify Day of the Week from a Number
# Prompt the user to enter a number between 1 and 7
day_number = int(input("Enter a number (1-7): "))
# Identify the day of the week based on the number
if day_number == 1:
print("The day is Monday.")
elif day_number == 2:
print("The day is Tuesday.")
elif day_number == 3:
print("The day is Wednesday.")
elif day_number == 4:
print("The day is Thursday.")
elif day_number == 5:
print("The day is Friday.")
elif day_number == 6:
print("The day is Saturday.")
elif day_number == 7:
print("The day is Sunday.")
else:
print("Invalid input! Please enter a number between 1 and 7.")
Output:
Enter a number (1-7): 3
The day is Wednesday.
Enter a number (1-7): 6
The day is Saturday.
Enter a number (1-7): 8
Invalid input! Please enter a number between 1 and 7.
Explanation:
- User Input: The program asks the user to enter a number between 1 and 7, which corresponds to the days of the week. The
input()
function captures the input, andint()
converts it into an integer. - Conditional Statements:
- The
if
andelif
statements match the entered number to a day of the week:1
corresponds to Monday2
corresponds to Tuesday3
corresponds to Wednesday4
corresponds to Thursday5
corresponds to Friday6
corresponds to Saturday7
corresponds to Sunday
- If the number is outside the range of 1 to 7, the
else
statement prints “Invalid input! Please enter a number between 1 and 7.”
- The
This exercise illustrates how to use conditional statements to map numeric input to specific outputs, like identifying days of the week. It’s a simple but effective way to practice handling user input and making decisions based on that input.
Must Read
- AI Pulse Weekly: December 2024 – Latest AI Trends and Innovations
- Can Google’s Quantum Chip Willow Crack Bitcoin’s Encryption? Here’s the Truth
- How to Handle Missing Values in Data Science
- Top Data Science Skills You Must Master in 2025
- How to Automating Data Cleaning with PyCaret
Nested If-Else Statement Exercises
Exercise 8: Age Group Classifier
# Prompt the user to enter their age
age = int(input("Enter your age: "))
# Age group classification using nested if-else statements
if age >= 0: # Valid age check
if age <= 12:
print("You are a Child.")
elif age <= 19:
print("You are a Teenager.")
elif age <= 35:
print("You are an Adult.")
elif age <= 59:
print("You are a Middle-aged Adult.")
else:
print("You are a Senior Citizen.")
else:
print("Invalid age! Please enter a non-negative number.")
Ouput:
Enter your age: 8
You are a Child.
Enter your age: 16
You are a Teenager.
Enter your age: 28
You are an Adult.
Enter your age: 45
You are a Middle-aged Adult.
Enter your age: 65
You are a Senior Citizen.
Enter your age: -5
Invalid age! Please enter a non-negative number.
Explanation:
- User Input: The program begins by asking the user to enter their age. The
input()
function takes the user’s input, andint()
converts it into an integer. - Outer If-Else Statement:
- The first
if
statement checks if the entered age is a valid non-negative number (age >= 0
). If the age is negative, the program prints an error message, “Invalid age! Please enter a non-negative number.”
- The first
- Nested If-Else Statements:
- If the age is valid, the program uses nested
if-else
statements to classify the user into different age groups:- Child: Age is between 0 and 12 (
age <= 12
). - Teenager: Age is between 13 and 19 (
age <= 19
). - Adult: Age is between 20 and 35 (
age <= 35
). - Middle-aged Adult: Age is between 36 and 59 (
age <= 59
). - Senior Citizen: Age is 60 or above.
- Child: Age is between 0 and 12 (
- If the age is valid, the program uses nested
This exercise is a practical example of how nested if-else
statements can be used to handle more complex decision-making processes, like classifying a person into different age groups based on their input. The nested structure allows for checking multiple conditions in a logical order.
Exercise 9: Multi-Tier Pricing Calculator
# Prompt the user to enter the quantity of items purchased
quantity = int(input("Enter the quantity of items purchased: "))
# Initialize the price per item
price_per_item = 100 # Assume each item costs $100
# Calculate the total cost using a multi-tier pricing system
if quantity > 0:
if quantity <= 10:
total_cost = quantity * price_per_item
elif quantity <= 20:
total_cost = quantity * price_per_item * 0.9 # 10% discount
elif quantity <= 50:
total_cost = quantity * price_per_item * 0.8 # 20% discount
else:
total_cost = quantity * price_per_item * 0.7 # 30% discount
print(f"Total cost for {quantity} items is: ${total_cost:.2f}")
else:
print("Invalid quantity! Please enter a positive number.")
Output:
Enter the quantity of items purchased: 8
Total cost for 8 items is: $800.00
Enter the quantity of items purchased: 15
Total cost for 15 items is: $1350.00
Enter the quantity of items purchased: 25
Total cost for 25 items is: $2000.00
Enter the quantity of items purchased: 60
Total cost for 60 items is: $4200.00
Enter the quantity of items purchased: -5
Invalid quantity! Please enter a positive number.
Explanation:
- User Input: The program asks the user to input the quantity of items they wish to purchase. The
input()
function captures this input, andint()
converts it to an integer. - Initialize Price Per Item:
- The program sets a base price of $100 per item (
price_per_item = 100
). This value can be adjusted based on real-world scenarios.
- The program sets a base price of $100 per item (
- Multi-Tier Pricing System:
- The program uses nested
if-else
statements to apply different discounts based on the quantity:- No Discount: If the quantity is 10 or less, no discount is applied, and the total cost is calculated as
quantity * price_per_item
. - 10% Discount: If the quantity is between 11 and 20, a 10% discount is applied (
total_cost = quantity * price_per_item * 0.9
). - 20% Discount: If the quantity is between 21 and 50, a 20% discount is applied (
total_cost = quantity * price_per_item * 0.8
). - 30% Discount: If the quantity is more than 50, a 30% discount is applied (
total_cost = quantity * price_per_item * 0.7
).
- No Discount: If the quantity is 10 or less, no discount is applied, and the total cost is calculated as
- The program uses nested
- Invalid Quantity Handling:
- If the user enters a quantity of 0 or less, the program displays an error message, “Invalid quantity! Please enter a positive number.”
This exercise demonstrates how nested if-else
statements can be used to create a multi-tier pricing system, where discounts are applied based on the quantity purchased. The program calculates the total cost and reflects the appropriate discount, providing a practical example of conditional logic in pricing strategies.
Exercise 10: Validate a Simple Login System
# Predefined username and password
correct_username = "user123"
correct_password = "pass123"
# Prompt the user to enter their username and password
entered_username = input("Enter your username: ")
entered_password = input("Enter your password: ")
# Validate the login credentials
if entered_username == correct_username:
if entered_password == correct_password:
print("Login successful! Welcome!")
else:
print("Incorrect password! Please try again.")
else:
print("Username not found! Please check your username.")
Output:
Enter your username: user123
Enter your password: pass123
Login successful! Welcome!
Enter your username: user123
Enter your password: wrongpass
Incorrect password! Please try again.
Enter your username: wronguser
Enter your password: pass123
Username not found! Please check your username.
Explanation:
- Predefined Credentials:
- The program begins by setting up a predefined username (
correct_username = "user123"
) and password (correct_password = "pass123"
). These values simulate a simple database of user credentials.
- The program begins by setting up a predefined username (
- User Input:
- The user is prompted to enter their username and password using the
input()
function.
- The user is prompted to enter their username and password using the
- Validation Process:
- The program first checks if the entered username matches the predefined username (
entered_username == correct_username
):- If the username is correct, the program then checks if the entered password matches the predefined password (
entered_password == correct_password
). - If both the username and password are correct, the program prints a message, “Login successful! Welcome!”
- If the username is correct, the program then checks if the entered password matches the predefined password (
- If the username is correct but the password is incorrect, the program prints “Incorrect password! Please try again.”
- If the entered username does not match the predefined username, the program prints “Username not found! Please check your username.”
- The program first checks if the entered username matches the predefined username (
- Nested
if-else
Statements:- The nested
if-else
statements ensure that the program first validates the username before checking the password. This structure allows for clear and logical handling of login credentials.
- The nested
This exercise demonstrates how to implement a simple login system using nested if-else
statements to validate user input. It’s a practical example of basic authentication logic, showcasing how to handle different cases like correct login, incorrect password, and unrecognized username.
Real-World Application Exercises
Exercise 12: Simple ATM Transaction Simulator
# Initialize a balance for the account
balance = 1000.0 # Assume the account starts with $1000
# Display options for the user
print("Welcome to the ATM Simulator!")
print("Select an option:")
print("1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")
# Prompt the user to select an option
option = int(input("Enter your option (1-4): "))
# Process the user's selection
if option == 1:
# Option 1: Check Balance
print(f"Your current balance is: ${balance:.2f}")
elif option == 2:
# Option 2: Deposit Money
deposit_amount = float(input("Enter the amount to deposit: "))
if deposit_amount > 0:
balance += deposit_amount
print(f"${deposit_amount:.2f} has been deposited. Your new balance is: ${balance:.2f}")
else:
print("Invalid deposit amount! Please enter a positive number.")
elif option == 3:
# Option 3: Withdraw Money
withdraw_amount = float(input("Enter the amount to withdraw: "))
if withdraw_amount > 0:
if withdraw_amount <= balance:
balance -= withdraw_amount
print(f"${withdraw_amount:.2f} has been withdrawn. Your new balance is: ${balance:.2f}")
else:
print("Insufficient funds!")
else:
print("Invalid withdrawal amount! Please enter a positive number.")
elif option == 4:
# Option 4: Exit
print("Thank you for using the ATM Simulator. Goodbye!")
else:
print("Invalid option! Please select a number between 1 and 4.")
Output:
Welcome to the ATM Simulator!
Select an option:
1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
Enter your option (1-4): 1
Your current balance is: $1000.00
Enter your option (1-4): 2
Enter the amount to deposit: 200
$200.00 has been deposited. Your new balance is: $1200.00
Enter your option (1-4): 3
Enter the amount to withdraw: 300
$300.00 has been withdrawn. Your new balance is: $900.00
Enter your option (1-4): 3
Enter the amount to withdraw: 1100
Insufficient funds!
Enter your option (1-4): 4
Thank you for using the ATM Simulator. Goodbye!
Explanation:
1. Initialize Balance:
- The program starts with a predefined account balance of $1000 (
balance = 1000.0
).
2. Display Options:
The program presents the user with four options:
- Check Balance: View the current account balance.
- Deposit Money: Add money to the account.
- Withdraw Money: Take money out of the account.
- Exit: End the transaction and exit the program.
3. User Input:
- The user selects an option by entering a number between 1 and 4 (
option = int(input("Enter your option (1-4): "))
).
4. Option 1 – Check Balance:
If the user selects this option, the program prints the current account balance.
5. Option 2 – Deposit Money:
- The program prompts the user to enter the amount they want to deposit.
- If the deposit amount is positive, it is added to the balance, and the new balance is displayed. If the deposit amount is negative or zero, the program displays an error message.
6. Option 3 – Withdraw Money:
- The program prompts the user to enter the amount they want to withdraw.
- If the withdrawal amount is positive and does not exceed the current balance, the amount is subtracted from the balance, and the new balance is displayed.
- If the withdrawal amount exceeds the current balance, the program displays an “Insufficient funds!” message.
- If the withdrawal amount is negative or zero, the program displays an error message.
7. Option 4 – Exit:
- If the user selects this option, the program displays a farewell message and ends the simulation.
8. Invalid Option Handling:
- If the user enters a number outside the range of 1 to 4, the program prints an “Invalid option!” message.
This exercise simulates a simple ATM transaction system, illustrating how conditional statements and user input can be used to manage a series of transactions. It helps you understand basic banking operations like checking balances, deposits, and withdrawals, and the importance of handling user input correctly.
Exercise 13: Basic Traffic Light Control System
# Prompt the user to enter the current color of the traffic light
traffic_light = input("Enter the current traffic light color (red, yellow, green): ").lower()
# Control traffic based on the color of the light
if traffic_light == "red":
print("Stop! The light is red.")
elif traffic_light == "yellow":
print("Caution! The light is yellow. Prepare to stop.")
elif traffic_light == "green":
print("Go! The light is green. You can proceed.")
else:
print("Invalid color! Please enter red, yellow, or green.")
Output:
Enter the current traffic light color (red, yellow, green): red
Stop! The light is red.
Enter the current traffic light color (red, yellow, green): yellow
Caution! The light is yellow. Prepare to stop.
Enter the current traffic light color (red, yellow, green): green
Go! The light is green. You can proceed.
Enter the current traffic light color (red, yellow, green): blue
Invalid color! Please enter red, yellow, or green.
Explanation:
- User Input:
- The program asks the user to input the current color of the traffic light (
traffic_light = input(...).lower()
). The.lower()
method is used to make the input case-insensitive.
- The program asks the user to input the current color of the traffic light (
- Traffic Control Logic:
- The program checks the entered color:
- Red: If the light is red, it tells the user to “Stop!”
- Yellow: If the light is yellow, it advises caution and tells the user to “Prepare to stop.”
- Green: If the light is green, it tells the user they can proceed.
- If the user enters a color that isn’t red, yellow, or green, the program outputs an error message.
- The program checks the entered color:
This exercise demonstrates the use of if-elif-else
statements to simulate a basic traffic light control system, which helps understand conditional logic based on user input.
Exercise 14: Shopping Cart Price Calculation
# Initialize an empty shopping cart and total price
shopping_cart = []
total_price = 0.0
# Define the available items with their prices
item_prices = {
"apple": 0.5,
"banana": 0.3,
"bread": 2.0,
"milk": 1.5,
"eggs": 3.0
}
# Display available items to the user
print("Available items:")
for item, price in item_prices.items():
print(f"{item.capitalize()}: ${price:.2f}")
# Loop to add items to the cart
while True:
item = input("Enter an item to add to your cart (or type 'done' to finish): ").lower()
if item == 'done':
break
elif item in item_prices:
shopping_cart.append(item)
total_price += item_prices[item]
print(f"{item.capitalize()} added to your cart. Current total: ${total_price:.2f}")
else:
print("Item not available. Please select an available item.")
# Final cart summary
if shopping_cart:
print("\nFinal shopping cart:")
for item in shopping_cart:
print(f"- {item.capitalize()}")
print(f"Total price: ${total_price:.2f}")
else:
print("Your cart is empty.")
Output:
Available items:
Apple: $0.50
Banana: $0.30
Bread: $2.00
Milk: $1.50
Eggs: $3.00
Enter an item to add to your cart (or type 'done' to finish): apple
Apple added to your cart. Current total: $0.50
Enter an item to add to your cart (or type 'done' to finish): bread
Bread added to your cart. Current total: $2.50
Enter an item to add to your cart (or type 'done' to finish): eggs
Eggs added to your cart. Current total: $5.50
Enter an item to add to your cart (or type 'done' to finish): done
Final shopping cart:
- Apple
- Bread
- Eggs
Total price: $5.50
Explanation:
- Item Prices Dictionary:
- The program defines a dictionary
item_prices
where each item (like apple, banana, etc.) is paired with its price.
- The program defines a dictionary
- User Interaction:
- The program displays the available items and their prices to the user.
- The user can then input items to add to their shopping cart. The program keeps a running total of the cart’s value.
- Adding Items:
- The program uses a
while
loop to continuously prompt the user to add items to the cart. The loop breaks when the user types “done.” - If the entered item exists in the
item_prices
dictionary, it’s added to theshopping_cart
list, and its price is added to thetotal_price
.
- The program uses a
- Invalid Items Handling:
- If the user enters an item not available in the
item_prices
dictionary, the program displays an error message.
- If the user enters an item not available in the
- Final Summary:
- Once the user finishes shopping, the program prints a summary of the items in the cart and the total price.
This exercise showcases how to handle user input, use loops for repeated actions, and manage data in lists and dictionaries. It simulates a simple shopping cart system, a common feature in e-commerce platforms.
Advanced Conditional Logic Exercises
Exercise 15: Create a Basic Calculator with Nested Conditionals
# Display the available operations
print("Basic Calculator")
print("Select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
# Prompt the user to choose an operation
operation = int(input("Enter the number corresponding to the operation (1-4): "))
# Check if the selected operation is valid
if operation in [1, 2, 3, 4]:
# Prompt the user to enter two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform the selected operation using nested conditionals
if operation == 1:
result = num1 + num2
print(f"The result of addition is: {result}")
elif operation == 2:
result = num1 - num2
print(f"The result of subtraction is: {result}")
elif operation == 3:
result = num1 * num2
print(f"The result of multiplication is: {result}")
elif operation == 4:
# Handle division, checking for division by zero
if num2 != 0:
result = num1 / num2
print(f"The result of division is: {result}")
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid operation! Please select a number between 1 and 4.")
Output:
Basic Calculator
Select an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter the number corresponding to the operation (1-4): 1
Enter the first number: 5
Enter the second number: 3
The result of addition is: 8.0
Enter the number corresponding to the operation (1-4): 4
Enter the first number: 10
Enter the second number: 0
Error: Division by zero is not allowed.
Enter the number corresponding to the operation (1-4): 5
Invalid operation! Please select a number between 1 and 4.
Explanation:
- Operation Selection:
- The program begins by displaying the four available operations: addition, subtraction, multiplication, and division.
- The user is prompted to select one of these operations by entering a number between 1 and 4.
- Validating the Operation:
- The program first checks if the user has entered a valid operation number (1-4). If not, it displays an error message.
- User Input for Numbers:
- If a valid operation is selected, the user is asked to input two numbers (
num1
andnum2
), which are used for the calculation.
- If a valid operation is selected, the user is asked to input two numbers (
- Nested Conditionals for Calculations:
- The program then uses nested conditionals (
if-elif-else
) to perform the operation selected by the user:- Addition: Adds
num1
andnum2
and displays the result. - Subtraction: Subtracts
num2
fromnum1
and displays the result. - Multiplication: Multiplies
num1
bynum2
and displays the result. - Division: Divides
num1
bynum2
, but first checks ifnum2
is not zero to avoid division by zero errors.
- Addition: Adds
- The program then uses nested conditionals (
- Division by Zero Handling:
- The program specifically checks for division by zero when performing the division operation. If
num2
is zero, it displays an error message instead of attempting the division.
- The program specifically checks for division by zero when performing the division operation. If
- Invalid Operation Handling:
- If the user selects an invalid operation (i.e., a number outside the range of 1-4), the program immediately informs them of the error.
This exercise introduces the concept of nested conditionals, where decision-making steps are embedded within each other to perform complex operations like building a basic calculator. This example demonstrates how to handle user input, perform arithmetic operations, and implement error checking in a simple yet practical way.
Exercise 16: Movie Recommendation System Based on User Preferences
# Display movie categories
print("Welcome to the Movie Recommendation System!")
print("Select a genre from the following options:")
print("1. Action")
print("2. Comedy")
print("3. Drama")
print("4. Horror")
print("5. Science Fiction")
# Prompt the user to choose a genre
genre = int(input("Enter the number corresponding to your preferred genre (1-5): "))
# Recommend movies based on the selected genre using nested conditionals
if genre == 1:
print("Recommended Action Movies: 'Mad Max: Fury Road', 'John Wick', 'The Dark Knight'")
elif genre == 2:
print("Recommended Comedy Movies: 'Superbad', 'The Hangover', 'Step Brothers'")
elif genre == 3:
print("Recommended Drama Movies: 'The Shawshank Redemption', 'Forrest Gump', 'The Godfather'")
elif genre == 4:
print("Recommended Horror Movies: 'Get Out', 'A Quiet Place', 'The Conjuring'")
elif genre == 5:
print("Recommended Science Fiction Movies: 'Inception', 'Interstellar', 'The Matrix'")
else:
print("Invalid genre! Please select a number between 1 and 5.")
Output:
Welcome to the Movie Recommendation System!
Select a genre from the following options:
1. Action
2. Comedy
3. Drama
4. Horror
5. Science Fiction
Enter the number corresponding to your preferred genre (1-5): 3
Recommended Drama Movies: 'The Shawshank Redemption', 'Forrest Gump', 'The Godfather'
Enter the number corresponding to your preferred genre (1-5): 6
Invalid genre! Please select a number between 1 and 5.
Explanation:
- Genre Options:
- The program starts by listing five movie genres and their corresponding numbers.
- User Input:
- The user selects a genre by entering a number between 1 and 5.
- Movie Recommendations:
- Based on the selected genre, the program uses
if-elif-else
statements to provide movie recommendations:- Action: Lists popular action movies.
- Comedy: Lists popular comedy movies.
- Drama: Lists popular drama movies.
- Horror: Lists popular horror movies.
- Science Fiction: Lists popular science fiction movies.
- Based on the selected genre, the program uses
- Invalid Input Handling:
- If the user enters a number outside the range of 1-5, the program displays an error message.
This exercise helps illustrate how conditional statements can be used to tailor recommendations based on user preferences, providing a practical example of handling user input and delivering customized output.
Exercise 17: Employee Bonus Calculation Based on Multiple Criteria
# Display bonus calculation options
print("Employee Bonus Calculation")
print("Select your performance rating:")
print("1. Excellent")
print("2. Good")
print("3. Average")
print("4. Below Average")
# Prompt the user for performance rating and years of service
rating = int(input("Enter your performance rating (1-4): "))
years_of_service = int(input("Enter the number of years of service: "))
# Calculate bonus based on performance rating and years of service using nested conditionals
if rating in [1, 2, 3, 4]:
if rating == 1:
if years_of_service >= 5:
bonus = 2000
else:
bonus = 1500
elif rating == 2:
if years_of_service >= 5:
bonus = 1500
else:
bonus = 1000
elif rating == 3:
if years_of_service >= 5:
bonus = 1000
else:
bonus = 500
elif rating == 4:
if years_of_service >= 5:
bonus = 500
else:
bonus = 250
print(f"Your bonus is: ${bonus:.2f}")
else:
print("Invalid rating! Please select a number between 1 and 4.")
Output:
Employee Bonus Calculation
Select your performance rating:
1. Excellent
2. Good
3. Average
4. Below Average
Enter your performance rating (1-4): 1
Enter the number of years of service: 6
Your bonus is: $2000.00
Enter your performance rating (1-4): 3
Enter the number of years of service: 3
Your bonus is: $500.00
Enter your performance rating (1-4): 5
Invalid rating! Please select a number between 1 and 4.
Explanation:
- Rating and Years of Service:
- The program prompts the user to select their performance rating (from 1 to 4) and enter their years of service.
- Bonus Calculation:
- The bonus amount is calculated based on both performance rating and years of service using nested conditionals:
- Rating 1 (Excellent): Higher bonus if years of service are 5 or more.
- Rating 2 (Good): Moderate bonus, with a higher amount for 5 or more years of service.
- Rating 3 (Average): Lower bonus, with a higher amount for 5 or more years of service.
- Rating 4 (Below Average): Lowest bonus, with a higher amount for 5 or more years of service.
- The bonus amount is calculated based on both performance rating and years of service using nested conditionals:
- Invalid Rating Handling:
- If the user enters a rating outside the range of 1-4, the program displays an error message.
This exercise demonstrates how to use nested conditionals to calculate bonuses based on multiple criteria, such as performance ratings and years of service, which is a common requirement in real-world employee compensation systems.
Comprehensive Practice Set
Mixed Exercises for Mastery
Exercise 1: Grade Evaluation System
# Prompt the user to enter their grade
grade = float(input("Enter your grade (0-100): "))
# Determine the grade category using nested conditionals
if 0 <= grade <= 100:
if grade >= 90:
print("Grade: A")
elif grade >= 80:
print("Grade: B")
elif grade >= 70:
print("Grade: C")
elif grade >= 60:
print("Grade: D")
else:
print("Grade: F")
else:
print("Invalid grade! Please enter a number between 0 and 100.")
Output:
Enter your grade (0-100): 85
Grade: B
Enter your grade (0-100): 45
Grade: F
Enter your grade (0-100): 105
Invalid grade! Please enter a number between 0 and 100.
Explanation:
- Input Handling: The user inputs a grade, and the program checks if it’s within the valid range (0-100).
- Grade Evaluation: Uses nested conditionals to categorize the grade into an A, B, C, D, or F based on the score.
Exercise 2: Shipping Cost Calculator
# Prompt the user to enter the weight of the package
weight = float(input("Enter the weight of the package in pounds: "))
# Determine the shipping cost based on weight using nested conditionals
if weight > 0:
if weight <= 2:
cost = 5.00
elif weight <= 6:
cost = 10.00
elif weight <= 10:
cost = 15.00
else:
cost = 20.00
print(f"The shipping cost is: ${cost:.2f}")
else:
print("Invalid weight! Please enter a positive number.")
Output:
Enter the weight of the package in pounds: 4
The shipping cost is: $10.00
Enter the weight of the package in pounds: 11
The shipping cost is: $20.00
Enter the weight of the package in pounds: -3
Invalid weight! Please enter a positive number.
Explanation:
- Input Handling: The program checks if the weight is positive.
- Cost Calculation: Uses nested conditionals to determine the shipping cost based on weight.
Advanced Challenges for Experienced Coders
Exercise 3: Complex Discount Calculator
# Prompt the user for the purchase amount and membership status
purchase_amount = float(input("Enter the total purchase amount: "))
membership_status = input("Are you a member? (yes/no): ").lower()
# Calculate discount based on purchase amount and membership status
if purchase_amount > 0:
if membership_status == "yes":
if purchase_amount >= 100:
discount = 0.20
else:
discount = 0.10
else:
if purchase_amount >= 100:
discount = 0.10
else:
discount = 0.05
final_amount = purchase_amount * (1 - discount)
print(f"Discount applied: {discount * 100}%")
print(f"Total amount after discount: ${final_amount:.2f}")
else:
print("Invalid amount! Please enter a positive number.")
Output:
Enter the total purchase amount: 150
Are you a member? (yes/no): yes
Discount applied: 20.0%
Total amount after discount: $120.00
Enter the total purchase amount: 75
Are you a member? (yes/no): no
Discount applied: 5.0%
Total amount after discount: $71.25
Enter the total purchase amount: -50
Invalid amount! Please enter a positive number.
Explanation:
- Input Handling: The program ensures the purchase amount is positive.
- Discount Calculation: Uses nested conditionals to apply different discounts based on membership status and purchase amount.
Exercise 4: Advanced Loan Approval System
# Prompt the user for income, credit score, and loan amount
income = float(input("Enter your annual income: "))
credit_score = int(input("Enter your credit score: "))
loan_amount = float(input("Enter the loan amount requested: "))
# Determine loan approval based on income, credit score, and loan amount
if income > 0 and credit_score >= 0 and loan_amount > 0:
if credit_score >= 750:
if loan_amount <= 0.3 * income:
approval = "Approved"
else:
approval = "Denied"
elif credit_score >= 600:
if loan_amount <= 0.2 * income:
approval = "Approved"
else:
approval = "Denied"
else:
if loan_amount <= 0.1 * income:
approval = "Approved"
else:
approval = "Denied"
print(f"Loan status: {approval}")
else:
print("Invalid input! Ensure all values are positive and credit score is non-negative.")
Output:
Enter your annual income: 50000
Enter your credit score: 780
Enter the loan amount requested: 12000
Loan status: Approved
Enter your annual income: 60000
Enter your credit score: 650
Enter the loan amount requested: 15000
Loan status: Denied
Enter your annual income: 45000
Enter your credit score: 550
Enter the loan amount requested: 6000
Loan status: Approved
Enter your annual income: -10000
Enter your credit score: 700
Enter the loan amount requested: 5000
Invalid input! Ensure all values are positive and credit score is non-negative.
Explanation:
- Input Handling: The program checks if income, credit score, and loan amount are valid.
- Loan Approval: Uses nested conditionals to approve or deny the loan based on income, credit score, and requested loan amount.
These exercises offer a mix of practical scenarios and complex challenges to help solidify your understanding of conditional statements and nested logic in Python.
Conclusion
Exploring conditional statements through practical exercises is an essential step in mastering Python programming. These exercises not only help solidify your understanding of basic and advanced conditional logic but also demonstrate their real-world applications.
From checking if a number is positive, negative, or zero, to determining eligibility for voting, each exercise introduces a unique aspect of conditional statements. By tackling problems such as basic password validation, shipping cost calculations, and movie recommendations, you gain hands-on experience in applying these concepts in diverse scenarios.
As you progress to more advanced challenges, like developing a loan approval system or creating a movie recommendation system, you refine your skills in using nested conditionals and handling complex decision-making processes. These practical applications mirror common programming tasks and prepare you for real-world problem-solving.
By engaging with these exercises, you’ve learned to craft solutions that are both efficient and effective. You now have a strong toolkit for making decisions in your code, ensuring that your programs respond appropriately to varying inputs and conditions. This foundational knowledge is crucial for developing more sophisticated algorithms and applications as you continue your journey in programming.
Keep practicing and experimenting with different conditional scenarios to enhance your problem-solving abilities and coding expertise. The more you work with these concepts, the more intuitive and powerful your programming skills will become.
External Resources
Python Official Documentation – Control Flow Statements
- This is the official Python documentation, which provides a comprehensive overview of control flow statements, including
if
,elif
, andelse
. It’s a great starting point for understanding the syntax and behavior of conditional statements.
FAQs
Answer: Conditional statements in Python are used to execute different blocks of code based on certain conditions. The primary conditional statements are if
, elif
, and else
. They help control the flow of a program by allowing different paths of execution depending on whether specific conditions are true or false.
Answer: Conditional statements are crucial because they allow a program to make decisions and perform different actions based on varying inputs. This decision-making capability is fundamental for creating dynamic and interactive applications, handling user inputs, and managing complex logic.
if
statement work? Answer: The if
statement evaluates a condition, and if the condition is true, it executes a block of code. If the condition is false, the code inside the if
block is skipped. It’s the most basic form of decision-making in a program.
if
, elif
, and else
? Answer:if
: Tests a condition and executes a block of code if the condition is true.elif
(short for “else if”): Tests additional conditions if the initial if
condition is false.else
: Executes a block of code if none of the preceding if
or elif
conditions are true.
if
statements be used? Answer: Nested if
statements involve placing one if
statement inside another. This allows for more complex decision-making where multiple conditions need to be checked in sequence. It’s useful when decisions depend on a series of related conditions.