Using Python Conditional Expressions

30 minutes
  • 3 Learning Objectives

About this Hands-on Lab

We need to constantly evaluate a condition of some kind to determine what action to take or what value to assign to a variable we’ll use later in our program. In the situation where we only have an `if` and an `else`, and the body of each branch contains only one expression, then we’re able to use a conditional expression. Conditional expressions can be used to succinctly express a simple conditional. In this hands-on lab, we’ll be refactoring an existing script by rewriting the simple conditional statements as conditional expressions.

The following is a prerequisite for feeling comfortable completing this lab:

– Conditional expressions.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Call `print` with a Different String Using a Single Conditional Expression

Our first conditional statement checks the length of the name passed in and prints a different message depending on that length. We’ve been tasked with writing a conditional expression that calls one of these print functions if true and the other if false.

process_name.py

name = input("What is your first name? ")

# 1) Call `print` with a different string using a single conditional expression
# 1) Call `print` with a different string using a single conditional expression
print(
    "Your name is as long or longer than the average first name in the United States"
) if len(name) >= 6 else print(
    "Your name is shorter than the average first name in the United States"
)

These messages are pretty long, so it makes it easier to read if we spread this expression across multiple lines. However, we are still running only one expression.

Assign a Value to the `message` Variable Based on a Conditional Expression

Each branch for our next conditional statement assigns a value to the message variable. Because of this, we can assign the value returned by a conditional expression directly to the message variable.

process_name.py

# 2) Set `message` using a single conditional expression
message = (
    "The first letter in your name is among the five most common"
    if name[0].lower() in ["a", "j", "m", "e", "l"]
    else "The first letter of your name is not among the five most common"
)

print(message)

The strings that we might assign to message are fairly long, but we can spread this expression across multiple lines by wrapping the entire expression in parenthesis.

Change the String Passed to the `print` Function Using a Conditional Expression

We want to change the string that is printed as we iterate over all of the letters in our name variable. The portion of the printed message that is different based on the letter is at the end. We can utilize a conditional expression from within the print function instead of having two separate print lines.

process_name.py

# 3) Change the string passed to the `print` function using a conditional expression
for letter in name:
    print(
        f"{letter} {'is a vowel' if letter.lower() in ['a', 'e', 'i', 'o', 'u'] else 'is a consonant'}"
    )

Additional Resources

Because we're refactoring an existing script, our goal is to not change what happens when we run the script. To run process_name.py, we'll pass it to our Python interpreter and then answer a few questions.

$ python3.7 processing_items.py
What is your first name? Keith
Your name is shorter than the average first name in the United States
The first letter of your name is not among the five most common
K is a consonant
e is a vowel
i is a vowel
t is a consonant
h is a consonant

We're going to rewrite the conditional statements that are used in the process_name.py script to be conditional expressions instead. We're able to do this only because each branch in the conditionals has just one expression.

Logging In

Using the Terminal To Complete the Lab

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the lab, log in with SSH, and use a text editor in the terminal, such as Vim.

Note: When copying and pasting code into Vim from the lab guide, first enter :set paste (and then i to enter insert mode) to avoid adding unnecessary spaces and hashes. To save and quit the file, press Escape followed by :wq. To exit the file without saving, press Escape followed by :q!.

Using VS Code To Complete the Lab

You can also access the lab using VS Code in the browser. If you'd like to go this route, then follow the steps below:

  1. Navigate to the public IP address of the workstation server (provided in your lab credentials) on port 8080, using http (e.g., http://PUBLIC_IP:8080).
  2. If you receive a notification indicating the connection is not secure, click Advanced. Then, proceed to the server.
  3. Use the password provided in your lab credentials.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?