Is there a way to stop everything after an exception?
For example, I'm creating a reverse polish notation calculator (to learn postfix) and I want to make sure "Cannot divide by zero" is printed out if there is a "0" in my string.
I got it to do what I wanted using try/except.
I tried putting in a "break" after my print statement in the exception but that obviously does not help because my final "pop" is outside the loop. And that causes a bunch of traceback error as obviously the "divide by zero" operation was not performed and the list becomes messed up.
Any ideas?
def RPN(ll):
mys = Stack()
for x in ll:
if x == '+':
sum_of_two = mys.new_pop() + mys.new_pop()
mys.push(sum_of_two)
"""mys.print_stack()""" #test addition
elif x == "*":
product = mys.new_pop() * mys.new_pop()
mys.push(product)
"""mys.print_stack()""" #test multiplication
elif x == "-":
subtrahend = mys.new_pop()
minuend = mys.new_pop()
subtrahend
minuend
difference = minuend - subtrahend
mys.push(difference)
"""mys.print_stack()""" #test subtraction
elif x == "/":
divisor = mys.new_pop()
dividend = mys.new_pop()
divisor
dividend
try:
quotient = dividend/divisor
mys.push (quotient)
except ZeroDivisionError:
print "Cannot divide by zero"
"""mys.print_stack()""" #test division
else:
mys.push(int(x))
return mys.new_pop()
example = [3,4,"-",5,"+",6,"*",0,"/"] #test reverse polish calc
print RPN(example)