持续要求输入,直到输入满足多个条件

时间:2020-02-16 16:29:43

标签: python while-loop

我希望我的函数能够不断要求用户提供输入,直到它满足所有条件。我的功能如下:

def PromptNumber(Text, Positive, Integer):

    while True:                                                                 #Keep asking for value until input is valid

        Input = input(Text)

        try:                                                                    #Check if input is float
            Input = float(Input)
        except:
            print('You must enter a valid number.')
            continue

        if Positive:

            if Input < 0:                                                       #Check if input is negative      
                print('You must enter a valid number (positive).')
                continue

        else:
            print("Positive else")

        if Integer:

            try:                                                                #Check if input is integer
                Input = int(Input)
            except ValueError:
                print('You must enter a valid number (integer).')
                continue
            break

        else:
            print("Integer else")
            break

    return Input

其中的参数是:

  • 文字:我要问的问题的字符串
  • Positive:定义输入是否必须为正数的布尔值
  • 整数:定义输入是否必须为整数的布尔值

这对于大多数问题都可以,但是当使用PromptNumber(“ hi”,True,True)这样的2个True布尔值(正整数)调用该函数时,它将继续询问输入值是否为负-如预期的那样。但只要它们为正,它仍将接受非整数值。

0 个答案:

没有答案