Skip to main content

5.13) Input And Output


You’ve already seen that you can get a program to output some values for the user to read with the print statement, like this:

>>> a = 3
>>> print 'a is', a
a is 3

There are various ways to input data to a program. The most basic way is to directly ask for the user to type it in:

>>> x=raw_input('enter a value for x:')
enter a value for x:34.3
>>> x
'34.3'

The prompt or program will hold until you type something in and press Return. The result of raw_input() is always a string. Note: in Python 3, raw_input has been replaced with the function input(). Check the compatibility of your code.

You can convert your input string to a number by using either the float() or int() functions.

>>> float(x)

Alternatively the eval function will return an object of whatever type was input, whether it is a float, int or string.

>>> eval('35.6')
35.6