Please am currently having a problem with how to get sum of number in a list using while and for loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please am currently having a problem with how to get sum of number in a list using while and for loops

Problem

23rd May 2022, 4:54 PM
Sheriff Oladimeji
Sheriff Oladimeji - avatar
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?
23rd May 2022, 5:17 PM
Justice
Justice - avatar
+ 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
23rd May 2022, 6:13 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
Emerson Prado ok, thanks for the tip
25th May 2022, 1:09 PM
Sheriff Oladimeji
Sheriff Oladimeji - avatar
0
What is your code?
23rd May 2022, 5:04 PM
Justice
Justice - avatar
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.
24th May 2022, 2:47 AM
Emerson Prado
Emerson Prado - avatar
- 2
Justice Sum = 0 X = 10 while x > o: sum += x X -= 1 Print (sum)
23rd May 2022, 5:10 PM
Sheriff Oladimeji
Sheriff Oladimeji - avatar