Bruh gamer epic
Bruh gamer epic

Reputation: 9

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

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

Upvotes: 0

Views: 79

Answers (4)

Adon Bilivit
Adon Bilivit

Reputation: 27002

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)))

Upvotes: 0

Mashaim Tahir
Mashaim Tahir

Reputation: 59

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)

Upvotes: 0

pollfly
pollfly

Reputation: 63

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))

Upvotes: 0

AKX
AKX

Reputation: 168966

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))

Upvotes: 3

Related Questions