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