如何同时检查输入是数字还是在范围内?Python

2024-04-23 23:08:45 发布

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

我想检查我的输入是否是数字和范围(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

感谢你的帮助。在


Tags: the方法答案代码fromnumberinputget
3条回答

看看这个行不行

def get_main_menu_choice():
    while True:
        try:
            number = int(input("choose an option from the menu: "))
            if number not in range(1,3):
                number = int(input("please pick a number from list: "))
        except IndexError:
            number = int(input("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

如果您的整数介于1和2之间(或在范围(1,3))中,则表示它是数字!在

while not (number in range(1, 3)):

我可以简化为:

^{pr2}$

或者

while not 0 < number < 3:

您的代码的简化版本只在int(input())附近尝试过:

def get_main_menu_choice():
    number = 0
    while number not in range(1, 3):
        try:
            number = int(input('Please pick a number from the list: '))
        except: # just catch the exceptions you know!
            continue # or print a message such as print("Bad choice. Try again...")
    return number

相关问题 更多 >