0
name=input("What is your name?:  ")

while name != int:
    print("Input is Invalid.  Please enter a name.")
    name = input("Enter name:  ")

This code works when an integer is entered. However when I type in a string it recognizes it as invalid as well. How can I fix this problem?

3 Answers 3

3

Your while condition is always satisfied - int is an object of class type, while name is a string. These two will never be equal.

You could use regular expressions to validate your input. E.g. if names cannot contain numerical characters:

import re
name = input("What is your name?:  ")

while re.search('\d', name):
  print("Input is Invalid.  Please enter a name.")
  name = input("Enter name:  ")
Sign up to request clarification or add additional context in comments.

Comments

0

Consider this.

>>> n = input("your name ")
your name 5 #5 is my input
>>> n !=int
True
>>> type(n)
<class 'str'>
>>> n = input("your name ")
your name chimp
>>> n != int
True
>>> type(n)
<class 'str'>

No matter what you enter - will always be string. So it will always evaluate true and you'll see "Input is Invalid. Please enter a name." message until you break the program.

So, you need to check input value does not contain numbers (of course there some other symbols, but let make things easier for now). But we also noticed that even if a user inputs a number, it is processed as string (5 -> "5"). So let us make a list of numbers as string.

>>> a = [str(i) for i in range(10)]
>>> a
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> name = input("what is your name? ")
what is your name? 3rwin
>>> any(i in a for i in name)
True
>>> name = input("what is your name? ")
what is your name? ernesto
>>> any(i in a for i in name)
False
>>> not any(i in a for i in name)
True

just change your while expression as while not any(i in a for i in name) and everything will be ok. then you can extend a (unwanted characters) as you wish and get more accurate results.

Comments

0

What about this?

name = input("What is your name?:  ")

while not name.isalpha():
    print("Input is Invalid.  Please enter a name.")
    name = input("Enter name:  ")

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.