1

I would like to automate the division by 0. Some of variable extracted from db might equal 0 and division would give an error. Should I make an exception In DB or in python code?

3 Answers3

1

This is better:

for b in varb:
    try:
        v = 1/b # or any code that raises division by zero
        print(v)
    except ZeroDivisionError:
        print(0)
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • should I put it in every formula? I tried to put return 0 instead of print (0). But it does not work. how to make it just return 0 instead of printing? –  Feb 24 '20 at 07:28
  • @Gunel I think I will need more code form you to answer that question. can you post and share your desire a bit clear? – Mehrdad Pedramfar Feb 24 '20 at 07:30
  • I want the code be applicable to other formulas so that the code if detects 0 it returns 0 rather than an error. As I understood I need to write your code for each formula? is that correct ? –  Feb 24 '20 at 07:34
1
data  = [1,2,0,3,4,0,0,5]
updated_data = [0 if i==0 else 1/i for i in data]
print(updated_data)

Here, data is simple data you required. I have used list comprehension to create new list with 1/x or 0.

It will check if i =0, it will execute instruction written before if that is 0. Else, it will execute else part that is 1/i.

It creates new list and assign to the variable declare.

Parth Parekh
  • 119
  • 1
  • 6
0

you can also use continue statement with if else statement to avoid the divisible by zero error like this way

m=10

b=7

varb=[var1,var2,var3,var4,var5,var6,var7,var8]
for b in varb:
    if b==0: 
      print ("Not Devisible by zero")
      continue
    else:
      print (m/b)
M Hamza Razzaq
  • 432
  • 2
  • 7
  • 15