Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

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.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.