【问题标题】:how to make a function call other 4 functions to perform 4 arithmetic operation (addition, subtraction, multiplication and division)如何让一个函数调用其他4个函数来执行4个算术运算(加法、减法、乘法和除法)
【发布时间】:2017-10-29 08:02:19
【问题描述】:

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

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

【问题讨论】:

  • 第一件事:修复代码的缩进。

标签: python-3.x


【解决方案1】:

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

import operator

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

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

【讨论】:

    【解决方案2】:

    首先你有错误的意图。 if 指令应该在 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      相关资源
      最近更新 更多