Next / Previous / Contents / TCC Help System / NM Tech homepage

20.20. input(): Read an expression from the user

This function asks the user to type something, then evaluates it as a Python expression. Here is the general form:

input([prompt])

If you supply a string as the optional prompt argument, that string will be written to the user before the input is read.

In any case, the result is the value of the expression. Of course, if the user types something that isn't a valid Python expression, the function will raise an exception.

>>> input()
2+2
4
>>> print "The answer was '{0}'.".format(input())
2+3*4
The answer was '14'.
>>> print "The answer was '{0}'.".format(input("Type an expression:"))
Type an expression:2+3*4
The answer was '14'.
>>> print input()
1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero