How to handle zero by zero exception in python?

8th Oct 2019, 6:12 AM
Divyansh Upadhyay
Divyansh Upadhyay - avatar
5 Answers
+ 2
Divyansh Upadhyay Please review the Exception chapter, the example there uses division by zero case for the code sample. https://www.sololearn.com/learn/Python/2441/
8th Oct 2019, 7:59 AM
+ 2
Sometimes you can also just evade the problem with a condition. Let's say you want to divide every number in a list by 2. numbers = [5, 7, 0, 3, 2] for i in range(5): if numbers[i]: numbers[i] /= 2
8th Oct 2019, 8:39 AM
HonFu - avatar
+ 1
scr4pp3r You should try to be as specific as possible when catching an error so that other errors don't get caught accidentally. That is why Williams code is preferable to yours.
8th Oct 2019, 11:26 AM
Thoq! - avatar
try: x = 0/0 print x except Exception as e: print e run this code n you will get it
8th Oct 2019, 7:47 AM
m8riix - avatar
user = int(input("Type you calculation")) try: user/0 except ZeroDivisionError: print("Can not divide by zeor")
8th Oct 2019, 9:22 AM
William M
William M - avatar