r/learnpython • u/lailoken503 • 4d 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.
7
Upvotes
10
u/Langdon_St_Ives 4d 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.
18
u/Buttleston 4d 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
u/Temporary_Pie2733 4d ago
numMatchis an antipattern in the first place. If you want to exit the loop early, usebreakinstead of setting a flag to be checked later. Also, To iterate over a list, use aforloop instead of a manually incremented index.If
maxnumisn’t just the last valid index intonumList, iterate over a slice:2
u/PureWasian 4d 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 4d 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 4d 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 4d 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 4d 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/Rare-Pay9795 4d ago
The loop uses
or, so it keeps going as long as either condition is true. After the match,numMatch == Falseis False, butincCount <= maxNumis 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: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)becomesnot a and not b.Small extras:
random.randintalready returns an int, so theint()isn't needed, andfor n in numList:with abreakon match is the more usual Python pattern for this.-2
u/lailoken503 4d 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.