pythonpython-3.xlistpostfix-mta

Why does my postfix program in Python not work?


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!


Solution

  • 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