Sunday, May 14, 2023

Pythons chained conditional expressions (and Fizz Buzz)

 I was lurking on the LinkedIn Python forum and someone brought up FizzBuzz again and I thought; "Why not try a solution that closely follows the description"

The description given was:

Print a range of numbers from 1 to 100 but for multiples of 3, print "Fizz", for multiples of 5 print "Buzz" and for multiples of both 3 and 5 print "FizzBuzz".

Common factors

You know that because fifteen is a factor of three and five,but three and five share no common factors you can test first for fifteen then for either three or five, Since three is mentioned first I chose to test in order of fifteen, three then five.

We are already moving away from the textual description out of necessity.

Pythons chained conditional expressions

Hiding in plain site of the docs you have:

conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr

The else part of a conditional expression can itself be a conditional expression!

For FizzBuzz there are multiple conditions. Let's try stringing them along, and I will use F and B instead of Fizz and Buzz to better show the chained conditional expression:

for i in range(1, 101):
    print('FB' if not i % 15 else 'F' if not i % 3 else 'B' if not i % 5 else i)

The corresponding English description has changed, but it should be straight-forward in its logic.

Here's a picture of this type of chained conditional expressions in action:


END.