Being new to programming, I am trying to input name which is a string input. If I enter anything other than a string, error should be displayed as invalid input type. How can this be achieved?
You can catch that exception using the try-except block. The try block lets you test a block of code for errors, the except block handles the errors and the finally block lets you execute code regardless of errors.
isNaN() method This method returns true if the value represented by this object is NaN; false otherwise.
raw_input()
(Python 2) or input()
(Python 3).Type
of variable name
is string
, so we have to use string method to valid user enter string. isalpha()
string method to check user entered string is valid or not.code:
name = raw_input("Enter your Last Name:")
if not name.isalpha():
print "Enter only alpha values."
output:
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:123
Enter only alpha values.
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek 123
Enter only alpha values.
Other string methods to check user string is integer or alpha or both
>>> "123".isalnum()
True
>>> "123a".isalnum()
True
>>> "123abc".isalnum()
True
>>> "123abc".isalpha()
False
>>> "123abc".isdigit()
False
>>> "123".isdigit()
True
>>> "123".isalpha()
False
By Type conversion and Exception method
e.g. for invalid input:
>>> a = "123a"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
User string is not number
e.g. for valid input:
>>> a = "123"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
>>> print a
123
>>> type(a)
<type 'int'>
>>>
Ask user to enter value again and again if user enter invalid value.
code:
while 1:
try:
age = int(raw_input("what is your age?: "))
break
except ValueError:
print "Enter only digit."
continue
print "age:", age
output:
vivek@vivek:~/Desktop/stackoverflow$ python 5.py
what is your age?: test
Enter only digit.
what is your age?: 123test
Enter only digit.
what is your age?: 24
age: 24
You can write an if statement like this:
if not entry.isalpha():
print ("Invalid entry!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With