I
I
Islam Azikov2020-07-09 13:52:48
Python
Islam Azikov, 2020-07-09 13:52:48

How to use the variable sum in the for in range statement?

We need to find the sum 1² + 2² + 3² + ... n² for a given value of n. You need to use a variable - adder sum. I understood it like this:

for a in range (1, 5):
    b = a ** 2
    result = sum(b)
    print(result)

But of course it doesn't work. Where is my mistake and how to do it right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Fedoryan, 2020-07-09
@Dzharves

More or less like this

n = 5

result = 1
for num in range(2, n + 1):
    result += num * num

print(result)

A variable with a name sum- it's better not to use it, this is a keyword in python
You can do it in one line:
print(sum([num ** 2 for num in range(1, n + 1)]))

L
Little_CJIOH, 2014-11-27
@Little_CJIOH

Google testing of any suitable for the price, if it is not an obvious outsider - take it. Samsung 840 just do not take.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question