Cannot figure this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Cannot figure this code

sum = 0 x = 10 while x > 0: sum += x x -= 1 print(sum) Why sololearn tell me 55 as a result?

27th Oct 2021, 7:02 PM
Giuseppe Leonardi
8 Answers
+ 4
10 + 9 + … + 1 = 55
27th Oct 2021, 7:08 PM
Per Bratthammar
Per Bratthammar - avatar
+ 4
Yes this while loop will continue to run for 10 time, starting from 0 to 9, On every iteration it will accumulate result of integers 1,10. If u add 1 to 10 numbers, it will results in 55.
28th Oct 2021, 3:29 AM
Nomi
Nomi - avatar
+ 3
10+9+8+7+6+5+4+3+2+1 = 55
27th Oct 2021, 7:06 PM
Lisa
Lisa - avatar
+ 3
Yes, exactly
27th Oct 2021, 7:31 PM
Lisa
Lisa - avatar
+ 2
Why the code do the summary? Cause of “Sum +=x” right? And thank tho this x -=1 we are telling to start to sum from 10 to 1 is this right?
27th Oct 2021, 7:19 PM
Giuseppe Leonardi
+ 1
The x that started out as a 10 is reduced by 1 after each loop, the resulting 9 is then added to the 10(sum += x or sum = sum + x). Next loop the 9 is reduced to an 8 (x -= 1 or x = x - 1 in cs). The 8 is added to the earlier found 9 and 10, and so on... Until the final result of 55 is obtained. 😃
28th Oct 2021, 7:59 PM
Pius Motai
Pius Motai - avatar
+ 1
The value of x initial level was 10 ,it reduced by 1 after each loop so the the code adds numbers from 10 to 1
29th Oct 2021, 4:08 PM
Amrutha
Amrutha - avatar
0
An easy way..the sum from 1 to n is equal to n x (n +1)/2... in this case 10 * 11/2= 55 that is the Gauss method
28th Oct 2021, 4:03 AM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar