Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to determine which variables to add and which to not add together?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading