r/learnpython • • 19h ago

while loop behaves unexpectedly

Been at this for a while and can't seem to make sense of why a multi-conditioned while loop only triggers when one condition is met, but not the other, which generally happens sooner before the 2nd condition is met.

The results I get running the sample:import random
numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
randNum = int(random.randint(1, 10))
numMatch = False
maxNum = 9
incCount = 0

while numMatch == False or incCount <= maxNum:
    if numList[incCount] == randNum:
        numMatch = True
    
    print(numList[incCount])
    incCount += 1
print('Random number: ' + str(randNum) + '\n')
print('numMatch: ' + str(numMatch))


Y:\Users\lailoken\Documents\Python>python sample.py
1
2
3
4
5
6
7
8
9
10
Random number: 3
numMatch: True

The second condition triggers but not the Boolean, and I'm stumped as to why.

5 Upvotes

20 comments sorted by

View all comments

0

u/Rare-Pay9795 18h ago

The loop uses or, so it keeps going as long as either condition is true. After the match, numMatch == False is False, but incCount <= maxNum is still True, so the whole condition stays True and it carries on until the counter runs out.

You want it to stop when either one fails, which means and:

while not numMatch and incCount <= maxNum:

A handy way to think about it: write the condition for when the loop should stop ("matched or out of numbers"), then negate it. By De Morgan's law, not (a or b) becomes not a and not b.

Small extras: random.randint already returns an int, so the int() isn't needed, and for n in numList: with a break on match is the more usual Python pattern for this.