0

so I'm kind of confused by a question I'm being asked which involves preventing division by zero exception not really sure what means. The question is, ask a user for 2 integers and divide them. Prevent the division by zero exception. Display the result.
I'm not sure what it means by prevent division by zero exception and how exactly do I do that? This is my code so far.

a = int(input("Give me an integer of your choice: "))
b = int(input("Give me another integer of your choice: "))
print(a/b)
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
Trainer Red
  • 7
  • 1
  • 4

2 Answers2

1

An "exception" is something that the python kernel raises to let you know it found an error and the code doesn't work. For example, try

print(12/0)

You will get a "traceback" that shows all the exceptions that were handled by python (this is why python is so great, it doesn't just crash your computer when an error happens). In this case the "exception" is called ZeroDivisionError. You can handle the error yourself in a number of different ways; for example, you could prevent python from trying to divide by zero, by checking the inputs first. Let's try:

a = int(input("Give me an integer of your choice: "))
b = int(input("Give me another integer of your choice: "))
if b == 0: 
    print("Sorry, can't divide by zero, this will cause an error.")
else:
    print(a/b)
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
0

Use the build in try exception statement to avoid your script crash.

Reference: https://docs.python.org/3/library/exceptions.html#ZeroDivisionError

a = int(input("Give me an integer of your choice: "))
b = int(input("Give me another integer of your choice: "))
try:
    print(a/b)
except ZeroDivisionError:
    print("Error ZeroDivisionError, try again")
Boying
  • 1,404
  • 13
  • 20
  • I don't the OP was told to handle the exception, but instead prevent the exception. – Bobby Ocean May 07 '20 at 04:22
  • I thought is to supress the crash @BobbyOcean, if using checking if b==0, it's not worth to ask here maybe... – Boying May 07 '20 at 04:43
  • Agreed that computationally try/except is more memory efficient and better; especially if we think that the error won't happen that often. However, it was pretty clear it was a learning exercise for the OP, and I don't think the OP as gotten to try/except yet. – Bobby Ocean May 07 '20 at 04:53