[Tutor] input() and raw_input()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 8 Feb 2001 09:17:36 -0800 (PST)

On Thu, 8 Feb 2001, Henry wrote:

> I'm taking a number as input from the user and attempting to do a
> comparison on it:
> selection = raw_input('Enter number: ')
> if selection < 3:
> 	print 'Invalid number'
> else:
> 	print 'OK number'
> The comparison works using input() but doesn't when using
> raw_input() -- it always drops to the 'else:'.  
> I was trying to use raw_input() because it was recommended in the
> documentation as a safer way to get user input.  What exactly is
> raw_input() doing to the input?  Can I still do my comparison using
> raw_input()?  Are there some general rules on when to use
> input() vs. raw_input()?

About input():  We can think of input() as if we were directly entering
something in the interpreter prompt --- Python will try to evaluate
whatever you type, into something appropriate.  So if we type


in response to an input(), Python will return back an integer.  However,
if we tried something like:


(unquoted), it will break unless a 'hello' variable had been defined in
our program previously.  If it helps, you can think of input() as a pure
text substitution into the program.  Given the file:

    mynum = input("Number? ")

whatever we type will replace the 'input("Number? ")'.  (This isn't quite
what Python does, but it's close.)

raw_input(), on the other hand, will always return back strings.  The
problem that you're running into is that strings need to be squeezed into
integer form before you do the numerical comparison:

    if int(selection) < 3:

is one possible way to fix it.

Another way is this:

    selection = int(raw_input('Enter number: '))

which is nicer if you want to always think of selection as a number.

By the way, the reason it doesn't like

    selection < 3

is because string-to-string comparison is also available to us.  If both
the left side and right sides are strings, like this:

    'hello' < 'world'

then Python will do an alphabetic comparison.  However, because the left
side of your comparison uses a string and your right side a number, Python
gets very confused... *grin*  So it just stops until you make the types
match up.

Hope this helps!