August 2019
Beginner
482 pages
12h 56m
English
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) == answerTrue
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, ...