+ 3
I'm new to python and I don't understand for loop :(
Someone help me please, what is wrong in my code, how to sum all numbers in the list? list = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] for x in list: print(sum(list))
14 Réponses
+ 4
just print the sum of the list no need for the for loop
+ 4
Quarkom
You are caught between 2 different ways of doing this.
Try removing 'for x in list:' from your code.
You will have a method which will sum the contents of your list.
But if you want to use a for loop,
then you will need to create a variable to catch the iterated items of the list
Example
result = 0
for x in list:
add each item into result
print(result)
See if you can figure out how to do that.
Good luck, let us know how you go
+ 3
get Thank you, didn't see that mistake
+ 2
Don't give me the full answer, just a hint
+ 2
There are many variants of how to implement it:
1. MATOVU CALEB has answered it already.
2. Create a variable for the result and add each item to it.
The other ones may be confusing for beginners and it is better to use them only in some specific cases. I can mention some of them that come to my mind if you want to, though.
+ 2
for x in list:
Simply saying x is going to visit all the elements in the list. First x will get the value 42 so x=42. Now it will go inside the for loop and executes the statements and wherever x is written the value 42 will be evaluated. Again after executing all the statements inside the for loop x will get the next value 8 and it continues the same until it become 99 and the for loop gets ended.
Here in your code everytime the for loop runs the sum of list is printed and there is no use for x.
In python the sum() function returns the sum and there is no need for loop.
If you want to find the sum using for loop then do this
list = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99]
sum=0
for x in list:
sum=sum+x
print(sum)
+ 2
Rik Wittkopp it worked but I have another problem...
cart = [15, 42, 120, 9, 5, 380]
discount = int(input())
total = 0
for x in cart:
total+=x
print(total*((100-discount)*0.01))
How to make this code outputting only one number from cart list instead of all numbers
+ 2
Quarkom
I am not sure, but it looks like your print function is inside the loop indentation.
Take it out of the indentation to just print the total of the iterations
PS: You don't need to apply the discount to each item.
Total the items and apply the discount
+ 2
You should store the list in a variable and also should write x = 0 and x+=1 .
+ 1
Here it goes:
list = [42,8,7,....]
for x in list:
sum += x
print(sum)
0
Just use the sum function
0
The sum method is for a list not for an individual element.
For loop takes elements one by one…which makes it impossible to sum them up, since there is only one element taken. Just erase for x in list line and your code will work.
0
https://code.sololearn.com/cHyJlOGTErRs/?ref=app if you really want to use a for loop to sum up your elements