Home > Software design >  why wont I get the output "good" in this if statement?
why wont I get the output "good" in this if statement?

Time:07-24

I changed the value of pressure to 31 or even higher. But still I wont be able to get the output "good" as expected. Would be happy to learn why I can't get the expected output.

pressure = 32

if pressure <= 20:
    print("bad")

elif pressure >20 or pressure <=30:
    print("medium")

elif pressure >30:
    print("good")

CodePudding user response:

You should use and instead of or in the first elif statement

if pressure <= 20:
    print("bad")

elif pressure >20 and pressure <=30:
    print("medium")

elif pressure >30:
    print("good")

The and operator returns True only if both operands are True.

The or operator returns True if either operand is true.

CodePudding user response:

Your third check never gets evaluated because in your second check you're checking to see if pressure is more than 20, which will always pass (when passing 32). You don't need to check that pressure is more than 20 if it passes the first statement:

if pressure <= 20:
    print("bad")

elif pressure <= 30:
    print("medium")

elif pressure > 30:
    print("good")

CodePudding user response:

your code doesn't work because the check pressure > 20 or pressure <= 30 evaluates also with the numbers from range 20 to 30 (all numbers would work):

To make your code work properly you should:

  • Instead of an or, you should use an and or &

  • for readabililty purpose I advise to use chained comparisons

  • Use an else at the end; all the possible numbers less than 30 had already been in some check.

This is the code I made using this adjustments:

elif pressure < 20:
    print("low")
elif 20 <= pressure <=30:
   print("medium")
# # same as:

# elif 20 <= pressure and pressure <=30:
#    print("medium")
else:
   print("high")

this gives the same output as this one but i don't reccomend it because of the poor readability

elif 20 < pressure:
   print("low")
elif pressure <= 30:
   print("medium")
else:
   print("high")

this works because the elif goes into the next statement only if the block before was False and not executed.

  • Related