如何提示用户选择介于0到90之间的间隔并将其存储为浮点数?

问题描述 投票:0回答:2

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

到目前为止的代码如下:

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

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

python variables output user-input intervals
2个回答
0
投票

如果要将输入存储为浮点数,请使用函数“ float”:

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

0
投票

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]")

# Then convert 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)) 
© www.soinside.com 2019 - 2024. All rights reserved.