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.
18
u/Buttleston 19h 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
2
2
u/Temporary_Pie2733 11h ago
numMatch is an antipattern in the first place. If you want to exit the loop early, use break instead of setting a flag to be checked later. Also, To iterate over a list, use a for loop instead of a manually incremented index.
for num in numList:
print(num)
if num == randNum:
breakIf maxnum isn’t just the last valid index into numList, iterate over a slice:
for num in numList[:maxNum+1]:
…2
u/PureWasian 19h 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.
1
u/LegalDebate5423 17h ago
`or` keeps the loop running while either condition is true, so finding the number won't stop it while the index is still within the bound. Use `and` if you want to stop when either the match is found or the list ends. A `for value in numList` loop is simpler here and avoids indexing past the list if the value isn't present.
1
u/Top-Cauliflower-1808 16h ago
Your loop uses or so it keeps running while either condition is true. A match sets numMatch to True but incCount <= maxNum is still true so the loop continues to the end. Use and instead and also check incCount < len(numList) to avoid an index error.
1
u/Baner-Fournadet 4h ago
swap `or` for `and`. right now youre telling python to keep looping if either condition is true, so it won't stop until both become false.
0
u/Jello_Penguin_2956 19h 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
0
u/Hanuman_2007 18h ago
The issue is that you used or instead of and in your while condition! With while numMatch == False or incCount <= maxNum:, as soon as numMatch becomes True, the first part becomes False, but incCount <= 9 is still True—so the or condition stays True and the loop keeps running all the way to 10. Change or to and so the loop stops as soon as either condition fails: python while not numMatch and incCount <= maxNum: Use code with caution. (Bonus tip: You can also write while not numMatch: instead of numMatch == False, which is cleaner in Python!)
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.
-2
u/lailoken503 18h ago
Thanks for helping me slay this dragon, even if it turns out to be a little toy dragon.
I had the impression that 'or' meant one or the other, and reading the comments about the incrementor count conditions has shown me the errors of my way.
3
u/Buttleston 18h ago
it does - it means "if one or the other is true"
"and" means "both are true"
It works in english. It will rain today if it's cloudy and the temperature drops - it has to both cloudy and the temp has to drop
it will rain today if it's cloudy or the temperature drops - it will rain if either is true
1
u/scoberry5 11h ago
Pretend for a minute we're talking about "if" instead of "while." Slightly easier to understand, but exactly the same idea.
Let's say I say "The lawn will be wet if the sprinklers have come on or it has rained."
You know that it rained. Is the lawn wet? (Yes. Doesn't matter whether the sprinklers have come on.)
You know that the sprinklers have come on. Is the lawn wet? (Yes. Doesn't matter whether it has rained.)
That's the usage of "or" in use, and it's the same in the "while" case:
"Do this work while there's still work in the queue or it's not 5 o'clock yet."
That would be a strange thing to say, right, because it means that if there's no work in the queue but it's not 5 yet, you keep doing it. You don't want that. You want "and" there.
-1
u/Langdon_St_Ives 18h ago
It does mean one or the other, but you're negating the compound statement, and when you then distribute the negation that turns the or into an and. See my other top level comment for more details about your case.
9
u/Langdon_St_Ives 18h 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.