未定义变量“结果”

时间:2017-04-03 20:45:06

标签: python

我一直在研究这段代码,每次运行它都会说结果没有定义。

Error: Traceback (most recent call last):
  File "/Users/Bubba/Documents/Jamison's School Work/Programming/Python scripts/Ch9Lab2.py", line 24, in <module>
    print(str(numberOne) + " " + operation + " " + str(numberTwo) + " = " + str(result))
NameError: name 'result' is not defined

原始代码:

def performOperation(numberOne, numberTwo):
    if operation == "+":
        result = numberOne + numberTwo
    if operation == "-":
        result = numberOne - numberTwo
    if operation == "*":
        result = numberOne * numberTwo
    if operation == "/":
        result = numberOne / numberTwo

numberOne = int(input("Enter the first number: "))
numberTwo = int(input("Enter the second number: "))
operation = input("Enter an operator (+ - * /): ")

performOperation(numberOne, numberTwo)

print(str(numberOne) + " " + operation + " " + str(numberTwo) + " = " + str(result))

2 个答案:

答案 0 :(得分:1)

您需要使用return关键字在函数

之外使用变量结果
def performOperation(numberOne, numberTwo):
    ...
    return result

result = performOperation(numberOne, numberTwo)

答案 1 :(得分:0)

变量'result'仅在函数范围内定义。如果要将其打印出来,则应将performOperation函数的结果分配给结果变量。另外,请确保您实际上在函数中返回了一些内容。

def performOperation(numberOne, numberTwo):
    if operation == "+":
        result = numberOne + numberTwo
    if operation == "-":
        result = numberOne - numberTwo
    if operation == "*":
        result = numberOne * numberTwo
    if operation == "/":
        result = numberOne / numberTwo
    return result

result = performOperation(numberOne, numberTwo)
print str(result) # will print the result