英文:
Why does my postfix program in Python not work?
问题
我有这段代码来计算后缀表达式中的内容:
operator = ["+", "-", "*", "/", "^"]
operand=[]
exp=input("Please enter something in postfix notation:")
expression = exp.split(' ')
for ele in expression:
if(ele not in operator):
operand.append(ele)
else:
number1=eval(operand.pop())
number2=eval(operand.pop())
if(ele=="+"):
answer=number2+number1
elif(ele=="-"):
answer=number2-number1
elif(ele=="*"):
answer=number2*number1
elif(ele=="/"):
answer=number2/number1
elif(ele=="^"):
answer=number2**number1
operand.append(str(answer))
print("answer =", operand[0])
我可以输入一些内容进行计算,但然后它会显示NameError: name 'answer' is not defined,并指向operand.append(str(answer))行。我该如何修复这个问题,其余部分是否正常?
谢谢任何帮助!
英文:
I have this code to calculate something given in postfix notation:
operator = ["+", "-", "*", "/", "^"]
operand=[]
exp=input("Please enter something in postfix notation:")
expression = exp.split(' ')
for ele in expression:
if(ele not in operator):
operand.append(ele)
else:
number1=eval(operand.pop())
number2=eval(operand.pop())
if(ele=="+"):
answer=number2+number1
elif(ele=="-"):
answer=number2-number1
elif(ele=="*"):
answer=number2*number1
elif(ele=="/"):
answer=number2/number1
elif(ele=="^"):
answer=number2**number1
operand.append(str(answer))
print("answer =", operand[0])
I can enter something to calculate but then it says NameError: name 'answer' is not defined and refers to the operand.append(str(answer)) line. How do I fix that and is the rest fine?
Thank you for any help!
答案1
得分: 1
你的缩进在else块中不正确,这会在每个元素处附加错误的答案值。
operator = ["+", "-", "*", "/", "^"]
operand = []
exp = input("请输入后缀表达式:")
expression = exp.split(' ')
for ele in expression:
if ele not in operator:
operand.append(ele)
else:
number1 = eval(operand.pop())
number2 = eval(operand.pop())
if ele == "+":
answer = number2 + number1
elif ele == "-":
answer = number2 - number1
elif ele == "*":
answer = number2 * number1
elif ele == "/":
answer = number2 / number1
elif ele == "^":
answer = number2 ** number1
operand.append(str(answer))
print("答案 =", operand[0])
以下是更新后的代码。
以下是输出:
请输入后缀表达式:15 5 +
答案 = 20
英文:
Your indentation isn't correct in your else block, which is appending garbage value for the answer at every element.
operator = ["+", "-", "*", "/", "^"]
operand=[]
exp=input("Please enter something in postfix notation:")
expression = exp.split(' ')
for ele in expression:
if(ele not in operator):
operand.append(ele)
else:
number1=eval(operand.pop())
number2=eval(operand.pop())
if(ele=="+"):
answer=number2+number1
elif(ele=="-"):
answer=number2-number1
elif(ele=="*"):
answer=number2*number1
elif(ele=="/"):
answer=number2/number1
elif(ele=="^"):
answer=number2**number1
operand.append(str(answer))
print("answer =", operand[0])
Here's your updated code.
Following is the output:
Please enter something in postfix notation:15 5 +
answer = 20
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论