next up previous
Next: About this document ... Up: A Second Python Program: Previous: "Adding" strings

Making Python interpret the input: eval

So far we have seen that the function input treats what you type as a string of characters. But sometimes it is useful to have Python interpret the characters as Python constants. For example, when you input your age, we saw that the result was treated as a string of characters. To get Python to treat it as an integer constant, you would do this:




age = eval(input("Enter your age "))

Python's eval function interprets the character string and determines its type automatically. So if you enter the number 25, the eval function converts it to an integer, assigns it to the variable age and gives age the type int. Then you can do arithmetic with it without further conversion.

The order of operations in this example is found by reading from inside-to outside the parentheses and from right to left. First, the input function reads a string of characters from the keyboard, then the eval function operates on that string, and, finally, the result is stored in the variable age.

If you use the same procedure to enter your name, as in




name = eval(input("Enter your name "))

then Python expects that what you type follows its rules for a Python string constant. So when you input your name, you must enclose what you type with single or double quotes. Then Python treats it as a string and name becomes a string variable.

Try changing your code so both your name and age are read using the eval function to process the result of the input function. Then see what happens if you print your age in five years by simply using addition as in age + 5.


next up previous
Next: About this document ... Up: A Second Python Program: Previous: "Adding" strings
Carleton DeTar 2017-08-10