简体   繁体   中英

Good Practice to check user input

The normal approach, I found online, to ensure the correct type of user input is as the code below.

if not isinstance(amount, int):
    raise ValueError("Please enter an integer as amount.")
else:
    return amount

I wrapped the above code in a function and then called the function with the parameter. I personally prefer to put it in a function. Is it an acceptable variation to check the user input? (in a class)

def __init__(self, amount):

    def check_userinput(amount):
        if not isinstance(amount, int):
            raise ValueError("Please enter an integer as amount.")
        else:
            return amount

    self.amount = check_userinput(amount)

The user inputs will probably be str , not int unless you convert them first. To see if that's doable, the Pythonic way might be to try and see, ie

def is_int_like(x):
    try:
        int(x)
        return True
    except ValueError:
        return False

You could go either way, community wise Python works with EAFP principle. (Easier to ask for forgiveness than permission.) I would go ahead and cast it, and just catch the exception so you can add the custom message.

In regards to your code, it would look something like:

try:
    self.amount = int(amount)
except ValueError as e:
    raise ValueError("Please enter an integer as amount.")

User input from input will always be a str . Therefore, you can just do this:

def get_checked_input():
    while True:
        user_input = input('Please enter a number.')
        if user_input.isdigit():
            return user_input

        else:
            print('Something other than a number was entered.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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