Skip to content
Home » Blog » Practical Exercises on Conditional Statements in Python

Practical Exercises on Conditional Statements in Python

Practical Exercises on  Conditional Statements in Python

Table of Contents

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

Flowchart illustrating the steps of a basic if statement in Python, including decision-making and paths for true and false conditions.
Flowchart of a basic if statement in Python showing the process from checking a condition to executing code based on true or false outcomes.

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:

  1. User Input: The program starts by asking the user to enter a number. The input() function is used to get this input, and float() converts the input to a floating-point number, allowing the user to enter decimal numbers as well.
  2. 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.”

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:

  1. User Input: The program begins by asking the user to enter an integer. The input() function captures this input as a string, and int() converts it to an integer.
  2. Modulus Operator %: This operator is key to determining whether a number is even or odd. The expression number % 2 computes the remainder when number 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.
  3. 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.

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:

  1. Predefined Password: The program starts by setting a predefined password, "EmiTechLogic", which represents the correct password that users need to enter.
  2. User Input: The program then prompts the user to enter a password using the input() function. The user’s input is stored in the variable entered_password.
  3. Conditional Check:
    • The if statement compares the entered_password with the correct_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.”

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:

  1. User Input: The program starts by asking the user to enter their age. The input() function captures this input as a string, and int() converts it to an integer.
  2. 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.”

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

Tree-like flowchart illustrating decision-making with elif statements in Python, showing different conditions and their outcomes.
Elif Statements: Visualizing the flow of decision-making in a Python program with multiple conditions.

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:

  1. 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, and float() converts them to floating-point numbers to allow for non-integer inputs.
  2. 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.”
  3. 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.

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:

  1. 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 the lower() method is used to convert the input to lowercase, making the program case-insensitive.
  2. Conditional Weather Responses:
    • The if and elif statements check the value of weather 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.
  3. 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.

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:

  1. 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, and int() converts it into an integer.
  2. Conditional Statements:
    • The if and elif statements match the entered number to a day of the week:
      • 1 corresponds to Monday
      • 2 corresponds to Tuesday
      • 3 corresponds to Wednesday
      • 4 corresponds to Thursday
      • 5 corresponds to Friday
      • 6 corresponds to Saturday
      • 7 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.”

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


Nested If-Else Statement Exercises

Mind Map diagram illustrating nested if-else statements with decision points and outcomes.
Diagram illustrating the flow of nested if-else statements

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:

  1. User Input: The program begins by asking the user to enter their age. The input() function takes the user’s input, and int() converts it into an integer.
  2. 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.”
  3. 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.

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:

  1. User Input: The program asks the user to input the quantity of items they wish to purchase. The input() function captures this input, and int() converts it to an integer.
  2. 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.
  3. 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).
  4. 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:

  1. 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.
  2. User Input:
    • The user is prompted to enter their username and password using the input() function.
  3. 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 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.”
  4. 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.

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:

  1. 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.
  2. 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.

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:

  1. Item Prices Dictionary:
    • The program defines a dictionary item_prices where each item (like apple, banana, etc.) is paired with its price.
  2. 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.
  3. 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 the shopping_cart list, and its price is added to the total_price.
  4. Invalid Items Handling:
    • If the user enters an item not available in the item_prices dictionary, the program displays an error message.
  5. 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

Mind Map diagram showing advanced conditional logic with multiple layers of conditions and outcomes.
Diagram illustrating advanced conditional logic exercises with nested conditions and multiple decision points.

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:

  1. 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.
  2. 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.
  3. User Input for Numbers:
    • If a valid operation is selected, the user is asked to input two numbers (num1 and num2), which are used for the calculation.
  4. Nested Conditionals for Calculations:
    • The program then uses nested conditionals (if-elif-else) to perform the operation selected by the user:
      • Addition: Adds num1 and num2 and displays the result.
      • Subtraction: Subtracts num2 from num1 and displays the result.
      • Multiplication: Multiplies num1 by num2 and displays the result.
      • Division: Divides num1 by num2, but first checks if num2 is not zero to avoid division by zero errors.
  5. 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.
  6. 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:

  1. Genre Options:
    • The program starts by listing five movie genres and their corresponding numbers.
  2. User Input:
    • The user selects a genre by entering a number between 1 and 5.
  3. 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.
  4. 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:

  1. 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.
  2. 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.
  3. 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, and else. It’s a great starting point for understanding the syntax and behavior of conditional statements.

FAQs

1. What are conditional statements in Python?

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.

2. Why are conditional statements important in programming?

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.

3. How does the 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.

4. What is the difference between 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.

5. How can nested 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.

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *