eval 函数:
作用:
把一个字符串当成一个表达式来执行,返回表达式执行后的结果
格式:
eval(source, globals=None, locals=None)
示列:
x = 100
y = 200
while True:
s = input("请输入表达式 >>> ")
if not s:
break
v = eval(s)
print(v)
示列2
x = 100
y = 200
v = eval(‘x + y’)
print(v) # 300
dict_local = {‘x’:1, ‘y’: 2}
v = eval(‘x + y’, None, dict_local)
print(v) # 3
dict_global = {‘x’:10, ‘y’: 20}
v = eval(‘x + y’, dict_global, {‘y’:2})
print(v) # 12
v = eval(‘x + y’, None, {‘y’:2})
print(v) # 12
v = eval(‘x + y’, {‘x’:1})
print(v) # 1 + y 出错