如何同时检查输入是否为数字和范围?蟒蛇

时间:2017-07-19 22:44:18

标签: python python-3.x loops input

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

非常感谢您的帮助。

6 个答案:

答案 0 :(得分:1)

我想最干净的方法是删除双循环。但是如果你想要循环和错误处理,你最终会得到一些有问题的代码,无论如何。我亲自去找:

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 :(得分:1)

def user_number():

    # variable initial
    number = 'Wrong'
    range1 = range(0,10)
    within_range = False

    while number.isdigit() == False or within_range == False:
        number = input("Please enter a number (0-10): ")

        # Digit check
        if number.isdigit() == False:
            print("Sorry that is not a digit!")

        # Range check
        if number.isdigit() == True:
            if int(number) in range1:
                within_range = True
            else:
                within_range = False

    return int(number)

print(user_number())
``

答案 2 :(得分:0)

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

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

我将简化为:

while number < 1 or number > 2:

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

答案 3 :(得分:0)

看看是否有效

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

答案 4 :(得分:0)

如果你需要对非数字进行验证,你还需要添加几个步骤:

def get_main_menu_choice(choices):
    while True:
        try:
            number = int(input('Chose an option from menu: '))
            if number in choices:
                return number
            else:
                raise ValueError
        except (TypeError, ValueError):
            print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))

然后,您可以通过传递有效选项列表(例如,有效选项)来重复使用它。 get_main_menu_choice([1, 2])get_main_menu_choice(list(range(1, 3)))

答案 5 :(得分:0)

我会这样写:

def get_main_menu_choice(prompt=None, start=1, end=3):
    """Returns a menu option.

    Args:
        prompt (str): the prompt to display to the user
        start (int): the first menu item
        end (int): the last menu item

    Returns:
        int: the menu option selected
    """
    prompt = prompt or 'Chose an option from menu: '
    ask = True
    while ask is True:
        number = input(prompt)
        ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
   return int(number)