+ 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?
8 Antworten
+ 4
10 + 9 + … + 1 = 55
+ 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.
+ 3
10+9+8+7+6+5+4+3+2+1 = 55
+ 3
Yes, exactly
+ 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?
+ 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. 😃
+ 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
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