[Tutor] pausing + raw_input vs input

Michael Janssen Janssen@rz.uni-frankfurt.de
Sat Jan 4 13:33:01 2003

On Sat, 4 Jan 2003, mike O wrote:
> If you just wanted a number, couldn't you use input instead of raw_input?
> I'm not entirely sure on these two functions, other than that I thought
> input was for an integer, and raw_input was for a string, is that right?

half right ;-)

raw_input(prompt) returns always strings. input(prompt) returns that type
of object the expert user created at the prompt. The main difference is
not string vs any-object but expert user vs nonexpert user!

compare doc/lib/built-in-funcs.html#l2h-30

          Equivalent to eval(raw_input(prompt)). Warning: This function
          is not safe from user errors! It expects a valid Python
          expression as input; if the input is not syntactically valid, a
          SyntaxError will be raised. Other exceptions may be raised if
          there is an error during evaluation. (On the other hand,
          sometimes this is exactly what you need when writing a quick
          script for expert use.)

You can take input() to get an integer, but the user need only to
type a letter and your programm is down. Better use raw_input() and "try"
to convert the users input with int():

while 1:
   user_input = raw_input("No: ")
           number = int(user_input)
           break # stop while-loop
       except ValueError:
           print "that was no number: " + user_input
           # implicite remain in while loop

try-except is explained in the tutorial: doc/tut/node10.html. You will
need to learn this anyway (in case not already done :-)


Example for input (at interactive interpreter):

>>> j = input("hey, experts, give me an object! ")
hey, experts, give me an object! [2, 3, 4, 5]
>>> type(j)
<type 'list'>
>>> j
[2, 3, 4, 5]