Winterflags Winterflags - 9 months ago 41
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.

is the lowest and
is the highest order.

The "highest order" available should be printed. Only if
, do we continue to test to print
, 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"


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).


how about

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

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