如何提示用户选择 0-90 之间的间隔并存储为浮点数?



到目前为止,我有一个代码,但我试图提示用户输入一个介于 [0-90] 之间的数字,例如 20 并将其存储为浮点数。

到目前为止的代码如下所示:

x=input("Choose a number Between [0, 90]")
x=float(20)

目标是让他们选择 20 个;如果他们选择其他号码,它将退出。

Python是一种"鸭子类型"语言。由于任何变量都可以是任何类型,在赋值时确定,因此您需要显式检查值输入以确保它介于 0 和 99 之间。

# First Set a standard error message here. 
# Note the use of "{}" which will be filled in using the python method "format" later. 
err = "The value must be a floating point number between 0 and 99. The value '{}' is invalid."
# Then get the value itself.
x=input("Choose a number Between [0, 90]")
# The value "x" will be a string, no matter what is typed. So you must convert it to a float. 
# Because an invalid input (such as "a") will error out, I would use a try/except format. 
try: 
x=float(x)
except ValueError as e: 
print(err.format(x))
# Then check the value itself
if ( (x < 0) or (x > 99) ):
raise ValueError(err.format(x)) 

@עומר דודסון 的答案也是正确的,因为它会在输入时尝试将输入转换为浮点数。如果输入了无效的输入,例如"a",它将引发错误...所以我仍然会尝试/除了...

try: 
x=float( input("Choose a number Between [0, 90]") )
except ValueError as e: 
print(err.format(x))
# But you still need to check the value itself
if ( (x < 0) or (x > 99) ):
raise ValueError(err.format(x)) 

如果你想将输入存储为浮点数,那么使用函数"float":

x=float(input("Choose a number Between [0, 90]"))

相关内容

  • 没有找到相关文章

最新更新