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
- Start with n is 2
- Do this Choose by sign
- Result positive
n = 2
print("positive" if n > 0 else "other")
positive
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.
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
for count in (0, 3):
label = "no samples" if count == 0 else str(18 // count)
print(label)
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.