基本计算器无法使用我的功能

时间:2019-12-23 19:34:01

标签: python python-3.x

所以我已经在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

即使我输入“ add”作为操作,它始终显示“错误:未知操作”。 有什么想法为什么不起作用?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

var2save对于askAndStore函数而言是本地的。要从函数外部访问它,必须return。稍作修改:

def calculate(num1,num2,op):
    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:
        raise ValueError("Unknown operation " + op) 
    return output

n1 = input("What is the first number?")
n2 = input("What is the second number?")
op = input("What is the operation?")
output = calculate(n1, n2, op)
print(output)


答案 2 :(得分:-1)

我猜您是一个C程序吗?或类似的东西,在python中,您不能将过去的值重新分配给这样的函数,当您将参数传递给函数时,它只是指向此PyObject的指针,并且您不能更改此指针地址,只能是值(重新分配变量对此将永远无效)

如您所见,您可以在这些情况下使用return语句

def calculate(num1,num2,op):
    output = None
    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")
    return output

# PROGRAM MAIN

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

看看复杂的对象确实可以这样工作,例如list

def f(l):
    l.append(1)
l = []
f(l)
print(l) # [1]

但是您不能这样重新分配指针:

def f(l):
    l = [1]
l = []
f(l)
print(l) # []