Programming fundamentalsLesson 7 of 7 in the course Decisions

Python Conditional Expressions: Syntax, Evaluation, and Precedence

5 flashcards · 4 quiz questions · 5 match pairs · 4 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

expression_if_true if condition else expression_if_false

status = "ready" if is_connected else "offline"

If is_connected is true, status receives "ready". Otherwise, it receives "offline".

Definition: A conditional expression is a single expression that evaluates a condition and produces one of two values.

Python checks the condition first. It then evaluates the expression on the matching side and uses that result as the value of the entire conditional expression. Only the selected branch is evaluated.

All flashcards

What is a conditional expression?
A single Python expression that checks a condition and evaluates one of two expressions to produce a value. It is also called a ternary operator.
What is the general template for a conditional expression?
`expression_if_true if condition else expression_if_false`. Python uses the first expression when the condition is true and the second when it is false.
How does Python evaluate a conditional expression?
Python checks the condition first, then evaluates the expression for the outcome that applies. The selected expression's value becomes the result.
How can a conditional expression be used to find the maximum of two numbers?
Use `max_num = y if x < y else x`. It selects `y` when `x` is less than `y`; otherwise it selects `x`.
What does lowest precedence mean for conditional expressions?
Conditional expressions bind less tightly than other Python operations. When combining one with other operations, use parentheses where needed to make the intended grouping clear.

Quiz questions

  1. What is another name for a conditional expression?Answer: A ternary operator
  2. Which part of a conditional expression is checked first?Answer: The condition
  3. In `"yes" if ready else "no"`, what value is produced when `ready` is false?Answer: `"no"`
  4. What value is assigned to `max_num` when `x` is 8 and `y` is 12 in `max_num = y if x < y else x`?Answer: 12

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons