Home  >  Article  >  Backend Development  >  What is the usage of eval in python

What is the usage of eval in python

coldplay.xixi
coldplay.xixiOriginal
2021-03-02 13:52:39119293browse

Usage of eval in python: Treat the string str as a valid expression to evaluate and return the calculation result. The syntax is [eval(source[, globals[, locals]]) -> value].

What is the usage of eval in python

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer. This method is suitable for all brands of computers.

Usage of eval in python:

Python eval() function function: evaluate the string str as a valid expression and return the calculation result.

Syntax:

eval(source[, globals[, locals]]) -> value

Parameters:

  • source: a Python expression or code object returned by the function compile()

  • globals: Optional. Must be dictionary

  • locals: Optional. Any map object

If the globals parameter is provided, it must be of dictionary type; if the locals parameter is provided, it can be any map object.

Python's global namespace is stored in a dict object called globals(); the local namespace is stored in a dict object called locals(). We can use print (locals()) to view all variable names and variable values ​​​​in the function body.

 x = 1
 y = 1
 num = eval("x+y")
print('num',num)
 
 def g():
     x = 2
    y = 2
    num1 = eval("x+y")
    print('num1',num1)
     num2 =eval("x+y",globals())
     print('num2',num2)
     num3 = eval("x+y",globals(),locals())
     print('num3',num3)
g()
 
num 2
num1 4
num2 2
num3 4

Analysis: num2 is a global variable because it has globals, and the result after execution is 4; num3 has both globals and locals. In this case only, the value of locals is preferred, so the calculation result is 2

Related free learning recommendations: python video tutorial

The above is the detailed content of What is the usage of eval in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn