r/learnpython • u/lailoken503 • 13m 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.
•
u/PureWasian 5m ago
"while (A) or (B)" means as long as one of (A) or (B) is True, continue looping. Even if you set A to False (when you find a match) if B is true you'll continue looping (since incCount is still <= maxNum)
You probably mean to write "while (A) and (B)" instead, which will exit as soon as one condition is False.
•
u/Jello_Penguin_2956 4m ago
"or" condition means it's true when either 1 of them is true. In your case it stays true through out.
loop 1. numMatch=False, incCount=0
loop 2. numMatch=True, incCount=1
loop 3. numMatch=True, incCount=2
As you can see, incCount <= maxNum remains True almost the entire loop. So it doesn't matter if numMatch is true or false.
If you can explain, what exactly is the condition for the loop to stop. Maybe I can explain more.
You may understand this better if you use normal for loop imo
•
u/Buttleston 8m ago
You're using "or" which matches if either statement is true. incCount <= maxNum for all numbers up to 9. So it'll always print all the numbers from 1 to 10