Just started to learn Python and got stuck immediately. I have to add together variables that are greater than 0. So e.g. if I had these variables:
num1 = 5
num2 = 5
num3 = 0
num4 = -5
num5 = 5
I’d like to add together 1, 2 and 5 (total 15) and exclude 3 and 4.
I guess I could use
if num1 <= 0:
print(num2 + num3 + num4 + num5)
else:
print(num1 + num2 + num3 + num4 + num5)
and go through every variable like this but it sounds really unconvenient and awkward. How should I do it with one command? Thanks.
>Solution :
It’s better to store the values in a list, rather than in five different variables. And then it will be easy to use for loop or list comprehension, for example, to do what you want.
Using for-loop:
lst = [5, 5, 0, -5, 5]
output = 0
for x in lst:
if x > 0:
output += x
print(output) # 15
Using list comprehension (more precisely, generator expression):
lst = [5, 5, 0, -5, 5]
output = sum(x for x in lst if x > 0)
print(output) # 15