[Solved] Taking square of summed numbers


Ah, I see you like Project Euler 🙂

Solution

I think this is what you meant by your code:

def square_of_sum():
  sum_ = 0
  for x in xrange(1, 11):
    sum_ += x
  return sum_ ** 2

To rewrite this more idiomatically, use generator comprehensions and built-ins:

def square_of_sum():
  return sum(range(11)) ** 2

If your performance conscious, you can eliminate the loop by noticing that your finding the sum of an arithmetic series:

def square_of_sum(x):
   print (x * (x + 1) / 2) ** 2

Fixes

As to why your code isn’t working, it’s b’coz of many reasons.

First of all, I think you’re confused about how the for loop in Python works. Basically, it just loops over an array. You didn’t have to check and break when x became greater than 10, nor increment it. Read up on the Python docs on how to use the for loop. To see an example of when to use it, see the wiki page.

Secondly, variable assignments are done with the variable on the left and the expression to be evaluated on the right. So x + sum = sum should really have been sum = sum + x or sum += x for brevity.

Thirdly, sum is a built-in function. You probably didn’t want to nor shouldn’t over-shadow it, so rename your sum variable to something else.

And last, sum*sum is equivalent to just raising it to the power of 2 and you can do that using the ** operator as so: sum ** 2.

Hope this helped you understand.

solved Taking square of summed numbers