Cant get this to work!

def sum_squares(x):
    sum = 0
    expo = x * x
    for x in range(x):
        sum += expo
    return sum

im trying to create a function that sums the square of a set of numbers in a range. can i get some guidance and an explanation

I’m going to assume that the problem you’re tackling is this one and address it in a way that follows those requirements. But please let me know if you’re attempting a different one.

To understand things better, let’s break down the process for how the sum squares algorithm works in general. The process goes something like:

  • Create a sum variable to store our answer
  • Loop through each element in the input array
    • Calculate the square of the current element and add the answer to sum
  • After looping through all elements, return sum.

Another thing to help with understanding the logic is to run through a test case as an example. The test case we’ll use is sumsq([1, 2, 3, 4, 5]) should return 55. Using the process above we would do:

  • Set sum = 0 (like you’ve done above)
  • Begin looping through the input array
    • 1 * 1 = 1, so add 1 to sum (sum is now 1)
    • 2 * 2 = 4, so add 4 to sum (sum is now 5)
    • 3 * 3 = 9, so add 9 to sum (sum is now 14)
    • 4 * 4 = 16, so add 16 to sum (now 30)
    • 5 * 5 = 25, so add 25 to the sum (now 55)
    • Since there are no more elements to loop through, we exit the loop
  • Return sum

Now your code is on the right track, but I can see a few key mistakes that come down to these two lines below. With the examples above in mind, can you see where the mistakes are?

expo = x * x
for x in range(x):

If it’s still not clear, I would try stepping through your code on paper with some example inputs and work out what each step is doing.

Hope that helps :slight_smile:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.


Line 3 & 4 should be switched.

Also your range doesn’t go high enough.

Range(start(optional and inclusive), stop(exclusive))
You have range(5), which means 5 is not included.

The answer is:

def sum_squares(n):
    return sum(list(x * x for x in range(n)))

if you have a list :

def sum_squares(a_list):
    return sum(list(x * x for x in a_list))