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')
4
  • 3
    Possible duplicate of How to check if string input is a number? Commented Mar 25, 2018 at 7:58
  • Possible duplicate of Data type validation in python - Strings Commented Mar 25, 2018 at 8: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. Commented Mar 25, 2018 at 8:03
  • You just need int() instead of str(). Commented Mar 25, 2018 at 8:41

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.