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.
7
Upvotes
View all comments
Show parent comment
4
u/lailoken503 2d ago
This was my thinking, plus, stressing a bit over why the first condition wasn't triggering the loop termination while the other was, eventually, didn't help me see what I should have noticed (looking back, duh). I had thought OR was one or the other, which is normal in life. I want a hamburger or i want a steak. Both can be true, I do want both; it's what I go through when the family and I go out for dinner. I guess this way of thinking overflowed into the program, and I didn't make the connection about OR and AND.
The thing is, this was discussed in my programming class a bit more than 10 years ago, and I've forgotten about it since then. Programming isn't something I do daily, but something I do once in a while when the mood, or work need, strikes.
In this case, this is a simpler version of a 'help me do my job quicker' code I've been doing at work, as a way to read through hundreds of 'thousand lines test results' to find anything that I should raise concerns with. This portion of the code was intended to locate a range of test failures for me to review and ensure the parts were not inadvertently retested again. It is related to an earlier learn python post I've placed months ago, and recent changes in production requirements required me to find failures in a specific range of tests where they weren't needed before.
In a nutshell, if a failed test number matches a set of numbers in a list (noRetest = [1, 29, 224, 323...]), it can't be retested until it gets looked at more closely. The conditions were to stop the loop if a test failed for anything in the noRetest list OR when the end of the failure list is reached, which my sample code above is roughly based on.
I'm glad I asked, despite some of the downvoting (hey, it's a learning experience).
I've also changed my while loop to:
while numMatch == False or incCount == maxNum:
which seemed to work after several repetition of the code being run.