只能调用一个函数的返回值,而不可以调用其中的其他指令吗?

我正在尝试使用以下脚本编写一个简单的计算器:

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))

它通过先要求2个数字输入,然后要求运算来工作。 我试图让它要求2个数字输入之间的操作。 为此,我需要以下内容:

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()?

在Windows 10上运行Python 3.8.3

评论
菊花残
菊花残

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))

例:

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
点赞
评论