Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

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) == 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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content