The eval function

The eval function takes a string as an argument and attempts to parse and execute it as Python code. This can be used if you get the code from external sources (although this is potentially dangerous from the security standpoint).

Here is an example:

>>> problem = "2 + 2"
>>> answer = int(input(problem + ' = '))
2 + 2 = 4

>>> eval(problem) == answer

True

What is happening here? First, we store the operation "2 + 2" as a string. On the next line, we use that string, concatenating the equals sign, to ask the user for an answer. Once input is received, the value is converted to an integer. Finally, we evaluate this string, as if it was a Python code, and check whether the result matches the typed-in answer. 

Using that approach, you could generate dozens of arithmetic puzzles and create a simple educational game to train math skills, and all without knowing the answers yourself!

In the next section, we'll go meta, talking about functions allowing us to inspect the properties of variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset