r/learnpython • u/lailoken503 • 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: TrueThe second condition triggers but not the Boolean, and I'm stumped as to why.
5
Upvotes
9
u/Langdon_St_Ives 19h ago
Others have pointed out the faulty logic, but let me add a guess why you got it wrong: you were probably thinking you want to break out of the loop as soon as the first OR the second condition is violated, which is correct. And this would translate to a logical OR in an _until_ loop which some languages have (like `do until numMatch == True or incCount > maxNum`), but Python lacks. So when you invert this compound condition, remember that not (A or B) doesn't distribute to (not A or not B), but to (not A and not B). That's why you need an and for your while loop.