Can someone help me understand how this returns/prints a 6?

Ed:
Can someone help me understand how this returns/prints a 6?
image.png

Mohamed Ayman:
Hello @Ed
is 1 => 3 ? yes go to the while loop, sum= 0+1 and i = 1+1

is 2 =>3? yes go to the while loop, sum= 1+2 and i =1+1+1

is 3 => 3 yes go to the while loop, sum= 1+2+3 and i= 1+1+1+1

is 4=>3? no exit from the loop and print the sum which is 1+2+3 = 4

Saqib Valliani:
In this code, the variable i is being incremented until it reaches the target value which is x, and on every iteration the value of “sum” is getting updated by adding the value of “i” to the current value of sum. sum(updated value) = sum(current value) + i
• sum = sum + i, sum = 0 +1 = 1 (i=1)
• sum = sum + i, sum = 1 + 2 = 3 (i=2)
• sum = sum + i, sum = 3 +3 = 6 (i=3 which is the breaking condition).

Ed:
@Saqib Valliani AWESOME Explanation. Thank you so much. So why is the while loop <= and not == to break the loop?

Saqib Valliani:
if you set while(i==x), this means that loop will execute until x and i are equal, in the code initially x = 3 and i = 1 so, the code will not enter in while loop since i and x are not equal.

Ed:
k make sense. I guess Ill have to revisit the module regarding when does a while loop begin and when will it stop. Thank you for helping me understand this PE

Alistair Mackay:
@Ed A video speaks a thousand words! Here is that sript running in the Visual Studio Code debugger. On the right we see the flow of the program as I step through it. On the left we see the values of i and sum changing.
By the time we get to the print statement, the value of sum is 6
py-debug2.gif