Search code examples
pythonlistfor-loopdivide-by-zero

Dividing by Zero while Generating List in Python


I am trying to make a list of percents generated by User-Input into the table. The table is working and has inputs from e1 - e24. The problem is that some of the inputs are zero, and thus my program stops when it runs into the error.

Here is the user input (generated by Tkinter):

enter image description here

The first column is e1-e12 and the second is e13-e24. Thus, I divide e1 by e13 to divide along the row.

Here is the list:

   Percents= [("%.2f" % (int(e1.get())/int(e13.get()))), ("%.2f" % (int(e2.get())/int(e14.get()))),\
   ("%.2f" % (int(e3.get())/int(e15.get()))),("%.2f" % (int(e4.get())/int(e16.get()))),\
   ("%.2f" % (int(e5.get())/int(e17.get()))),("%.2f" % (int(e6.get())/int(e18.get()))),\
   ("%.2f" % (int(e7.get())/int(e19.get()))),("%.2f" % (int(e8.get())/int(e20.get()))),\
   ("%.2f" % (int(e9.get())/int(e21.get()))),("%.2f" % (int(e10.get())/int(e22.get()))),\
   ("%.2f" % (int(e11.get())/int(e23.get()))),("%.2f" % (int(e12.get())/int(e24.get())))]

When it gets to the zeroes, though, it gets stuck. I tried try: and except ZeroDivisionError: but since it inevitably runs into the error it doesn't store anything from the Percent List. I was hoping to make the list by a loop but trying e(i) is different than e1 so I got roadblocked by that issue.

for i in range(1, 12):
    if 5 > i:
    Percents.append("%.2f" % (int(e(i).get())/int(e(i+12).get())))

EDIT: Based on an answer below, I attempted:

def calc_percent(foo,bar):   
   try:
       return ("%.2f" % (int(foo.get())/int(bar.get())))
   except ZeroDivisionError:
       return "0"

Percents = [calc_percent(e1,e13),calc_percent(e2,e14)]
print Percents

I get TclError: invalid command name ".286005808" So I put Percents and print Percents inside the def and get TypeError: calc_percent() takes exactly 2 arguments (0 given)


Solution

  • It will be a better idea to create 2 lists of entries (one for each column), then do:

    my_list = [e_left.get() / e_right.get() for e_left, e_right in zip(left_entries_list, right_entries_list) if e_right.get() != 0 else y]
    

    y is whatever value you decide to use in case the right value is 0.

    EDIT: Apparently you can use if in list comprehensions but if...else won't work. So you can use map instead. Here is a simplified example:

    a = [1, 2, 3, 4]
    b = [1, 1, 0, 1]
    
    # -1 or other `default value` you wish to use
    my_list = map(lambda x, y: x / y if y != 0 else -1, a, b)
    
    print my_list
    >> [1.0, 2.0, -1, 4.0]