I started learning Python, I encountered the following problem.
The conditions of the problem are as follows:

For this natural n calculate the sum of 1Β²+2Β²+3Β²+...+nΒ² .

I got this code, but it does not display the correct values. What could be the error? You need to use only while , without using for / range :

 n = int(input()) i = 0 sum = 0 while i < n: i = (i + 1)**2 sum = i + n**2 print(sum) 
  • one
    With a pencil and paper, go over your algorithm, it will become clear. - Enikeyshchik
  • I also study python, kmk, if I need an answer with one (final) number, then I should add if i < n: continue if ii == n ΠΏΠ΅Ρ€Π΅Π΄ print , otherwise the answer will be a sample of numbers - user340699

1 answer 1

 n = int(input()) i = 1 # Π½Π°Ρ‡ΠΈΠ½Π°Ρ‚ΡŒ с нуля Π½Π΅ ΠΈΠΌΠ΅Π΅Ρ‚ смысла, Ρ‚.ΠΊ. 0^2 = 0 sum = 0 # наш Ρ†ΠΈΠΊΠ» Π΄ΠΎΠ»ΠΆΠ΅Π½ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ Ρ‚Π°ΠΊ ΠΆΠ΅, ΠΊΠ°ΠΊ ΠΈ for i in range(1, n+1). ΠŸΠΎΡΡ‚ΠΎΠΌΡƒ условиС ΠΈΠΌΠ΅Π½Π½ΠΎ Ρ‚Π°ΠΊΠΎΠ΅, Π° Π½Π° ΠΊΠ°ΠΆΠ΄ΠΎΠΉ ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ ΡƒΠ²Π΅Π»ΠΈΡ‡ΠΈΠ²Π°Π΅ΠΌ i Π½Π° 1 while i <= n: sum += i**2 # добавляСм ΠΊΠ²Π°Π΄Ρ€Π°Ρ‚ этого числа ΠΊ суммС i += 1 print(sum) 
  • from the unit there is no more meaning. You can immediately equate the amount to 1. - slippyk
  • It would be desirable to arrange this all in the form of a function, but this is optional. It is also possible to use range (). - my diamonds dancing
  • I agree with the first one and with the second one, but the clause stated β€œwithout using for / range” - XxX
  • @slippyk and if 0 elements? - Suvitruf ♦