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 themessage
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 theletter
is at the end. We can utilize a conditional expression from within theprint
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'}" )