r/learnpython • u/lailoken503 • 2d 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.
6
Upvotes
View all comments
Show parent comment
1
u/realmauer01 2d ago
Your understanding of "or" is correct, your understanding of while is not.
While something is true you are doing something specified. So in this case, while nummatch is false or inccount is smaller or equal to maxnum, you are doing whatever you are doing.
What you wanted is different, you wanted to do something while nummatch is false and inccount is lower or equal to maxnum. Because only then it stops when either of these condition changes.
You can only turn the conditions around. Do something while not nummatch and inccount is not higher than maxnum.
The important part is understanding that the while condition keeps the loop alive, and doesnt break it.