Reputation: 11
I'm very new to programming in Python and most of the answers I have searched for are more complex versions of the script than I am looking for. I have made very simplistic calculator:
loop = 1
choice = 0
while loop == 1:
print 'Python Calculator!\n'
print 'Mathematical Operation:\n'
print '1) Addition'
print '2) Subtraction'
print '3) Multiplication'
print '4) Division'
print '5) Quit Python Calculator'
choice = input('Choose your operation: ')
if choice == 1:
add1 = input('Add:')
add2 = input('to: ')
print add1, '+', add2, '=', add1 + add2
elif choice == 2:
sub2 = input('Subtract: ')
sub1 = input('from: ')
print sub1, '-', sub2, '=', sub1-sub2
elif choice == 3:
mul1 = input('Multiply: ')
mul2 = input('by: ')
print mul1, '*', mul2, '=', mul1 * mul2
elif choice == 4:
div1 = input('Divide: ')
div2 = input('by: ')
print div1, '/', div2, '=', div1/div2
elif choice == 5:
print 'GOODBYE'
exit()
Now I am wondering how I can divide by zero and return the print "Divide by 0 Error" rather than what it does now, which is exit the program. The error I get when dividing by 0 is:
Traceback (most recent call last):
File "./calculator.py", line 32, in <module>
print div1, '/', div2, '=', div1/div2 ZeroDivisionError:
integer division or modulo by zero
Upvotes: 0
Views: 4548
Reputation: 566
Change the print statement in division as :
print div1, '/', div2, '=', div1/(div2 or not div2)
this will make sure whenever your div2 ==0, not div2 will become 1 and will give you numerator back. not div2 will always be false when div2 is other than 0 so need not worry about any other case.
Upvotes: 0
Reputation: 1035
Use a condition on div2 that returns the string "Divide by 0 Error" rather than handling the exception - that way is much simpler.
if div2 == 0:
print "Divide by 0 Error"
else:
print div1, '/', div2, '=', div1/div2
The reason why you want to avoid the try/catch is because there no need to add the exception catching since your program is simple. The overhead isn't worth it, and your program will crash every time the user types '0'
Upvotes: 0
Reputation: 78536
Put your division operation in a try-except
block like this:
try:
# put division here div1/div2
pass
except ZeroDivisionError:
print "Divide by 0 Error"
Upvotes: 1
Reputation: 106
try/except :)
try:
print div1, '/', div2, '=', div1/div2
except ZeroDivisionError:
print div1, '/', div2, ':', 'Division by zero!'
Upvotes: 0