如何使函数调用其他 4 个函数来执行 4 个算术运算(加法、减法、乘法和除法)



我发现很难调用其他函数。例如,如果用户输入calculate(2,3,"+")我想调用addition()函数并显示结果。如果用户输入calculate(2,3,"-")我想调用subtraction()函数。这是我的代码

def addition():
if string == "+":
    a = num1 + num2
    print("addition was performed on the two numbers ", num1, ' and ', num2)
    return a

def subtraction():
if string == "-":
    s = num1 - num2
    print("subtraction was performed on the two numbers ", num1, ' and ', num2)
    return s

def multiplication():
if string == "*":
    t = num1 * num2
    print("multiplication was performed on the two numbers ", num1, ' and ', num2)
    return t

def division():
if string == "/":
    d = num1 / num2
    print("division was performed on the two numbers ", num1, ' and ', num2)
    return d

def calculate(num1, num2, string):
str(string)

我希望calculate(num1, num2, string)调用其他函数。顺便说一句,如果我的代码让你感到困惑,我很抱歉

**谢谢,多曼迪尼奥。当我在这里粘贴代码时,如果空格被搞砸了,欢呼**

这是使用字典和运算符模块的另一种方法。

import operator
d = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    }
def calculate(num1, num2, string):
    return d[string](num1, num2)
首先,

你有错误的意图。 如果指令应该在 4 个空格之后,则 if 下的所有指令都应该在 8 个空格之后。所有变量都应该可供使用它们的函数访问,因此加法、减法、乘法和除法需要 num1 和 num2 作为参数。str(string) 什么都不做,因为字符串变量的类型是 str。您必须在计算函数中调用这 4 个函数,具体取决于字符串的值。

其次,如果 str 的检查值应该在计算函数中,而不是在例如加法函数中。如果字符串不是"+",则加法函数将返回 None。

def addition(num1, num2):
    a = num1 + num2
    print("addition was performed on the two numbers ", num1, ' and ', num2)
    return a

def subtraction(num1, num2):
    s = num1 - num2
    print("subtraction was performed on the two numbers ", num1, ' and ', num2)
    return s

def multiplication(num1, num2):
    t = num1 * num2
    print("multiplication was performed on the two numbers ", num1, ' and ', num2)
    return t

def division(num1, num2):
    d = num1 / num2
    print("division was performed on the two numbers ", num1, ' and ', num2)
    return d

def calculate(num1, num2, string):
    result = None
    if string == '+':
        result = addition(num1, num2)
    elif string == '-':
        result = subtraction(num1, num2)
    elif string == '*':
        result = multiplication(num1, num2)
    elif string == '/':
        result = division(num1, num2)
    print('Result is ' + str(result))

最新更新