theochenko
theochenko

Reputation: 21

while not expression and boolean understanding

I found this in order to generate random numbers.

def main():
    randomNumber = randint(1,100)
    found = False
    while not found:
        userGuess = input("")
        if userGuess == randomNumber:
          print "You win."
          found = True
        elif
          .....
        else
          .....

So my question is about 'while not found', I don't find this is instinctive. More instinctive but not working should be something like:

found = False
while found

--> the loop is working while found is false

Could someone explain this?

Upvotes: 2

Views: 9140

Answers (2)

Michael Geary
Michael Geary

Reputation: 28870

If while not found seems unintuitive, you should probably just get used to it. It's a common Python idiom and will seem very intuitive after a while (pun intended).

If you want more readable code, though, I would get rid of the found variable entirely and use break to terminate the loop:

def main():
    randomNumber = randint(1,100)
    while True:
        userGuess = input("")
        if userGuess == randomNumber:
            print "You win."
            break
        # Code here will run only if the break isn't executed.
        # You don't need the elif any more.

It is a matter of personal preference: some people like to use a flag variable to terminate a loop; I prefer the simplicity of an explicit break in code like this.

Upvotes: 1

ganzogo
ganzogo

Reputation: 2614

A while loop will execute while the given expression is True. In your case, the given expression is not found. Since found starts off as False, not found is of course True, hence the loop executes and will continue to execute until found is set to True, at which point not found will be False.

My advice would be to not rewrite this - it is actually very readable as it is. You are saying that while you have not found something, keep looking.

Upvotes: 3

Related Questions