只接受0到1之间的浮点数 - python

时间:2016-03-05 10:00:21

标签: 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),它会崩溃

2 个答案:

答案 0 :(得分:0)

你应该使用try / except,只有当它是0到1之间的数字时才返回输入,将错误输入作为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,因为您只在 isnumeric 检查后进行投射,这意味着输入是eval'd。如果是这种情况,请使用 raw_input 代替输入

答案 1 :(得分:-1)

首先需要检查它是否真的是浮点数if "." in initial_input,然后您可以继续进行其他转换:

def user_input():
    while True:    
        initial_input = input("Please enter a number between 1 and 0").strip()
        if "." in initial_input or initial_input.isnumeric():
            initial_input = float(initial_input)
            if 0 <= initial_input <= 1:
                print("Thank you.")
                return initial_input
            else:
                print("Please try again, it must be a number between 0 and 1")
        else:
            # Input was not an int or a float
            print("Input MUST be a number!")

initial_input = user_input()