[英]Python greater than or less than
I have an 'if-elif-else' block and if a value is within that range it is assigned a certain value.我有一个“if-elif-else”块,如果一个值在该范围内,它就会被分配一个特定的值。 However it when I run it just assigns it the value in the else block.
但是,当我运行它时,它只是为它分配了 else 块中的值。 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. Mile 返回一个浮点数,但我认为这并不像 Java 中的那么重要。
Thanks谢谢
Maybe mile
is a string containing a number?也许
mile
是一个包含数字的字符串? 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.您不需要让
elif
重新检查之前的if
为假。 If the value wasn't < 300
, it is guaranteed to be >=300
.如果该值不是
< 300
,则保证为>=300
。
The issue was that 'mile' was a string and as pointed out by other members string is not automatically converted.问题是 'mile' 是一个字符串,正如其他成员指出的那样,字符串不会自动转换。 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.使用打印类型(英里)有助于检查类型是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.