2017-04-03 74 views
0

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

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

'result'不在全局范围内。它在'performOperation'范围内。如果你想得到'result',从你的函数中返回并在你调用该函数时存储返回的值, – MooingRawr

+0

如果你正在试图制作一个计算器,为什么不直接使用exec函数呢?示例:while True:exec('print('+ input('Enter the equation:')+')') - Exec是一个运行以字符串形式存在的代码的函数。该示例使用“9 + 9”等输入,然后将解决方案输出到您的计算中。 – Josh

回答

1

你需要使用return关键字使用变量结果的功能

def performOperation(numberOne, numberTwo): 
    ... 
    return result 

result = performOperation(numberOne, numberTwo) 
0

变量“结果”之外只被定义你的功能的范围。如果你想打印出来,你应该将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