Search code examples
pythonpython-3.xreturn

python - return returns None


I wrote a function which gets two numbers and an operation (string) and returns the result of the two numbers with the given operation. For example calculate_matehamatical_expression(5,6,'+') should return 11. I divide the the assignment to little functions, but when I call these little function it always returns None. Can someone explain to me why that happens? This is the Code I wrote:

def mathematical_sum(num1,num2):
    return num1 + num2

def mathematical_difference(num1,num2):
    return num1 - num2

def mathematical_product(num1,num2):
    return num1 * num2

def mathematical_division(num1,num2):
    if num2 != 0:
        return num1 / num2
    else:
        return None

def operation_error(operation):
    if operation != "+" or operation != "-" or operation != "*" or operation != "/":
        return None




def calculate_mathematical_expression(num1,num2,operation):
    if operation == "+":
        mathematical_sum(num1,num2)
    elif operation == "-":
        mathematical_difference(num1,num2)
    elif operation == "*":
        mathematical_product(num1,num2)
    elif operation == "/":
        mathematical_division(num1,num2)
    else:
        operation_error(operation)

Solution

  • You need to return again inside calculate_mathematical_expression, e.g.:

    def calculate_mathematical_expression(num1,num2,operation):
        if operation == "+":
            return mathematical_sum(num1,num2)
    

    The return in mathematical_sum doesn't affect the function it's being called from.