#Please review code and answer question at end. Thanks! i = input ("Enter a number ") # playing with while statements to see how to end buggy loop from exercises while i > 0: print i if i % 2 == 0: #checks for even i = i / 2 #divides number if even else: i = i + 1 # adds 1 if odd if i < 3: i = -1 #ends loop when i = 2 #Question: when running, the output goes to 1 before stopping. # Why does it not stop at 2 since last line redefines i as -1 # when the value is less than 3?
A `2` always becomes a `1` because `2 % 2 == 0`. A `1` always stops the loop: If `i < 3` is done as `2 < 3`, it means that the `else` block started with `i=1`. That means that `1` has been printed at the beginning of the loop, and since the loop stops, no other values is printed. `1` is always printed last.
Join our real-time social learning platform and learn together with your friends!