Feb-18-2018, 05:29 PM
Think of it like this.
Error:>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 305, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
So in a list like this in a loop.lst = [0, 0, 0, 0, 1, 2, 0, 0, 4]We want to to skip all 0 which give ZeroDivisionError and get to get result where there is no error.
>>> 1 / 1 1.0This can bye files or what ever that generate a error,that's want to be bypassed.
def foo(): lst = [0, 0, 0, 0, 1, 2, 0, 0, 4,] l = [] for i in lst: try: n = 1 / i l.append(n) except ZeroDivisionError: return('Cannot divide by 0') return l print(foo())
Output:Cannot divide by 0
def foo(): lst = [0, 0, 0, 0, 1, 2, 0, 0, 4,] l = [] for i in lst: try: n = 1 / i l.append(n) except ZeroDivisionError: pass return l print(foo())
Output:[1.0, 0.5, 0.25]