Mast3r_Heath
Mast3r_Heath

Reputation: 77

Finding the square of an unknown variable using a for loop

I am trying to figure out how to find the square root for an unknown variable using a for loop. the prompt I was given is: So if we passed in 3, you would output 0^2+1^2+2^2+3^2=14

this is for my intro to scripting class, and I am just at a compete loss.

Upvotes: 1

Views: 316

Answers (2)

be_good_do_good
be_good_do_good

Reputation: 4441

One way to do this is:

n = int(raw_input("Enter number")) # get the number, use input if you are using python 3.x
sum([i**2 for i in range(n+1)]) # form a list with squares and sum them

You can do it with lambda too. Here it goes:

reduce(lambda x,y: x + y**2, range(n+1))

Upvotes: 2

scripter
scripter

Reputation: 356

def solve(n):
    res = 0
    for i in range(n + 1):
        res += i ** 2
    return res

Hope that helps!

Upvotes: 1

Related Questions