首页 > 解决方案 > 基本计算器不适用于我的功能

问题描述

所以我在 Python 3.7 中编写了一个简单的计算器,但它不适用于我的函数。变量“输出”是灰色的,但我不知道为什么。


n1 = 0
n2 = 0
op = 0
res = 0
output = 0

# DEFINING FUNCTIONS

def askAndStore(aasText,var2save):
    print(aasText)
    var2save = input()

def calculate(num1,num2,op,output):
    if op == "add":
        output = float(num1) + float(num2)
    elif op == "sub":
        output = float(num1) - float(num2)
    elif op == "mul":
        output = float(num1) * float(num2)
    elif op == "div":
        output = float(num1) / float(num2)
    else:
        print("Error: Unknown operation")


# PROGRAM MAIN

askAndStore("What is the first number?", n1)
askAndStore("What is the second number?", n2)
askAndStore("What is the operation?", op)
calculate(n1, n2, op, res)
print(res)

我的输出是:


What is the first number?
10
What is the second number?
5
What is the operation?
add
Error: Unknown operation
0

Process finished with exit code 0

它总是显示“错误:未知操作”,即使我输入“添加”作为操作。任何想法为什么它不起作用?

标签: pythonpython-3.x

解决方案


n1 = float(input("What is the first number? "))
n2 = float(input("What is the second number? "))
op = str(input("What is the operation? "))

# DEFINING FUNCTIONS


def calculate(num1, num2, opr):
    if opr == "add":
        output = num1 + num2
    elif opr == "sub":
        output = num1 - num2
    elif opr == "mul":
        output = num1 * num2
    elif opr == "div":
        output = num1 / num2
    else:
        print("Error: Unknown operation")
    return output

print(calculate(n1, n2, op))

推荐阅读