Python Forum

Full Version: Learning about if statements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Bello, I am learning about if statements. The question is to assign True or False to variables small and green. Then write some if/else statements to print which of these matches those choices; cherry, pea, watermelon and pumpkin.

Which of these two is better? Which is more pythonic?

small = True
green = False
if small and green:
    print("pea")
elif small and not green:
    print("cherry")
elif not small and green:
    print("watermelon")
elif not small and not green:
    print("pumpkin")
or

small = True
green = False
if small:
    if green:
        print("pea")
    else:
        print("cherry")
else:
    if green:
        print("watermelon")
    else:
        print("pumpkin")
I would argue for the top version, from the point of view of maintainability and expandability. What happens if another fruit is introduced, apple? Add a couple lines to the first one and you are fine. But, how do you fix the second code snippet to handle apples? And then they add coconuts. And they migrate.