[Tutor] A question about input/raw_input

Gregor Lingl glingl@aon.at
Fri, 19 Apr 2002 10:48:06 +0200


From: "Crane, Adam" <ACrane@computer2000.co.uk>
To: <tutor@python.org>


> I was just wondering, what is the difference between the two?  I know that
> 'input' is specifically for numbers, while 'raw_input' is for words and
> numbers (well that's what I've come to understand).
>

That's only half of the truth. In fact raw_input() accepts only strings as
input.
If you need numbers, for instance for some computations to perform with
them,
you have to convert the strings into numbers using the int(), float()
or similar functions.

On the other hand, input() accepts numbers, but not only numbers.
input() accepts every legal Python expression ( and mere numbers are
legal Python exprssions ).

>>> a = input('gimme an expression: ')
gimme an expression: 3
>>> input('gimme an expression: ')
gimme an expression: 3
3
>>> input('gimme an expression: ')
gimme an expression: 3+4
7
>>> input('gimme an expression: ')
gimme an expression: 'Wow!'         # Remark: you need the quotation marks!
'Wow!'
>>> var = input('gimme an expression: ')  # store the result of input()
gimme an expression: 'ok!'
>>> input('gimme an expression: ')
gimme an expression: var                  # !! A variable is also a legal
Python expression
'ok!'
>>> input('gimme an expression: ')
gimme an expression: nonVarName           # but a name without quotation
marks is not
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in ?
    input('gimme an expression: ')
  File "<string>", line 0, in ?
NameError: name 'nonVarName' is not defined      # Sorry!
>>> input('gimme an expression: ')        # Some more examples
gimme an expression: 'Wow' + ' or not Wow!'
'Wow or not Wow!'
>>> 'Wow' * 5
'WowWowWowWowWow'
>>> input('gimme an expression: ')
gimme an expression: [1,2]*3
[1, 2, 1, 2, 1, 2]
>>>

So, shortly, input() is for people who know Python and
who know what they ar going to do.

> But, if 'raw_input' can be used for words and numbers, then why is there
an
> 'input' in the first place?  When writing programs, I often find myself
> using 'raw_input' for numbers, because if I use input, and enter a word,
the
> program brings up an error message.  So I find it a lot easier to just use
> 'raw_input'.

Consequently this is - in my opinion - normally a good strategy.

>
> I'm confused....more than usual I mean...
>

I hope no more ...

Gregor