我正在尝试使用以下脚本编写一个简单的计算器:
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 returnoperation
frominp()
, and pass it as a parameter tomath()
.例: