Reputation: 474
Here's my for
loop that does stuff:
for x in range(0, 100):
currentRate10 = srall10[x].current_rate
startRate10 = srall10[x].start_rate
lessons10 = srall10[x].sr_completed
if currentRate10 is not None and startRate10 is not None:
gain10 = currentRate10 - startRate10
else:
gain10 = 0
rateavg = gain10 / lessons10
rateavg
returns 1.42
. Seems accurate to me. However, when I put a variable in place of the 100
OR anything above 100
, I get 0
returned back. So if I change 100
to 101
, rateavg
returns 0
. If I put in a variable that contains 143
, I still get 0
.
srall10
contains a list
srall10 = DBSession.query(Summary).filter(Summary.sid == 6933).filter(
Summary.sr_completed.between(1, 10)).all()
There are 143
entries, this was found by the exact same query except with count()
at the end instead of all()
Any ideas?
Upvotes: 0
Views: 111
Reputation: 2275
You get rateavg
as the result of the last item. and range(0, 100)
will not iterate over all elements. Instead iterate directly over the list.
l = []
for s in srall10:
if s.current_rate is not None and s.start_rate is not None:
gain10 = s.current_rate - s.start_rate
else:
gain10 = 0
l.append(gain10 / lessons10) # average if each item
# total average
total_average = sum(l) / len(l)
Upvotes: 2
Reputation: 50970
Python will always return an integer value for the division of two integers, so when a division operation in Python returns 0 and you were expecting a number, the first thing to check is whether both the dividend and the divisor are integers. If so, and if the dividend is less than the divisor, then you'll get 0 instead of a float between 0 and 1.
You can avoid this with:
rateavg = (gain10 * 1.0) / lessons10
I don't know if this is your problem since there's not enough information in the question to determine the type of the values in your lists, but it's often my problem when division unexpectedly returns 0.
Upvotes: 0