Comparing and Choosing

Let's see how we can compare objects and make decisions in Python.

Coding is not just about writing a linear set of commands to execute. Sometimes, we need the code to behave in a certain way in one situation and another way in a different situation. To make decisions, however, we first need to assess the situation. We should be able to distinguish between the conditions to act accordingly. Did you notice at some point that Edward had some intelligence and could distinguish between things? If you did not, try interacting with the print_info() button in the widget below.

Notice that Edward has the ability to distinguish between whether the block it is in is empty, has a bucket filled with trash, or is occupied by a potted plant. But how is it getting this ability to distinguish between certain states of the block? It does that by comparing the state of the block it is currently in with the set of possible states. In the widget below, we have broken down this functionality to a lower level to show that the print_info() function does in the background. Give it a try!

Wow! So in the background, it was just checking these three conditions, whether they were True or False. It just checks which of the three variables is set to True, and it displays a message according to that.

But how can we compare things using Python? Let's explore that in this lesson.

Comparison operators

Python has dedicated some specific symbols and their combinations to perform some specific tasks. These symbols are known as operators. We are already familiar with some of the operators:

  • The assignment operator (=) that is used to save values in variables.

  • The arithmetic operators (+, -, *, /) that are used to perform simple mathematical operations.

It turns out that a set of symbols known as comparison operators is dedicated to comparing values in Python. These operators require two values to compare, and depending on the statement they check, they output a boolean value. To elaborate on this concept further, we have jotted them down in the table below and included an example of each comparison operator.

Comparison Statement

Description of the Statement

Output

5 == 3

5 is equal to 3

False

3 != 4

3 is not equal to 4

True

5 > 6

5 is greater than 6

False

5 >= 5

5 is greater than or equal to 5

True

5 < 6

5 is less than 6

True

3 <= 0

3 is less than or equal to 0

False

We can save the output in a variable and/or print it on the screen. The following widget shows an example use case of the equality operator. Play around and try using different operators and values!

Python 3.10.4
print("The value of first comparison:", 2 == 2)
print("The value of second comparison:", 5 < 2)

Line 1: Making a comparison between the two values 2 == 2 and directly printing the result of the comparison.

Line 2: Making a comparison between the two values 5 < 2 and directly printing the result of the comparison.

Great! We now know how to compare two values. The next step is to learn how to make decisions depending on the outcomes of the comparisons.

Making decisions

So far, the code we’ve written executes in a sequential manner, with each step following the previous one.

The lines execute one-by-one and no line is skipped
1 / 9
The lines execute one-by-one and no line is skipped

With comparison operators at our disposal, we can choose whether to execute some lines or not. If our requirement to run a specific code block is met, we run it; else we will run some other lines of code. if, elif, and else are the keywords that we can use along with comparison operators to set a condition on code execution. These specific keywords are known as conditionals.

Execution of code depends on the condition being met
1 / 12
Execution of code depends on the condition being met

Let's consider the simple example below. The print statement will execute only if you guess the number right.

Python 3.10.4
def check_number(number):
if number == 5:
print("That's the number!")
guess = 2 # Change the number of this variable as required.
check_number(guess)

We will often need the code to do something if the specified condition is not met. We can also add the code that executes if the condition is not met in the else block. Can you improve the code written below to include the else conditional block? Simply print an appropriate message in the else block for the case when we guess the number wrong. If you get stuck, you may ask the AI mentor for help.

Python 3.10.4
def check_number(number):
# Improve this code by including the else conditioned code block.
if number == 5:
print("That's the number!")
guess = 2 # Change the number of this variable to match the need.
check_number(guess)

Adding to the functionality, we can include multiple options against multiple conditions. This can be achieved using the elif command. We have provided you with the starter code with the if conditional block for when the number is equal to 5. Try adding both elif and else conditional blocks in the code to cater to the conditions when the number is less than or greater than 5. The AI mentor is here to help you if needed!

Python 3.10.4
def check_number(number):
if number == 5:
print("That's the number!")
guess = 12 # Change the number of this variable as required.
check_number(guess)

Review

Let's get some hands-on practice with the concepts we just learned. We have to make a menu with several items with it, each with a specific ID number. A starter code has been provided for you. It is functional, but some functionality is broken. Try running the code and interact with it to see the defects in functionality (logical errors). These logical errors have arisen due to an incomplete implementation of code. We have marked some portions where the code is missing. Can you fill those gaps to make it work properly?

def greet_customer():
    # Greet the user and ask for their name
    print("Welcome to Our Restaurant!")
    print("May I have your name, please?")
    name = input("Enter your name here: ")
    print() # For new line
    
    # Output the name obtained
    return name

def ask_for_starter(name):
    # Prompt for input
    print("Hello", name, "! Here is our menu for starters:")
    print("1. Soup, 2. Salad, 3. Garlic Bread")

    # Taking the input
    starter = input("Please enter the number associated with your desired item: ")
    
    # Output the required value
    return starter

def ask_for_main():
    # Prompt for input
    print("What would you like to have for the main course?")
    print("1. Steak, 2. Pasta, 3. Burger")
    
    # Taking the input
    main = input("Please enter the number associated with your desired item: ")
    
    # Output the required value
    return main

def ask_for_dessert():
    # Prompt for input
    print("Lastly, what would you like to have for dessert?")
    print("1. Cake, 2. Ice cream, 3. Fruit Salad.")
    
    # Taking the input
    choice = input("Please enter the required number for your desired item: ")
    
    # Output the required value
    return choice

def check_starter(choice):
    if choice == "1":
        starter = "Soup"
    elif choice == "2":
        starter = "Salad"
    elif choice == "3":
        starter = "Garlic Bread"
    else: # To respond to the user in case of invalid input.
        print("Sorry, that item is not on the menu.")
        return
    print("Got it.", starter, "for starters.")
    print() # for new line    
    return starter

def check_main(choice):
    # TODO 1: Fill in the required conditions.
    if choice == ... :
        main = "Steak"
    elif choice == ... :
        main = "Pasta"
    elif choice == ... :
        main = "Burger"
    else: # To respond to the user in case of invalid input.
        print("Sorry, that item is not on the menu.")
        print() # for new line
        return
    print("Got it.", main, "for main entree.")
    print() # for new line
    return main

def check_dessert(choice):
    # TODO 2: Write to code to determine the conditions and what to print when a conition is met.
    dessert = "Cake"
    dessert = "Icecream"
    dessert = "Fruit Salad"
    print(dessert, " for dessert it is.")
    print("Sorry, we don't serve that here.")
    print() # for new line
    return dessert

# Function for order confirmation.
def repeat_order(customer_name, starter, main, dessert):
    print("Thank you", customer_name,"! I'm repeating your order:")
    print(starter, "for starters")
    print(main, "for main menu")
    print(dessert, "for dessert")

# Functions called in a sequential manner
customer_name = greet_customer()
starter_choice = ask_for_starter(customer_name)
starter = check_starter(starter_choice)
main_choice = ask_for_main()
main = check_main(main_choice)
dessert_choice = ask_for_dessert()
dessert = check_dessert(dessert_choice)
# TODO 3: Make a call to the repeat order function.

print() # for new line
E-waiter program
Show Hint

Recap

Key takeaways:

  1. Comparison operators: Specific symbols that allow us to compare the values of certain Python objects. Their outputs are boolean values

  2. Conditionals: Specific keywords reserved by Python to make decisions regarding code execution. The keywords reserved as conditional in Python are if, elif, and else.


A quick quiz

  1. Consider the following Python code snippet:

num = 10
if num < 5:
print("The number is less than 5.")
elif num == 10:
print("The number is exactly 10.")
elif num > 5:
print("The number is greater than 5.")
else:
print("The number does not fit into any category.")

Question: Describe in words the execution flow of the above code with the if-elif-else statements. Specifically, explain what happens after one of the conditions becomes true.

Saved
A quick knowledge check
  1. Examine the following loop code snippet:

i = 0
while i < 5:
if i == 3:
break
print(i)
i = i + 1

Question: In the context of this code, explain the difference between = and ==.

Saved
A quick knowledge check