r/learnpython • • 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: True

The second condition triggers but not the Boolean, and I'm stumped as to why.

5 Upvotes

20 comments sorted by

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.

3

u/lailoken503 16h 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.

1

u/Telinary 14h ago edited 14h ago

I had thought OR was one or the other, which is normal in life

Well it is (unless you mean exclusive or) it is just that you are writing a condition for when it should keep running not one for when it should stop. So if either are true it keeps running.

while numMatch == False or incCount == maxNum:

So let's look at this. It will keep running if numMatch stays false, makes sense because you haven't found a match yet.

But what does " incCount == maxNum" do? First it is only relevant if numMatch is already true. In that case if the loop count happens to be exactly the max it keeps running for one more step. I don't think that is the behavior you want. 

Either there is always a match and you do not need a second condition or there isn't and this code won't stop at the maxNum.

1

u/realmauer01 8h 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.

1

u/Dancing-umbra 16h ago

While not the best looking, I will sometimes approximate a do until loop with:

while True:
    foo()
    if breaking_condition:
        break

The other benefit of the do... Until... Is that the contents of the loop will always run at least once.

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

7

u/wosmo 19h ago

I suspect that wants to be an 'and'.

2

u/duskharborings 17h ago

yep, as long as one side stays true the whole loop just keeps marching on

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:
        break

If 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.