0

I am trying to validate the user input to check if it is a string or number.If it is a number I want to say 'Please input letters' This is the code i tried out

while True:
    try:
        member = str(input('Are you a child or adult member? '))
    except TypeError:
        print('Please input letters')
And3r50n 1
  • 337
  • 1
  • 5
  • 21
  • 3
    Possible duplicate of [How to check if string input is a number?](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – the.salman.a Mar 25 '18 at 07:58
  • Possible duplicate of [Data type validation in python - Strings](https://stackoverflow.com/questions/44011545/data-type-validation-in-python-strings) – Mayur Mar 25 '18 at 08:00
  • 1
    Digits are just as valid in strings as letters, so there's no way you're going to get a `TypeError` here. If you want to check the contents of a string, there are lots of methods on the string type that you can see with `help(str)` in the interactive interpreter or the documentation, including things like `isalpha` and `isdigit`. – abarnert Mar 25 '18 at 08:03
  • You just need `int()` instead of `str()`. – Artemis Mar 25 '18 at 08:41

1 Answers1

1

In Python3, the input() function always returns a string, even if the string entirely consists of digits, it still returns it as a string, e.g: "123".

So, trying to catch an error when converting it to a string will never work as it is always already a string!

The correct way to do this would be to use .isdigit() to check if it is an integer.

while True:
    member = input('Are you a child or adult member? ');
    if member.isdigit():
        print('Please input letters')
    else:
        break

However, if you want to validate properly, you should not allow the user to enter any string, you should restrict them to "child" or "adult":

while True:
    member = input('Are you a child or adult member? ');
    if member not in ('child', 'adult'):
        print('Please enter a valid entry.')
    else:
        break
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54