Home > Software design >  How do i sum numbers that come from an answer from a "for in" loop?
How do i sum numbers that come from an answer from a "for in" loop?

Time:04-01

gjeld = [79, 99, 598, 879, 299, 99, 79, 299, 99, 299, 598, 897]

for n in gjeld:
    if n > 500:
        print(n)

the list above is lets say taxes and i needed to find taxes above 500 and print the sum of all numbers that are over 500. It would print:

598
879
598
897

in that order, and i need a way to sum up all those numbers together.(Its a school task)

i tried doing:

gjeld = [79, 99, 598, 879, 299, 99, 79, 299, 99, 299, 598, 897] 
a=[]

for n in gjeld: 
    if n > 500:
        a.append(n)
        print(n)

but it didnt work

CodePudding user response:

If it's a school assignment, I'll assume they don't want you to use the sum() built-in function, so let's do the summing by hand:

total = 0

for n in gjeld:  # loop over gjeld 
    if n > 500:  # if n is over 500, then
        total = total   n  # compute total   n, and assign back to total

print(total)  # print the total computed after the loop

If sum() is allowed, then you'd be looking at

a = []

for n in gjeld: 
    if n > 500:
        a.append(n)

print(sum(a))

If generator expressions or list comprehensions are allowed – and this is the most Pythonic way to write this -

print(sum(n for n in gjeld if n > 500))

CodePudding user response:

The code you have is a good start, but all you have done so far is put the numbers higher than 500 in a list, so after the loop a = [598, 879, 598, 897]. After you finish creating the list, you need to add together everything in the list, which you can do with sum(a)

for n in gjeld:
    if n > 500:
        a.append(n)
        print(n)

print(sum(a))

CodePudding user response:

gjeld = [79, 99, 598, 879, 299, 99, 79, 299, 99, 299, 598, 897] 
a=0

for n in gjeld: 
    if n > 500:
        a=a n
        # print all above 500
        print(n)
# print after sum
print(a)

CodePudding user response:

You can do this with a generator:

gjeld = [79, 99, 598, 879, 299, 99, 79, 299, 99, 299, 598, 897]

print(sum(x for x in gjeld if x > 500))

This will give you the sum of any/all values in the list greater than 500. It will not print the individual values.

Alternatively:

print(sum(filter(lambda x: x > 500, gjeld)))
  • Related