关于python:未定义变量”result”

Variable “result” is not defined

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
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

原代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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))


您需要使用return关键字在函数外部使用变量结果。

1
2
3
4
5
def performOperation(numberOne, numberTwo):
    ...
    return result

result = performOperation(numberOne, numberTwo)

变量'result'只在函数的作用域中定义。如果要打印出来,则应将PerformOperation函数的结果赋给结果变量。另外,确保在函数中实际返回了一些内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
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