[Tutor] input() and raw_input()

D-Man dsh8290@rit.edu
Thu, 8 Feb 2001 18:28:56 -0500


All the responses given are good, but there is one thing they failed
to mention -- exceptions.  You may not want to bother with them now,
but as you become more experienced you will need to deal with them or
your programs will be very unstable.

Here is an example (when prompted for a number, I will enter invalid
data) :

>>> x = int( raw_input( "Enter a number: " ) )
Enter a number: invalid input
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  ValueError: invalid literal for int(): invalid input

>>> valid_input = 0 # we haven't gotten valid input yet
>>> while not valid_input :
...     try :
...         x = int( raw_input( "Enter an integer: " ) )
...         valid_input = 1
...     except ValueError , err :
...         print "'%s' is not a valid integer." %
...                         err.args[0].split(": ")[1]
... print "The user entered %d" % x
Enter an integer: asdf
'asdf' is not a valid integer.
Enter an integer: ;lkj
';lkj' is not a valid integer.
Enter an integer: 13
The user entered 13


If the int() function doesn't get a string that can be converted to an
integer, it throws a "ValueError" exception.  If you put the call to
int() in a try-except block, you can catch the ValueError exception
and do something about it.  If you don't catch it, your program will
terminate immediately.  

In the except block, I did a little "magic" to put a nice looking
error message together.  The key point I wanted to make is use
try-except once you understand the basics.

HTH,
-D