eval() 函数

eval() 函数用来执行一个字符串表达式,并返回表达式的值。

语法

以下是 eval() 方法的语法:

1
eval(expression[, globals[, locals]])

举例

1
2
>>> eval('pow(2,2)')
4

参数

  • expression —— 表达式。
  • globals —— 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
  • locals —— 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

返回值

返回表达式计算结果

语法糖

传统方法,字符无法参与运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
num1, num2, operator = (input("请输入数字及运算符:").split())


def calculate(num1, num2, operator):
num1, num2 = float(num1), float(num2)
if operator == '+':
return (num1 + num2)
elif operator == '-':
return (num1 - num2)
elif operator == '*':
return (num1 * num2)
elif operator == '/':
if num2 == 0:
return ("除数不能为零")
else:
return (num1 / num2)
else:
return ("参数错误")


print(calculate(num1, num2, operator))

把字符串转换为表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
num1, num2, operator = (input("请输入数字及运算符:").split())
operator_list = ['+', '-', '*', '/']


def calculate(num1, num2, operator):
if operator == '/' and num2 == 0:
return ("除数不能为零")
elif operator in operator_list and num1.isdigit() and num2.isdigit():
return eval(num1 + operator + num2)
else:
return ("参数错误")


print(calculate(num1, num2, operator))