[Tutor] Confusion about name in the target list of for loop
Richard Damon
Richard at Damon-Family.org
Fri Aug 28 08:35:11 EDT 2020
On 8/28/20 7:18 AM, Manprit Singh wrote:
> Dear sir ,
> Consider a problem of finding the average of numbers(1,2, 3, 4, 5). if this
> is solved using the for loop in this way, is it correct ?
>
> s = 0
> for i in range(1, 6):
> s = s + i
> print(s / i)
> 3.0
>
> As we know, the for loop in the above example will produce the sum of
> numbers,
> 1, 2, 3, 4, 5. Now as the last value of variable i (which is a variable in
> the target list of for loop) is equal to the number of loops executed, it
> can be used to find the average ?. s divided by i will give the average .
>
> My question is, the way i have used variable in the target list, just after
> the completion of for loop, is its appropriate use or not.
>
> Regards
> Manprit Singh
For a general average operation, it wouldn't be good as you are assuming
that the last number equals the number of points, which isn't generally
true (ranges beginning with 1 and stepping by 1 are one major special
case where it works)
--
Richard Damon
More information about the Tutor
mailing list