+ 1

Hello. Can anyone explain how this code works pls?

num = int(input()) result = 0 i = 0 while i <= num: result = result + i i = i + 1 print(result)

16th Dec 2020, 5:04 PM
Mas'ud Saleh
Mas'ud Saleh - avatar
2 Answers
+ 3
For example: you give input: 5 Now,i=0 and result=0 Now the loop will run 6 times,as i=0 and end with 5 in total 6 times. 1st time, in loop, result=result+i=(0+0)=0 then, i=i+1=(0+1)=1 2nd time in loop result=result+i=(0+1)=1 i=i+1=(1+1)=2 3rd time in loop result=result+i=(1+2)=3 i=i+1=(2+1)=3 4th time in loop result=result+i=(3+3)=6 i=i+1=(3+1)=4 5th time in loop result=result+i=(6+4)=10 i=i+1=(4+1)=5 6th time in loop result=result+i=(10+5)=15 i=i+1=(5+1)=6 So the answer will be 15
16th Dec 2020, 5:15 PM
The future is now thanks to science
The future is now thanks to science - avatar
0
First it takes input from user and assigns its value to num, this num variable is how many number of times the loop will be executed. Then it checks loop condition i.e. i<=num. If this condition is returned true then block inside loop is executed. In loop result variable is added to i variable and this sum's value is stored in result variable. Finally when loop condition is false result's value is printed. .....For example, if input is 3 then, loop will 4 times in that case result value will be 0+0=0 for first iteration and value of i will be 1. Similarly for second iteration, result=0+1=1, i=2. And so on so for input 3 final value of result and i will be 6 and 4 respectively. Hope it helped..
16th Dec 2020, 5:34 PM
Sanjyot21
Sanjyot21 - avatar