[Tutor] dealing with user input whose value I don't know

Steve Willoughby steve at alchemy.com
Thu Oct 2 19:49:11 CEST 2008


On Fri, Oct 03, 2008 at 01:38:48AM +0800, David wrote:
> Does that mean input() is obsolete (after all, Zelle's book is not the 
> freshest on the shelf)? Or do they have different uses?

Depends on how you look at it.

input() automatically evaluates whatever the user types as a Python
expression and returns the result.  So if they type 5, the integer
5 is returned.  For your program, that's probably what you want, and
has the advantage of letting you type something like 2+3 so your user
can let Python evaluate math expressions.

On the other hand, you'd think that you could ask a user for a text
response using input():
   name = input("What is your name? ")
   print "Hello, ", name

But if they just type the answer, Python will crash with an error
because it's expecting a legal Python expression there (so a 
string value would have to be typed in quotes).

However, raw_input() will just return the characters the user typed
without doing anything to them.  Great for string values, but this
means to get an integer result you'll have to pass that into the
int() constructor function.

IIRC Python 3.0 will actually make input() do what raw_input() today
does, because this is confusing to people as it stands now.

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list