Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling - how to handle invalid datatype in user input?

Tags:

python

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?

like image 734
Srini Avatar asked Feb 07 '15 02:02

Srini


People also ask

Can try-except be used to catch invalid keyboard input?

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.

Which method throws an exception for not a number and infinite input values?

isNaN() method This method returns true if the value represented by this object is NaN; false otherwise.


2 Answers

  1. Get input from user by raw_input() (Python 2) or input() (Python 3).
  2. Type of variable name is string, so we have to use string method to valid user enter string.
  3. Use 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
like image 131
Vivek Sable Avatar answered Oct 11 '22 01:10

Vivek Sable


You can write an if statement like this:

if not entry.isalpha():
   print ("Invalid entry!")
like image 38
Fede Couti Avatar answered Oct 11 '22 02:10

Fede Couti