Curl inside while loops 1

what is the difference between this code

x = 10
while x:
   x = x - 1
  if x % 2 == 0:
    print(x, end = ' ')

and this code

x = 10
while x:
  if x % 2 == 0:
    x = x - 1
    print(x, end = ' ')

I'v just start the python lerning thanks in advance

1 answer

  • answered 2017-11-12 21:56 PTN

    In the first code block: You subtract 1 from x after every loop iteration, thus the value of x will be:

    10 (outside the loop)
    9
    8
    ...
    1
    0
    

    It will print x whenever x is even

    8 6 4 2 0
    

    The second code block will loop infinitely after the first iteration. The inside of the if statement is executed only one when x = 10. After that, the value of x is always 9 and it stays like that infinitely.