Winterflags Winterflags - 5 months ago 23
Python Question

Python: Can this If / Elif control flow tree be shortened?

In Python, I'm going to write a bunch of rules that prints out the "highest order" in a tree hierarchy.

level_1
is the lowest and
level_3
is the highest order.

The "highest order" available should be printed. Only if
level_3
is
None
, do we continue to test to print
level_2
, and so forth.

level_1 = "Trunk"
level_2 = "Branch"
level_3 = "Leaf"

if level_3 is not None:
print level_3

elif level_2 is not None:
print level_2

elif level_1 is not None:
print level_1

>>> "Leaf"


Question:

Is there a way that this code can be simplified in Python? Ideally to as few rows as possible.

Whereby I mean, shortening the code length. (The issue is not deployment of the code for different cases, because it can be put in a function and used many times over).

Answer

how about

for msj in (level_3,level_2,level_1):
    if msj:
        print msj
        break

or a variation to Reut solution

msj = level_3 or level_2 or level_1
if msj:
    print msj

both solution will print the first non-empty and non-None element they come across