+ 1
Please explain the following code of Python3.
x = 0 while x<5: x=x+2 print(x) How the output is 6??
2 Answers
+ 4
This is what the program does:
x = 0
x < 5 ? (true)
x = x + 2 (x=2)
x < 5 ? (true)
x = x + 2 (x=4)
x < 5 ? (true)
x = x + 2 (x=6)
x < 5 ? (false)
print x
end program
+ 12
x = 0
while x<5:
x=x+2
print(x)
the condition of while loop is less than 5 the initial value of x is 0 so
0<5 true =>it will go in the loop x=x+2 so x=0+2=2
so x=2 now , 2<5 condition true x=x+2=2+2=4 so x become 4 now x=4 , 4<5 so condition true x=4+2=6
so x=6 now 6<5 condition false loop break and go to outside loop and print the value of x
which is 6 so output is 6