Python Forum
Learning about if statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learning about if statements
#1
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")
Larz60+ write Nov-15-2020, 07:27 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Fixed for you this time. Please use bbcode tags on future posts.
Reply
#2
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020