+ 1
explanation
hello all, can anyone explain why the output is 28. I thought the output would be the sum of all the characters in list. list = [4,6,8,3,7,9,5,3,] sum = 0 for a in range(len(list)): sum = sum + a print(sum)
3 Respostas
+ 9
There is no need to use range in the for loop here. And you should try to avoid using names like list for a variable name.
lst = [4,6,8,3,7,9,5,3,]
sum = 0
for a in lst:
sum = sum + a
print(sum)
+ 3
a is always the number in the range, and you're adding that.
Write:
sum = sum + list[a]
+ 3
len(list) returns the length of the list. Just simply use for a in list and it will be good.
Btw, for loop in Python is like foreach loop in other languages