PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to avoid failing with Decimal function when 0/0 occurs?

 August 07, 2022     decimal, linux, python     No comments   

Issue

I have a Python 2.7 script and it uses two lists and divides the numbers to each other then creates a new list with the results and it is working fine but it errors on the line below anytime the script has to divide 0 / 0, which happens sometimes depending on the state of my current servers. Is there any way to avoid this?

complist =[a, b, c]
totallist=[d, e, f]

percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)] 

I am getting error:

    MacBook-Pro-3$ python dailyReport.py 
    Traceback (most recent call last):
  File "dailyReport.py", line 67, in <module>
    percentlist = [Decimal(l) / Decimal(t) * 100 for l,t in zip(complist, totallist)] 
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 1321, in __truediv__
    return context._raise_error(DivisionUndefined, '0 / 0')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3873, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: 0 / 0

Solution

How about

percentlist = [0 if t == 0 else Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]


Answered By - Aguy
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing