1

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.

3
  • 1
    at least try to do it.... Commented Jan 27, 2018 at 19:23
  • 3
    your question heading says square, and the start of question says square root and your example belongs to something else. What exactly do you want? Commented Jan 27, 2018 at 19:24
  • for your given example, you can get desired result using sum((n+1)**2 for i in range(n)) where n = 3 for your case Commented Jan 27, 2018 at 19:27

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

also it is worth mentioning that it is raw_input for Python 2.x and input for Python 3.x
1
def solve(n):
    res = 0
    for i in range(n + 1):
        res += i ** 2
    return res

Hope that helps!

2 Comments

you definitely help get me started, I had modify your code a little bit to fit the requirement by Codio (the program my school uses for coding classes). so this is what it looks like now: ( res = 0 for i in range(0, N + 1): res += i ** 2 print (res) ) the output I'm getting is 0, 1, 5. how can I get it to output a single number with the for loop?
Put the print (res) outside the for loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.