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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With