I don't understand what is wrong with my code.
I am trying to add positive values of a list.
Here is my code:
def sam(n):for x in n:if x > 0:return sum(x)
I don't understand what is wrong with my code.
I am trying to add positive values of a list.
Here is my code:
def sam(n):for x in n:if x > 0:return sum(x)
You never actually create a value to add to. You are adding one value to a list per in iteration.
Just in iterate through the list and add them manually:
def sam(n): value = 0for x in n:if x > 0:value += xreturn value
Or you could do it in one line:
def sam(n):return sum(x for x in n if x > 0)
For better practice you should choose better variables. More meaningful variables are easier to remember and makes your code more readable:
So n
could be num_list
(or number_list
).
Rather than iterate with x you could use number
. This tells you that number contains a single letter.