检查用户输入是否在两个浮点数之间 - Python



我目前正在做一个小项目,该项目将接受用户输入,例如"50",并将其转换为浮点数,同时还将小数点放在左侧,例如"0.50" - 这部分我以我想要的方式工作,但是我现在遇到的似乎无法解决的问题是检查该值是否在另外两个浮点值之间。这是我到目前为止所拥有的。

value = float(input("Enter number: "))
value /= 100
if 0.61 <= value <= 69:
value = value - 0.049 # don't worry about this part

elif 0.70 <= value <= 79:
value = value - 0.10 # don't worry about this part


"""
if value >= 0.61:        
value = value - 0.049
if value >= 0.70:        
value = value - 1.5
"""

当我输入高于 69 的任何内容时,例如 70 或 71 等。程序似乎没有意识到我正在尝试以不同的方式调整值,就好像输入是 65 一样,程序知道该怎么做。底部是我尝试过的其他东西,但没有得到任何运气。

我用错了吗?为什么我无法正确读取我的第二个 if 语句?或者是否有一个函数或其他东西可以让我检查该值是否在两个浮点范围之间?

我感谢这些努力。

欢迎来到SO。

编辑: 应该适合您的评论的解决方案。

value = float(input("Input a number"))
if value >= 0.61 and value <= 0.69:
#whatever should happen here

elif value >= 0.70 and value <= 0.79:
#whatever you want to happen here

你真的需要将值除以 100 吗,如果是这样,那么你将永远不会完全进入第二个循环,因为当你的值介于0.69 and 69之间时,第一个 if 语句将被执行,如果你把它除以 100,它可以是任何值,因此它永远不会进入第二个 if 语句。

如果您确实想保留/100 但执行 TWO 语句,那么您只需将elif更改为 和if即可,以便在语句为 true 时也会执行它。不过,这将执行 TWO if 语句。

value = float(input("Input a number"))
value /= 100
if value >= 0.61 and value <= 69:
#whatever should happen here

if value >= 0.70 and value <= 79:
#whatever you want to happen here

这样,如果输入的值70则结果将是两个 if 语句都将被执行。

如果可以省略/100,则此处的代码有效,并且仅执行 ONE if 语句。

value = float(input("Input a number"))
if value >= 61 and value <= 69:
#whatever should happen here

elif value >= 70 and value <= 79:
#whatever you want to happen here

最新更新