Description
eval() 函数用来执行一个字符串表达式,并返回表达式的值。
The syntax of eval()
is:
eval(expression, globals=None, locals=None)
Parameters
The eval()
function takes three parameters:
- expression - the string parsed and evaluated as a Python expression
- globals (optional) - a dictionary
- locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.
- expression -- 表达式。
- globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
- locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象
Return Value
The eval() method returns the result evaluated from the expression.
返回表达式计算结果。
Example 1: How eval() works in Python
x = 1
print(eval('x + 1'))
Output
2
Here, the eval()
function evaluates the expression x + 1
and print
is used to display this value.
Example 2: Practical Example to Demonstrate Use of eval()
# Perimeter of Square
def calculatePerimeter(l):
return 4*l
# Area of Square
def calculateArea(l):
return l*l
expression = input("Type a function: ")
for l in range(1, 5):
if (expression == 'calculatePerimeter(l)'):
print("If length is ", l, ", Perimeter = ", eval(expression))
elif (expression == 'calculateArea(l)'):
print("If length is ", l, ", Area = ", eval(expression))
else:
print('Wrong Function')
break
Output
Type a function: calculateArea(l) If length is 1 , Area = 1 If length is 2 , Area = 4 If length is 3 , Area = 9 If length is 4 , Area = 16