23 Jul 2018

Loop and Break in Python




j=0

while (j < 11):
    print("inside while J=" , j)
    if (j == 3):
        break

    j += 1 # increment j by 1 (same as j=j+1) 
    
print("I am free J=", j)

'''
Look at first line of code, we have set j=0 initially.
the program now can enter the while loop as value of j is less than 11
while (j < 11):
Since j = 0, program enters the loop and prints "inside while j= 0"
next it checks if ( j==3), in the first loop run j is 0, so it skips if (j==3) code block
Then it finds j+=1 , which means increment the value of j. It is same as j=j+1
If we dont do that program will end up a iternal loop.
now j=1
Then it returns to while (j < 11) : condition,
the j is 1 so it is again allowed to enter the loop and run while code block again
So this goes on. we know at every run j get incremented by 1
I becomes 1, 2 and then 3
since j < 11 it can enter the loop again with j=3
in the loop it finds if (j==3) : condition. Now it is true,
Now it goes into if block and finds the break statement
break statement breaks out from inner most loop block, that is while j < 11 code block
so it jumps out of while loop and prints "I am free J=3"

Shilpa64 Algohack
'''

No comments: