+ 4
Given a list of numbers, calculate their sum using a for loop. Output the sum after the loop
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for n in x: sum+=n print(sum)
13 Respostas
+ 12
joanna Godfrey ,
i have no idea what problem you have , but this is your code with the correct indentation: (and it works!)
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in x:
sum+=n
print(sum)
to avoid trouble like this, it is recommend to use 4 spaces for indentation.
+ 8
You also should put the print statement at the same indent level as the for loop line. That way it only prints once
joanna Godfrey read it ^^^
+ 3
Try this
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in x:
sum+=n
print(sum)
make sure print (sum) do not to start on the same line with the sum += n
like so,
___________________
for n in x:
sum+=n
print(sum)
+ 3
حوراء
i can understand your question, the code is just confusing.
sum=0 is not using the sum() function, but declaring a variable with the name `sum`. if we do so, the sum() function will be shadowed and can not be used within the current scope.
we mention this kind of coding frequently, but it still happens again and again...
+ 2
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in x: #taking list values to n iteratively.
sum=sum+n #adding n value to sum
print(sum) #its outside of loop so prints only once after loop completion.
joanna Godfrey
if you work with indexes like x[n] then use
for n in range(len(x) ) : instead of for n in x:
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in range(len(x)):
sum=sum+x[n]
print(sum)
+ 2
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
S=0
for cal in x:
S+=cal
print(S)
===
Make sure you put Print and For Statment in the same level
+ 1
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in x:
sum+=n
print(sum)
Why do you have to enter "sum = 0"?
And where did "n" come from?
Thx
Addendum: I at least understand that there is nothing special about the characters of "sum" or "n" in particular. . .
piglet = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
bacon = 0
for oink in piglet:
bacon+=oink
print(bacon)
+ 1
#Given a list of numbers, calculate their sum using a for loop. Output the sum after the loop
num = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum=0
for x in num:
sum+=x
print(sum)
+ 1
Can someone explain this to me?
Well I know why we chose(for)
But why did we add the function sum=0?
0
Thank you
0
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum = 0
for n in x:
sum=sum+x[n]
print(sum)
Still not working
0
Still stocked..
- 1
jw