Simple for loop example | Sololearn: Learn to code for FREE!

-1

Simple for loop example

Hi this is a simple for loop example I have no idea how to approach. I only know while, len functions (not count or sum in python yet) how can I solve? When This is code I'm given: #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 list = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 0 #your code goes here for x in list: if(x == 1): sum += 1 print(sum)

12/12/2020 4:51:40 AM

Fast

16 Answers

New Answer

+9

l = [1,2,3,4,5,6,7,8,9] s = 0 for x in l: s += x print(f'sum is {s}') # don't use the words 'list' or 'sum' as variables' names. they are reserved keywords.

+7

Fast You will learn this somewhere in the course. The so called f-string enables you to insert values or strings at certain points in a given string. the points are marked with a pair of curly braces {}. between them you have to note the variable or the expression which you want to insert in the string. The f-string can be seen as a replacement for string concatenation. print(f'sum is {s}') is equivalent to print('sum is ' + str(s))

+2

So far my code is: sum = 0 for x in list: sum += x print(sum) Is this what is happening? Sum = 0+1 Sum = 1+2 Sum = 3+3 Sum = 6+4 Sum = 10+5 Sum = 15+6 Sum = 21+7 Sum = 28+8 Sum = 36+9 Sum = 45

+2

x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for x in x: sum += x print(sum) ##hehe

+1

Thank you Jan I will study that

+1

x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] r = 0 for n in x : r+=n print(r)

+1

x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for x in x: sum += x print(sum)

0

Fast Why are you checking x == 1 when you just need to add values of list? Just do sum += x

0

This is a code playground beginner challenge i don't know what print(f'sum is {s}') yet

0

Fast Yes Here we are adding next value with previous total value.

0

Try list = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 0 #your code goes here for x in list: if(x == 1): sum += 45 print(sum)

0

### x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for i in x: sum=sum + i print(sum) Perfect answer 😊

0

x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] count = 0 for x in x: count += x print(sum)

0

this is 100% correct list = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 0 #your code goes here for i in list: sum+=i print(sum)

-1

x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] sum = 0 for x in x: sum += x print(sum) done...!

-6

using sum() function: list = [1, 2, 3, 4, 5, 6, 7, 8, 9] total = sum(list) print(total)