[Tutor] input() and raw_input()
John Precedo
johnp@reportlab.com
Thu, 8 Feb 2001 17:02:57 -0000
Henry [porterh@m-net.arbornet.org] asked:
> 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 see your problem. Have a look at this snippet:
>>> x = input ("give me a number: ")
give me a number: 10
>>> print x
10
>>> print type(x)
<type 'int'>
>>> y = raw_input("give me another number: ")
give me another number: 20
>>> print y
20
>>> print type(y)
<type 'string'>
>>> z = int(y)
>>> print z
20
>>> print type(z)
<type 'int'>
>>>
So, input is returning an integer, but raw input is
returning a string.
You could do this to fix it - replace the first line with
these two:
selection = raw_input('Enter number: ')
selection = int(selection)
The 'int' bit converts your string into an integer so you
can do tests on it.
It _should_ work.
--
John Precedo (johnp@reportlab.com)
Junior Developer, Reportlab, Inc