2017-04-03 51 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