可以用变量来调用函数吗
我有四个子例程来对 2 个数字进行乘法、除法、加法和减法,我将向用户询问。
我未完成的代码是:
def multiply(a, b):
print(f"{a} x {b} = {a*b}")
def divide(a, b):
print(f"{a} ÷ {b} = {a*b}")
num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")
calculation(num1, num2)
但它给出了 TypeError: 'str' object is not callable
是否有必要使用 if 语句,例如:
if calculation == 'multiply':
multiply()
elif calculation == 'divide':
divide()
对于所有四个子例程,或者我可以使用变量计算来替换函数名称。
I have four subroutines to multiply, divide, add and subtract 2 numbers which I will ask the user for.
My unfinished code is:
def multiply(a, b):
print(f"{a} x {b} = {a*b}")
def divide(a, b):
print(f"{a} ÷ {b} = {a*b}")
num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")
calculation(num1, num2)
but it gives TypeError: 'str' object is not callable
Is it necessary to use if statements like:
if calculation == 'multiply':
multiply()
elif calculation == 'divide':
divide()
for all four subroutines or can I use the variable calculation to substitute for the function name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用字典来保存您的函数
,然后访问
funcs[calculation]
。...或者如果您有 DRY 迷恋:
演示:
您还可以访问
globals()
字典,但这不是一个好主意,因为要调用的函数来自用户输入,谁知道是什么奇怪的可调用对象位于
globals()
中。奖励:防止错误输入
用法:
Use a dictionary to hold your functions
and then access
funcs[calculation]
.... or if you have a DRY fetish:
Demo:
You could also access the
globals()
dictbut this is not such a good idea because the function to call comes from user input and who knows what weird callables are in
globals()
.Bonus: safeguarding against bad input
Usage: