Conditional expressions

4.7 Conditional expressions

Learning objectives

By the end of this section you should be able to

  • Identify the components of a conditional expression.
  • Create a conditional expression.

Conditional expressions

A conditional expression (also known as a "ternary operator") is a simplified, single-line version of an if-else statement.

Conditional expression template:

    expression_if_true if condition else expression_if_false

A conditional expression is evaluated by first checking the condition. If condition is true, expression_if_true is evaluated, and the result is the resulting value of the conditional expression. Else, expression_if_false is evaluated, and the result is the resulting value of the conditional expression.

A variable can be assigned with a conditional expression. Ex: Finding the max of two numbers can be calculated with max_num = y if x < y else x

Note: Conditional expressions have the lowest precedence of all Python operations.

Checkpoint

Example: Version check

Concepts in Practice

Using conditional expressions

1.
What is the conditional expression version of the following if-else statement?
if x%2 == 0:
  response = 'even'
else:
  response = 'odd'
  1. response = if x%2 == 0 "even" else "odd"
  2. response = "odd" if x%2 == 0 else "even"
  3. response = "even" if x%2 == 0 else "odd"
2.
Given x = 100 and offset = 10, what is the value of result?
result = x + offset if x < 100 else x - offset
  1. 90
  2. 100
  3. 110
3.
Which part of the conditional expression is incorrect?
min_num = x if x < y else min_num = y
  1. min_num = x
  2. x < y
  3. min_num = y
4.
Which of the following is an improved version of the following if-else statement?
if x < 50:
  result = True
else:
  result = False
  1. result = True if x < 50 else False
  2. result = x < 50
5.
What are the possible values of total?
total = fee + 10 if hours > 12 else 2
  1. 10, 2
  2. fee + 10, 2
  3. fee + 10, fee + 2

Try It

Ping values

Write a program that reads in an integer, ping, and prints ping_report, a string indicating whether the ping is low to average or too high. ping values under 150 have a ping_report of "low to average". ping values of 150 and higher have a ping_report of "too high". Use a conditional expression to assign ping_report.

Ex: If the input is 30, the output is "Ping is low to average".