Python Forum

Full Version: Use of if - and operators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Is use of the code below accurate? I believe it is not however, my friend tells me it is.

age=int(input("Enter your age: "))

if  21<age<=25 :
    money=125

elif 21<age :
    money=100

else:
    money=250

print(money)
It is valid python code, but I can't tell you if it produces the results you want. You didn't describe what the code is supposed to do

It is confusing because the 21 < age overlaps with 21<age<=25. The overlap is resolved because ages in the range 21 to 25 match the first comparison, and the rest of the if statement is skipped. Below is code that might be less confusing, but produces the same results:
if  21<age<=25 :
    money=125
 
elif 25<age :
    money=100
 
else:
    money=250
I think the following code is easier to read, but it might only be easier to read if you are a programmer. Here we have tons of overlap in the ranges, but like the code in your post, the overlap is resolved by the order of the comparisons.
if age < 21:
    money = 250
elif age <= 25:
    money = 125
else:
    money = 100