"Whole numbers between 15 (inclusive) and 100 (inclusive))" means that are all the numbers on this list: 15, 16, 17, 18... up to 100.
"Arithmetic mean" of a set of numbers is simply the sum of those numbers divided by the amount of numbers.
For example, if it were "arithmetic mean of the integers between 2 (inclusive) and 4 (inclusive)", it would be the arithmetic mean of (2, 3, 4), which would be the sum of them (2 + 3 + 4 = 9) divided by the quantity of numbers (3), then the mean would be 9 / 3 = 3.
In your case, the numbers are (15, 16, 17, .... 99, 100) and the number number is 86 (yes, you can count, there are 85).
Anyway, to do this in Python, you can use a range
from 15 to 101 (since a range
includes the first number, but does not include the last).
Then you can use sum
to calculate the sum of the numbers, and len
to get the amount of numbers, and then just divide one by the other:
numeros = range(15, 101)
media = sum(numeros) / len(numeros)
print(media) # 57.5
With this you get the average, which is 57.5.
But since this is an exercise, I believe the intention is that you use ties like the for
or while
, then you can do this "manually" (although the above solution is much more succinct and simple):
soma = 0
quantidade = 0
for i in range(15, 101):
soma += i
quantidade += 1
media = soma / quantidade
print(media)
Or still not using the range
:
soma = 0
quantidade = 0
i = 15
while i <= 100:
soma += i
quantidade += 1
i += 1
media = soma / quantidade
print(media)
Note that I only calculate the average at the end (after the for
/while
), only after the loop is that I have the sum and the amount of numbers.
Very cool, but the list conversion is unnecessary - both
sum()
how muchlen()
work with objects of the typerange
more efficiently without need "materialize" the list.– nosklo
@nosklo had forgotten that detail. I updated the reply, thank you!
– hkotsubo