Alex Hoover
Alex Hoover

Reputation: 1

Answer prints 0 not actual answer

def difference1():
    answer = 0
    for a in range(1, 100):
        sum1 = a**2
        sum1 += answer
    print(answer)
difference1()

why is my code printing 0? I want to get all the numbers between 1 and 100's squares added together. I probably have just made a dumb mistake but i can't figure it out.

Upvotes: 0

Views: 72

Answers (5)

Squishy
Squishy

Reputation: 96

you had an incorrect range and you added your answer to sum1 and and not adding answer to sum

you can directly add a**2 to answer

def difference1():
    answer = 0
    for a in range(101)
        answer += a**2
    return answer
print(difference1())

Upvotes: 0

retep
retep

Reputation: 227

On this line, sum1 += answer, you have declared answer as 0 and are adding it to sum1. It currently looks like this: sum1 = sum1 + 0. You want it to look like this: answer = answer + sum1. Therefore, use this expression instead: answer += sum1.

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56714

You are adding answer to sum1, when you should be adding sum1 to answer!

Also, you have a mistake in your range: it goes up to but not including the stop-value:

def sum_of_squares(upto):
    answer = 0
    for i in range(1, upto + 1):
        answer += i*i
    return answer

print(sum_of_squares(100))    # => 338350

For bonus points, it could also be written as

def sum_of_squares(upto):
    # turn the loop into a generator expression
    return sum(i*i for i in range(1, upto + 1))

or as

def sum_of_squares(upto):
    # sum of squares formula
    return upto * (upto + 1) * (2*upto + 1) // 6

Upvotes: 2

admix
admix

Reputation: 1782

You never change the 'answer' varaible, thats why it always 0 as you assigned it.

Do this:

def difference1():
    answer = 0
    for a in range(1, 100):
        sum1 = a**2
        answer += sum1 #the change is on this line
    print(answer)
difference1()

Upvotes: 1

Brendan Abel
Brendan Abel

Reputation: 37599

You're adding to the wrong variable, you want:

answer += sum1

Upvotes: 0

Related Questions