0
Please am currently having a problem with how to get sum of number in a list using while and for loops
Problem
6 Answers
+ 1
Your original question states a list. Have you creates a variable name for that list and initialized it as empty so you can add the sums?
+ 1
# For loop 1.
l = [10, 5, 6, 9]
res = 0
for i in l:
res += i
print(res)
# For loop 2.
l = [10, 5, 6, 9]
res = 0
for i in range(len(l)):
res += l[i]
print(res)
# While loop 1.
l = [10, 5, 6, 9]
res = i = 0
while i < len(l):
res += l[i]
i += 1
print(res)
# While loop 2.
l = [10, 5, 6, 9]
res = 0
while l:
res += l.pop()
print(res)
# While loop 3.
l = [10, 5, 6, 9]
res = 0
while l:
res += l[0]
l = l[1:]
print(res)
# Both while and for loop (odd one).
l = [10, 5, 6, 9]
res = 0
for i in l:
while i:
res += 1
i -= 1
print(res)
# Another odd one using sum.
l = [10, 5, 6, 9]
for i in l:
pass
else:
print(sum(l)) # do use for loop š¤£
https://code.sololearn.com/cS4DpcJIFJEC/?ref=app
+ 1
Emerson Prado ok, thanks for the tip
0
What is your code?
0
Sheriff Oladimeji 2 things about Python:
1. It's case sensitive. X and x are different names. So are Sum and sum. Style guidelines recommend lower case names for variables. The output function is print, not Print.
2. Indentation is critical. Think on which commands should be inside the while loop, and correct indentation.
One thing about SoloLearn Q&A section:
Your question becomes more viable if you put your code in Code Playground and include a link to it (use + button) inside your question.
- 2
Justice Sum = 0
X = 10
while x > o:
sum += x
X -= 1
Print (sum)