+ 3

How does this Python code work?

n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum+i i = i+1 # update counter print("The sum is", sum)

21st Sep 2020, 6:43 PM
3.14
3.14 - avatar
3 Answers
+ 6
There are 10 iterations in total from i=1 till i=n, where n is 10. Each time you add the value of i to the variable sum. So it is 1+2+3+...+10 which is 55.
21st Sep 2020, 7:02 PM
Avinesh
Avinesh - avatar
+ 7
Avinesh, good explanation. 3.14159265358, I recommend you to try your code in the sandbox with changed parameters like n = 100.
21st Sep 2020, 8:41 PM
Alexander KovalšŸ‡§šŸ‡¾
Alexander KovalšŸ‡§šŸ‡¾ - avatar
+ 1
yes
23rd Sep 2020, 3:15 PM
Mirzohid Choriyev
Mirzohid Choriyev - avatar