Search code examples
pythonfunctionreturncalculator

Can only the return of a function be called instead of other instructions in it?


I am trying to program a simple calculator using the following script:

def math(num_1, num_2):
    global operation
    if operation == '+':
        x = num_1 + num_2
    elif operation == '-':
        x = num_1 - num_2
    elif operation == '*':
        x = num_1 * num_2
    elif operation == '/':
        x = num_1 / num_2
    return float(x)

def opp():
    print("To add, press '+'")
    print("To add, press '-'")
    print("To multiply, press '*'")
    print("To divide, press '/'")

def inp():
    num_1 = input("Enter first number: ")
    num_2 = input("Enter second number: ")
    return float(num_1), float(num_2)

a, b = inp()

opp()
operation = input()

result = math(a, b)

print("The result is: " + str(result))

It works by asking for the 2 numerical inputs first and then the operation. I am trying to have it ask for the operation in between the 2 numerical inputs. For that, I want the following:

def opp():
    print("To add, press '+'")
    print("To add, press '-'")
    print("To multiply, press '*'")
    print("To divide, press '/'")
    operation = input()
    return operation

def inp():
    num_1 = input("Enter first number: ")
    opp()
    num_2 = input("Enter second number: ")
    return float(num_1), float(num_2)

And then I want to input the output of opp() into math(), but when I try to replace the operation variable in math() with opp(), then the entire opp() function executes, including its print statements.

Is there a way to input the return of opp() into math()?

running Python 3.8.3 on Windows 10


Solution

  • Don't use global - that's a bad way to move data around inside a program. Instead, just return operation from inp(), and pass it as a parameter to math().

    def math(operation, num_1, num_2):
        if operation == '+':
            x = num_1 + num_2
        elif operation == '-':
            x = num_1 - num_2
        elif operation == '*':
            x = num_1 * num_2
        elif operation == '/':
            x = num_1 / num_2
        return float(x)
    
    def opp():
        print("To add, press '+'")
        print("To add, press '-'")
        print("To multiply, press '*'")
        print("To divide, press '/'")
        operation = input()
        return operation
    
    def inp():
        num_1 = input("Enter first number: ")
        operation = opp()
        num_2 = input("Enter second number: ")
        return operation, float(num_1), float(num_2)
    
    operation, a, b = inp()
    
    result = math(operation, a, b)
    
    print("The result is: " + str(result))
    

    Example:

    Enter first number: 2
    To add, press '+'
    To add, press '-'
    To multiply, press '*'
    To divide, press '/'
    *
    Enter second number: 3
    The result is: 6.0