Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python greater than or less than [duplicate]

I have an 'if-elif-else' block and if a value is within that range it is assigned a certain value. However it when I run it just assigns it the value in the else block. This is my code:

if mile < 300:
    mileInfo['miles'] = 1
elif mile>=300 and mile <2000:
    mileInfo['miles'] = 2
elif mile>=2000 and mile <5000:
    mileInfo['miles'] = 3
else:
    mileInfo['miles'] = 4

Mile returns a float, but I thought that this didn't matter as much as in Java for example.

Thanks

like image 763
user94628 Avatar asked Feb 05 '26 10:02

user94628


2 Answers

Maybe mile is a string containing a number? It will not be automatically converted.

>>> "1" < 100
False
>>> "1" == 1
False

You don't need to have the elif re-check that the previous if was false. If the value wasn't < 300, it is guaranteed to be >=300.

like image 112
Has QUIT--Anony-Mousse Avatar answered Feb 06 '26 22:02

Has QUIT--Anony-Mousse


The issue was that 'mile' was a string and as pointed out by other members string is not automatically converted. So I changed code to:

mileInt = int(float(mile))

if mileInt < 300:
    mileInfo['miles'] = 1
elif mileInt < 2000:
    mileInfo['miles'] = 2
elif mileInt < 5000:
    mileInfo['miles'] = 3
else:
    mileInfo['miles'] = 4

Using print type(mile) helps check what the type is.

like image 24
user94628 Avatar answered Feb 07 '26 00:02

user94628



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!