+ 3
I do not understand, trace of this code; can anybody explain it?
i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") https://www.sololearn.com/discuss/1035408/?ref=app
2 Answers
+ 9
first you give i the value 0
then define a while loop the true value let the loop runs infinitely.
inside the loop: the current value of i equals to the previous value of i plus 1
now we check if i equals to 2 the loop (continue): will ignore the current iteration and cause the next iteration to begin.
we check if i equals to 5 the loop will (break): exit the loop immediately and move to the next line outside the loop.
+ 7
A 'while True' loop is an infinite loop. It will run indefinitely until broken somewhere inside. What it does inside, it increases the i iterator by 1 ewch time and prints it. Also, it has two conditional statements inside, which check for the value of i. If it is equal to 2, the "Skipping 2" is printed and the loop goes back to the top, ignoring everything inside the loop for this particular run. Then it continues to run, prints out 3 and 4. Then, when i equals 5, another if statement fires up. It prints "Breaking" and immediately breaks (exits) the while loop.
The program is ended.