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

时间:2017-10-28 23:19:07

标签: python-3.x

我很难调用其他功能。例如,如果用户输入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)调用其他函数。 顺便说一句,我初学者很抱歉,如果我的代码让你感到困惑

**谢谢,domandinho。当我在这里粘贴代码时,if空格搞砸了,欢呼**

2 个答案:

答案 0 :(得分:2)

这是使用字典和operator模块的另一种方式。

import operator

d = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    }

def calculate(num1, num2, string):
    return d[string](num1, num2)

答案 1 :(得分:1)

首先你有错误的意图。如果指令应该在4个空格之后,则if下的所有指令应该在8个空格之后。对于使用它们的函数,所有变量都应该是可访问的,因此加法,减法,乘法和除法需要num1和num2作为参数。 str(string)什么都不做,因为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))