Python 基于传递给函数的变量的决策
我是一名新的Python3用户,需要以某种方式完成以下工作。我不知道如何根据变量Python 基于传递给函数的变量的决策,python,function,Python,Function,我是一名新的Python3用户,需要以某种方式完成以下工作。我不知道如何根据变量操作正确执行操作 def arith(x, y, operation): if operation == add: return x + y if operation == mult: return x * y print(arith(x = 2, y = 3, operation = add)) print(arith(x = 2, y = 3, operation
操作
正确执行操作
def arith(x, y, operation):
if operation == add:
return x + y
if operation == mult:
return x * y
print(arith(x = 2, y = 3, operation = add))
print(arith(x = 2, y = 3, operation = mult))
我收到以下错误消息:
打印(算术(x=2,y=3,运算=add))
名称错误:未定义名称“添加”
我已经看过了,但找不到这类问题的答案
def arith(x, y, operation):
if operation == 'add':
return x + y
if operation == 'mult':
return x * y
arith(2, 3, 'add')
arith(2, 3, 'mult')
问题是没有定义add和mult。通过将它们分别用引号“add”和“mult”括起来,可以将它们定义为字符串
有关详细信息,请参阅字符串文档。您希望“添加”是什么?它应该是字符串吗?使用“add”而不是“add”