Reputation: 1
I am trying to use a for loop to get an average for each week and for the month in python:
sum = 0
sumA = 0
sumB = 0
sumC = 0
sumD = 0
week1 = (35,38,30,34,27,40,39)
week2 = (35,38,30,34,27,40,39)
week3 = (35,38,30,34,27,40,39)
week4 = (35,38,30,34,27,40,39)
for x in (week1):
sum = sum + week1[x]
avg1 = (sum + week1[x]) / 7
for y in (week2):
sumA = sumA + week2[y]
avg2 = (sumA + week2[y]) / 7
for z in (week3):
sumB = sumB + week3[z]
avg3 = (sumB + week3[z]) / 7
for k in (week4):
sumC = sumC + week4[k]
avg4 = (sumC + week4[k]) / 7
sumD = sum + sumA + sumB + sumC
avg = (sum + sumA + sumB + sumC) / 28
that is it but its not correct. can i get some help please
Upvotes: 0
Views: 1208
Reputation: 116097
You don't need these loops. Here's a quick example:
>>> week1 = (35,38,30,34,27,40,39)
>>> average1 = sum(week1) / len(week1)
>>> average1
34
As in the comments:
The above example (in Python 2.x) needs one part cast to float if you want 'true' division (e.g. 34.71).
In Python 3.x the single /
division defaults to 'true' division so the above snippet would be correct (although with a different resulting value for average1
).
Upvotes: 4
Reputation: 38412
>>> def ave(numbers):
... return sum(numbers) / len(numbers)
...
>>> week1 = (35,38,30,34,27,40,39)
>>> week2 = (35,38,30,34,27,40,39)
>>> week3 = (35,38,30,34,27,40,39)
>>> week4 = (35,38,30,34,27,40,39)
>>> ave(week1)
34
>>> ave(week1+week2+week3+week4)
34
>>>
from __future__ import division
if you want a non-truncated result
Upvotes: 1
Reputation: 363487
There are several problems here. First, for x in lst
yields the elements of lst
, not the indices. Second, you add in the elements twice, once when updating sum
, then again when updating avg
. Just compute avg
outside the list. Third, divide by a float
instead of an int
to prevent truncation:
for x in (week1):
sum = sum + x
avg1 = sum / 7.
Upvotes: 3
Reputation: 601391
Assuming you are using Python 2.x, the /
operator for two integers uses integer divsion, i. e. the result of the division is rounded down to the next integer. Try it in the interactive interpreter:
>>> 5/3
1
To get the correct floating point division, either use
from __future__ import division
or convert one of the operands to float
first
avg = float(sum + sumA + sumB + sumC) / 28
Upvotes: 5