Reputation: 223
please be kind with your answers I have been coding now for 10 days. I am having trouble with performing loops in my code, but I am fairly certain this is because I am getting a traceback.
I parse an xml file obtained from a url, using the following code:
pattern4 = re.compile('title=\'Naps posted: (.*) Winners:')
pattern5 = re.compile('Winners: (.*)\'><img src=')
for row in xmlload1['rows']:
cell = row["cell"]
##### defining the Keys (key is the area from which data is pulled in the XML) for use in the pattern finding/regex
user_delimiter = cell['username']
selection_delimiter = cell['race_horse']
##### the use of the float here is to make sure the result of the strike rate calculations returns as a decimal, otherwise python 2 rounds to the nearest integer!
user_numberofselections = float(re.findall(pattern4, user_delimiter)[0])
user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])
strikeratecalc1 = user_numberofwinners/user_numberofselections
strikeratecalc2 = strikeratecalc1*100
##### Printing the results of the code at hand
print "number of selections = ",user_numberofselections
print "number of winners = ",user_numberofwinners
print "Strike rate = ",strikeratecalc2,"%"
print ""
getData()
This code with the rest of the code returns:
number of selections = 112.0
number of winners = 21.0
Strike rate = 18.75 %
number of selections = 146.0
number of winners = 21.0
Strike rate = 14.3835616438 %
number of selections = 163.0
number of winners = 55.0
Strike rate = 33.7423312883 %
Now the results of this xmlload suggest that there is only three users to parse however there is a 4th whos data would read
number of selections = 0
number of winners = 0
Strike rate = 0
for my purposes it is not necessary to pull in user stat's for those with no track record, how do i make the code either skip users with 0 selections or at least make it so that the division by zero error doesn't affect the ability of the code to run in a loop?
Kind regards!
Upvotes: 0
Views: 9787
Reputation: 7821
Just use a continue
when you find a 0.
user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])
# if the number of winners is 0, go to the next row to avoid division by 0
if user_numberofwinners == 0.0 : continue;
Upvotes: 6