Georgina Cottrell
Georgina Cottrell

Reputation: 13

Validating string inputs

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?

Upvotes: 0

Views: 107

Answers (3)

Xyrus
Xyrus

Reputation: 928

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:  ")

Upvotes: 0

marmeladze
marmeladze

Reputation: 6564

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.

Upvotes: 0

Jan Buchar
Jan Buchar

Reputation: 1322

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:  ")

Upvotes: 3

Related Questions