+ 6

Who can explain this question ??

for loops allow you to easily iterate through lists. Given a list of numbers, output their sum. Sample Input 1 3 7 5 Sample Output 16 What is missing that did not write: https://code.sololearn.com/c0Sn0vQFnM3W/?ref=app

6th Jan 2021, 9:19 AM
XLK
XLK - avatar
3 odpowiedzi
+ 8
The "sum = 0" should be outside the for loop so every iteration, the value won't reset to 0. Same with "print(sum)", because based on the desired output, you only need to print the sum, not the cumulative sum (total every iteration). And by the way, if you want to get the input of for example 1 3 7 5: inpt = [int(x) for x in input().split()] split() splits the string(default input type) by whitespaces by default and so the 1 3 5 7 will become ["1", "3", "5", "7"] but each element is still a string so to make each element an integer, use list comprehension, [int(x) for x in list] Some additional useful function: >> print(sum(list)) >> # this will print the sum of each element of a tuple, list, etc. without using "for loop". I hope this helps. https://code.sololearn.com/ca0A11A17a16
6th Jan 2021, 9:31 AM
noteve
noteve - avatar
+ 6
Yes that was nice and smooth explanation Thank you for your help
6th Jan 2021, 9:51 AM
XLK
XLK - avatar
+ 1
x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for x in x: sum += x print(sum)
6th Feb 2022, 2:55 PM
ZEFANYA