Reputation: 11
My values can't be divided by zero. However, I would still like to run the other values. Is there a solution to this? I have done some research and I know that people uses np.errstate and np.where, but I am not sure how to apply that to my code.
diesel_electric = [0,0,0,0,0,0,0,6,17,23,22,22,21]
electric = [1,1,1,1,2,2,3,0,1,1,12,314,560]
year = [2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]
fuels = input('Please select a fuel type: ')
if fuels in ['1']:
for i in range(len(electric)):
per = (electric[i]-electric[i-1])/electric[i-1]*100
if per>= 6:
print(f"{year[i]} {electric[i]}")
elif fuels in ['2']:
for i in range(len(diesel_electric)):
per = (diesel_electric[i]-diesel_electric[i-1])/diesel_electric[i-1]*100
if per>= 6:
print(f"{year[i]} {diesel_electric[i]}")
Upvotes: 0
Views: 568
Reputation: 11
The problem seems to be in the diesel_electric
list, so you can just check if it is zero before doing the computation:
for i in range(len(diesel_electric)):
if diesel_electric[i-1] != 0:
per = (diesel_electric[i]-diesel_electric[i-1])/diesel_electric[i-1]*100
if per>= 6:
print(f"{year[i]} {diesel_electric[i]}")
else:
continue
It seems, though, that you'll find an aerror anyway because when i==0
, then i-1 = -1
, which isn't a valid index. So I'd say you start the loop from i = 1
in both loops:
for i in range(1,len(diesel_electric)):
if diesel_electric[i-1] != 0:
per = (diesel_electric[i]-diesel_electric[i-1])/diesel_electric[i-1]*100
if per>= 6:
print(f"{year[i]} {diesel_electric[i]}")
else:
continue
Upvotes: 1
Reputation: 118
you could use try:
and except:
to ignore or catch errors such as these, or just make some if and else statments to trace division by zero and skipping it
here is an example with try:
diesel_electric = [0,0,0,0,0,0,0,6,17,23,22,22,21]
electric = [1,1,1,1,2,2,3,0,1,1,12,314,560]
year = [2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]
fuels = input('Please select a fuel type: ')
if fuels in ['1']:
for i in range(len(electric)):
try:
per = (electric[i]-electric[i-1])/electric[i-1]*100
if per>= 6:
print(f"{year[i]} {electric[i]}")
except:
pass
elif fuels in ['2']:
for i in range(len(diesel_electric)):
try:
per = (diesel_electric[i]-diesel_electric[i-1])/diesel_electric[i-1]*100
if per>= 6:
print(f"{year[i]} {diesel_electric[i]}")
except:
pass
Upvotes: 0
Reputation: 406
Either you can apply a "if" condition to remove all zero values from processing. or you can take your code and insert it in a try and except block. that will not return any error for dividing by zero.
try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero!"
Upvotes: 2
Reputation: 861
You can use a try/except statement with the ZeroDivisionError:
try:
# some calculation
1 / 0
except ZeroDivisionError:
pass
Upvotes: 1