我希望我的函数能够不断要求用户提供输入,直到它满足所有条件。我的功能如下:
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
其中的参数是:
这对于大多数问题都可以,但是当使用PromptNumber(“ hi”,True,True)这样的2个True布尔值(正整数)调用该函数时,它将继续询问输入值是否为负-如预期的那样。但只要它们为正,它仍将接受非整数值。