python-3.x - 仅接受介于0和1之间的 float -python

标签 python-3.x error-handling floating-point

因此,我需要一个真正有效的代码,该代码将接受用户的0到1之间的任何数字,并不断提示他们重试,直到他们的输入满足此条件。
到目前为止,这是我得到的:

def user_input():
while True:
    global initial_input
    initial_input = input("Please enter a number between 1 and 0")
    if initial_input.isnumeric() and (0 <= float(initial_input) <= 1):
        initial_input = float(initial_input)
        return(initial_input)
    print("Please try again, it must be a number between 0 and 1")
user_input()

这有效,但仅当数字实际为1或0时。如果您在两者之间输入小数(例如0.6),则会崩溃

最佳答案

仅当输入是介于0和1之间的数字时,才应使用try/except返回输入,将错误的输入捕获为ValueError:

def user_input():
    while True:
        try:
            # cast to float
            initial_input = float(input("Please enter a number between 1 and 0"))      # check it is in the correct range and is so return 
            if 0 <= initial_input <= 1:
                return (initial_input)
            # else tell user they are not in the correct range
            print("Please try again, it must be a number between 0 and 1")
        except ValueError:
            # got something that could not be cast to a float
            print("Input must be numeric.")

另外,如果您使用自己的代码获取"Unresolved attribute reference 'is numeric' for class 'float'".,则说明您使用的是python2而不是python3,因为您只在等数字检查后才进行转换,因此意味着输入已被评估。如果是这种情况,请使用raw_input代替输入。

关于python-3.x - 仅接受介于0和1之间的 float -python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812703/

相关文章:

在 ANTLR 中使用正确的 CSS 解析约定解析 CSS 2.1

ios - NSDecimalNumber 不是应该能够进行以 10 为底的算术吗?

python-3.x - 使用 matplotlib 和 python 绘制所有三角函数 (x^2 + y^2 == 1)

python-3.x - Pandas 彼此更改日期

python-3.x - 从 pandastable 获取索引号

r - 在R中出现错误消息后添加更多详细信息

string - 返回结果,带无引号的字符串

java - 通过反射获取 Java 字段,而不是通过其 String 名称

c - 尽管未对其进行任何更改,C 中的全局变量也会发生变化

python - 如何系统地识别 Python 在其可访问的包/模块树中的依赖关系?