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

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab overview page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. For this route, navigate to the public IP address of the workstation server provided in the hands-on lab overview page. Make sure to access the link on port 8080 (e.g. http://PUBLIC_IP:8080). Your password will be the same password that you'd use to connect over SSH.

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.

Get Started
Who’s going to be learning?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout
Sign In
Welcome Back!
Thanks for reaching out!

You’ll hear from us shortly. In the meantime, why not check out what our customers have to say about ACG?