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

View all comments

-2

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