input() and raw_input() in Python

by Amit


Consider the following Python interactive console session with the input() function:

>>> input()
1
1
>>> input()
'f00 bar'
'f00 bar'
>>> input()
'f00
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
    'f00
       ^
SyntaxError: EOL while scanning string literal
>>> input()
1 67
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
    1 67
       ^
SyntaxError: unexpected EOF while parsing

>>> input()
'1 67'
'1 67'

And now, the raw_input() function:

>>> raw_input()
1
'1'
>>> raw_input()
2 56
'2 56'
>>> raw_input()
'f00 bar
"'f00 bar"
>>> raw_input()
f00bar
'f00bar'
>>> 

And finally:

>>> input()
5+4
9
>>> raw_input()
5+4
'5+4'

As mentioned in the documentation for the input() function (Python 2), the eval() function is called on the input using input(). Hence, the input should be syntactically valid Python. With raw_input(), the input is returned as a string and hence can be anything that your program wants to handle. In Python 3, raw_input() has been renamed to input() and raw_input doesn’t exist.

Python 3.2.3 (default, Jun  8 2012, 05:36:09) 
[GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input

>>> raw_input
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'raw_input' is not defined
>>> input()
'f00bar
"'f00bar"
>>> 

Simulating c like scanf()

You can simulate C like scanf() behavior using raw_input() and split(). For example ( In Python 2):

>>> x,y,z=raw_input('Enter the co-ordinates:: ').split()
Enter the co-ordinates:: 1 5 6
>>> x
'1'
>>> y
'5'
>>> z
'6'
>>> int(x)
1
>>> int(y)
5
>>> int(z)
6

Since the input is considered a string, we have to do explicit type conversion if we want to treat the input as integers, for example.

Advertisements