+ 1

How the print works?

i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") why if i brought print(i) under while True, it prints 2? while, if print is on the bottom before print("Finished") its not print 2. How the code run?

12th Nov 2018, 3:58 PM
Zulfadhli
Zulfadhli - avatar
1 Réponse
+ 4
Just go through it step by step: 1# i is increased to 1, no if condition holds, so it prints 1 2# I is increased to 2, first if condition holds, so it prints "Skipping 2" and continues on the top of the loop 3# i is increased to 3, no if condition holds, so it prints 3 #4 i is increased to 4, no if condition holds, so it prints 4 #5 i is increased to 5, so the second if condition holds, prints "Breaking" and breaks out of the loop (i.e. does not get to print(i)) Loop is finished and it prints "Finished" Summary: 1 Skipping 2 3 4 Breaking Finished
12th Nov 2018, 4:54 PM
Matthias
Matthias - avatar