Python:如果代码的答案是一个超出范围的整数,如何让代码再次询问相同的问题?我的例子如下:

2024-06-26 03:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何让这个问题一遍又一遍地要求输入,直到用户得到5到25之间的有效答案?你知道吗

newGen = int(input("Input number of new generations to model (should be between 5 and 25\n)"))

Tags: ofto答案用户numbernewinputmodel
2条回答

您需要捕获ValueError并循环它。你知道吗

newGen = None
while newGen is None or (newGen < 5 or newGen > 25):
     try:
         newGen = int(input("Input number of new generations to model (should be between 5 and 25\n)"))
     except ValueError:
         pass
newGen = 0
while newGen not in range(5, 26):
    newGen = int(input("Input number of new generations to model (should be between 5 and 25\n)"))

相关问题 更多 >