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))
'result'不在全局範圍內。它在'performOperation'範圍內。如果你想得到'result',從你的函數中返回並在你調用該函數時存儲返回的值, – MooingRawr
如果你正在試圖製作一個計算器,爲什麼不直接使用exec函數呢?示例:while True:exec('print('+ input('Enter the equation:')+')') - Exec是一個運行以字符串形式存在的代碼的函數。該示例使用「9 + 9」等輸入,然後將解決方案輸出到您的計算中。 – Josh