gpt4 book ai didi

python - 如何同时检查输入是否为数字和范围? Python

转载 作者:行者123 更新时间:2023-11-28 18:20:51 24 4
gpt4 key购买 nike

我想检查我的输入是否同时是数字和范围(1,3)并重复输入直到我得到满意的答案。现在我以这种方式这样做,但代码并不干净和简单......有没有更好的方法来做到这一点?也许用 while 循环?

def get_main_menu_choice():
ask = True
while ask:
try:
number = int(input('Chose an option from menu: '))
while number not in range(1, 3):
number = int(input('Please pick a number from the list: '))
ask = False
except: # just catch the exceptions you know!
print('Enter a number from the list')
return number

将不胜感激。

最佳答案

我想这样做最干净的方法是删除双循环。但是,如果您同时需要循环和错误处理,那么无论如何您最终都会得到一些复杂的代码。我个人会选择:

def get_main_menu_choice():
while True:
try:
number = int(input('Chose an option from menu: '))
if 0 < number < 3:
return number
except (ValueError, TypeError):
pass

关于python - 如何同时检查输入是否为数字和范围? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45202238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com