Python while not loop

Viewed 151

I'm new to Python and I cannot understand the following code:

i = 0
j = 0
while not(i < 3 or j == 5):
  i = i + 1
  j = j + 1
print(i)

returns 0, even though the inverse (not) of j == 5 returns true

7 Answers

not(i < 3 or j == 5)

is equivalent (by De Morgan's duality) to:

not(i < 3) and not(j ==5)

which is further simplified to:

(i >= 3) and (j != 5)

so since i = j = 0 this condition is not satisfied.

i < 3 or j == 5

returns True (i<3) therefore

not(i < 3 or j == 5) returns False which means that your while loop does nothing at all and finally your code prints the value of i which is 0

The reason is that not(i<3 or j==5) corresponds to (i >= 3 and j != 5). Since i and j do not satisfy both of these conditions at the same time, the code does not go into the loop and the variables i and j stay 0.

i = 0 and j = 0, so not(i < 3 or x == 5) = not(0 < 3 or 0 == 5) = not(True or False) = not True = False

i = 0
j = 0
while not(i < 3 or j == 5):
  i = i + 1
  j = j + 1
print(i)

(i < 3 or x == 5) -> (True or False) -> True -> not True -> False ->

i = 0
j = 0
while False:
  i = i + 1
  j = j + 1
print(i)

Also, (not(i < 3) and not(j == 5)) -> (False and True) -> False

So it doesn't execute.

i = 0 j = 0 are the initial values for the variables, then while not (i < 3 or j == 5) is the condition for the loop to initiate, which will only take place if j is not less than 3 or if j is equal to 5. Which isn't the case since i=0 and 0<3, and j isn't equal to 0.

In other words, the code will skip the loop and print i, which is 0.

while loop breaks, when its condition doesn't evaluate to True. In your case condition is not(i < 3 or j == 5). This means for this loop to break (i<3 or j==5) should be True. At start both i and j is 0. Then (i<3 or j==5) becomes (True or False), then True. That's why your loop breaks so early

Related