Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 输入x和y之间的值_Python_Python 3.x_Numbers_User Input - Fatal编程技术网

Python 输入x和y之间的值

Python 输入x和y之间的值,python,python-3.x,numbers,user-input,Python,Python 3.x,Numbers,User Input,因此,我需要收集用户的输入,但我必须确保在程序接受输入之前,用户只能输入1到0之间的数字。 以下是我到目前为止得到的信息: def user_input(): try: initial_input = float(input("Please enter a number between 1 and 0")) except ValueError: print("Please try again, it must be a number betw

因此,我需要收集用户的输入,但我必须确保在程序接受输入之前,用户只能输入1到0之间的数字。 以下是我到目前为止得到的信息:

def user_input():
    try:

        initial_input = float(input("Please enter a number between 1 and 0"))

    except ValueError:

        print("Please try again, it must be a number between 0 and 1")
        user_input()

有人可以编辑这个或向我解释如何添加另一个规则以及
ValueError
,以便它只接受1到0之间的数字吗?

捕获异常时,不能在同一行中检查值。 试试这个:

def user_input():
    while True:
        initial_input = input("Please enter a number between 1 and 0")
        if initial_input.isnumeric() and (0.0 <= float(initial_input) <= 1.0):
            return float(initial_input)
        print("Please try again, it must be a number between 0 and 1")
def user_input():
尽管如此:
初始输入=输入(“请输入一个介于1和0之间的数字”)

如果initial_input.isnumeric()和(0.0,则无法在捕获异常时检查同一行中的值。 试试这个:

def user_input():
    while True:
        initial_input = input("Please enter a number between 1 and 0")
        if initial_input.isnumeric() and (0.0 <= float(initial_input) <= 1.0):
            return float(initial_input)
        print("Please try again, it must be a number between 0 and 1")
def user_input():
尽管如此:
初始输入=输入(“请输入一个介于1和0之间的数字”)
如果初始_input.isnumeric()和(0.0