Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren+ 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)
11 Antworten
+ 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)
+ 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)
+ 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
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
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