Python mapping display exception

The following example is very simple. I want to execute map () with a function that can throw an exception. This will be more clear with an example:

number_list = range(-2,8) def one_divide_by(n): return 1/n try: for number, divide in zip(number_list, map(one_divide_by, number_list)): print("%d : %f" % (number, divide)) except ZeroDivisionError: # Execution is stopped. I want to continue mapping pass 

When I execute this code, I get:

 -2 : -0.500000 -1 : -1.000000 

This is because of 0 on my list. I do not want to remove this 0 (because in the real case, I cannot know first if I get an Exception). Do you know how to continue displaying after an exception ?

+5
source share
2 answers

you could catch an exception in your function (and not in a for loop) and return None (or whatever you choose) if a ZeroDivisionError raised:

 def one_divide_by(n): try: return 1/n except ZeroDivisionError: return None 

if you choose return None , you need to adapt the format string; None cannot be formatted with %f .

other values ​​that you could return (and that would be compatible with your string formatting): float('inf') (or float('-inf') depending on the numerator) or float('nan') - " infinity "or" not a number. "

here you will find some warnings about using float('inf') .

+3
source

You can move the try/except block inside the function. Example -

 def one_divide_by(n): try: return 1/n except ZeroDivisionError: return 0 #or some other default value. 

And then call this normally, without a try / except block -

 for number, divide in zip(number_list, map(one_divide_by, number_list)): print("%d : %f" % (number, divide)) 
+2
source

Source: https://habr.com/ru/post/1232263/


All Articles