# Try statement hands in, does not work?

Hello,

i stuck , i am sure it is a small detail:

``````numbers = IN
divisor = IN

def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
return (0.00)
else:
return(result)
finally:
return(result)

result = []

for i in divide(numbers,divisor):
result.append(i)

OUT = result
``````

How can i handle errors?

KR

Andreas

Have you tried declaring local variable `result` before assigning something?

``````numbers = IN
divisor = IN

def divide(x, y):
result = 0
try:
result = x / y
except ZeroDivisionError:
return (0.00)
else:
return(result)
finally:
return(result)

result = []

for i in divide(numbers,divisor):
result.append(i)

OUT = result
``````
3 Likes
``````numbers = IN
divisor = IN
result = []

def divide(x, y):
try:
global result
result = x / y
except ZeroDivisionError:
return (0.00)
else:
return(result)
finally:
return(result)

final = []

for i in divide(numbers,divisor):
final.append(i)

OUT = final
``````

how do i divine that?

i also noticed your two input are list. So you may need to add a loop.

``````divideResult = [divide(num, div) for num, div in zip(numbers, divisor)]
for i in divideResult :
final.append(i)
OUT  = final
``````

or

``````final = [divide(num, div) for num, div in zip(numbers, divisor)]
OUT = final
``````
2 Likes

zip! that was it! but there is still one detail, it gives a emty least insteat of 0.00

``````	except ZeroDivisionError:
return (0.00)
``````
``````	except ZeroDivisionError:
result = 0
return result
``````

Can you try this way?

2 Likes

0.00 is better to remain double. when i use 0 it is a integer hmm… i think i can do it better but doable option is using `float()`.

``````except ZeroDivisionError:
result = 0
return float(result)
``````

or

``````except ZeroDivisionError:
result = 0.00
return result
``````

I don’t know whether it is going to work or not cus i am away from my PC but try and let me know.

2 Likes

float is not working with 0… …0.00 works! @dylim

1 Like

That’s how I’d do it.
Notice they’re all doubles even if they’re not showing the decimal point.

1 Like

The super class of ZeroDivisionError is ArithmeticError. This exception raised when the second argument of a division or modulo operation is zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws “ZeroDivisionError: division by zero” error if the result is infinite number. While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate.

``````try:
z = x / y
except ZeroDivisionError:
z = 0
``````

Or check before you do the division:

``````if y == 0:
z = 0
else:
z = x / y
``````

The latter can be reduced to:

`z = 0 if y == 0 else (x / y)`

1 Like