简体   繁体   English

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

[英]How to check if input is digit and in range at the same time? Python

I would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer.我想同时检查我的输入是否为数字并且在范围(1,3)内,然后重复输入直到得到满意的答案。 Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this?现在我以这种方式这样做,但是代码并不干净和容易......有没有更好的方法来做到这一点? Maybe with while loop?也许用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

Will be grateful for help.将不胜感激的帮助。

I guess the most clean way of doing this would be to remove the double loops.我想最干净的方法是删除双循环。 But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what.但是,如果您同时需要循环和错误处理,无论如何最终都会得到一些令人费解的代码。 I'd personally go for:我个人会去:

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
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())
``

If your integer number is between 1 and 2 (or it is in range(1,3)) it already means it is a digit !如果您的整数介于 1 和 2 之间(或在范围(1,3)内),则表示它是一个数字

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

which I would simplify to:我会简化为:

while number < 1 or number > 2:

or

while not 0 < number < 3:

A simplified version of your code has try-except around the int(input()) only:您的代码的简化版本仅在int(input())周围具有 try-except :

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

see if this works看看这是否有效

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

If you need to do validation against non-numbers as well you'll have to add a few steps:如果您还需要对非数字进行验证,则必须添加几个步骤:

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]))

Then you can reuse it for any menu by passing a list of valid choices, eg get_main_menu_choice([1, 2]) or get_main_menu_choice(list(range(1, 3))) .然后您可以通过传递有效选项列表将其重用于任何菜单,例如get_main_menu_choice([1, 2])get_main_menu_choice(list(range(1, 3)))

I would write it like this:我会这样写:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM