1

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)
Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • Given that most *user input* will be a string anyway, `int(amount)` would accomplish pretty much the same thing…!? – deceze Apr 17 '19 at 09:13
  • maybe you can rename your function name to `is_int()` and create the corresponding function for different types. – navyad Apr 17 '19 at 09:15
  • 4
    Python programmers usually go for [duck typing](https://docs.python.org/3/glossary.html#term-duck-typing) and don't even bother to check. If there's a problem, sooner or later TypeError would be thrown anyways, and if the function returns successfully, then it's a good thing. – T Tse Apr 17 '19 at 09:18

3 Answers3

3

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, i.e.

def is_int_like(x):
    try:
        int(x)
        return True
    except ValueError:
        return False
Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
2

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.")
Chayemor
  • 3,577
  • 4
  • 31
  • 54
1

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.')
gmds
  • 19,325
  • 4
  • 32
  • 58