Lesson contents

Python — Conditional expressions

Python chooses a value with the form value_if_true if condition else value_if_false. Only the selected value expression is evaluated.

A simple example

Choose one value

  1. Start with n is 2
  2. Do this Choose by sign
  3. Result positive
The condition selects which word becomes the result.
lesson.py
n = 2
print("positive" if n > 0 else "other")
Output
positive
Advertisements

Choose a report value when a sample is missing

Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. The text for an empty group and the calculated mean are mutually exclusive. Use // because this report requires a whole-number average of nonnegative measurements.

Empty group: No samples. Measured group: 18 ÷ 3. Display: 6.
Handle an empty reading

A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.

Run the example

Use Python 3.9 or later. Run these commands from the directory containing the example.

python3 lesson.py
lesson.py
for count in (0, 3):
    label = "no samples" if count == 0 else str(18 // count)
    print(label)
Output
no samples
6

The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.

Try it yourself

What does an observed total of zero with three samples display?

Check your answer

It displays 0. This is a measured zero, whereas the empty group has no average.

Python language documentation

Related tags

  • Python
  • conditional selection
  • expressions
  • zero division