简体   繁体   中英

Problems with boolean statement and if statement in python

def test():
    boo = True
    enter = int(raw_input("Enter something: "))
    if enter > 0:
        boo = False
        print "Did it work?!"
    else:
        print "Still working..."
    while boo == True:
        test()

test()

So this bit of code seems to only work if the first part of the if statement is met first try. aka if you enter -1 then 1 it continues to loop through the function. What am I doing wrong?

boo is a local variable. Every time you recursively call test() , that recursive call gets a new local variable boo that is independent of all parent functions calling it. As such, it is set to True at the beginning of the function.

Your calls look like this:

  • test() , boo = True , enter = 1, so while boo == True is true:

    • test() , boo = True , enter = -1, so while boo == True is false, returning
  • at this level, boo == True is still true , so we call test() again.

    • test() , boo = True , enter = -1, so while boo == True is false, returning

etc. ad nauseum.

You want to return boo :

def test():
    boo = True
    enter = int(raw_input("Enter something: "))
    if enter > 0:
        boo = False
        print "Did it work?!"
    else:
        print "Still working..."
    while boo:
        boo = test()
    return boo

Now when test() returns, you set boo in the calling function to False .

Note that == True is redundant, just test for boo itself in while boo .

It is really not a good idea to use recursion for user input. Just use a while loop:

while True:
    enter = int(raw_input("Enter something: "))
    if enter < 0:
        print "Did it work?!"
        break
    print "Still working..."

Combining a potentially infinite while loop with a recursive function is a very dangerous game. When you get to subsequent calls of test() , even if they work and exit out right away, your original call to test() will still loop forever. boo is never changed in the original function call just because it's changed in later ones.

Your code could be fixed this way:

def test():
    boo = True
    enter = int(raw_input("Enter something: "))
    if enter > 0:
        boo = False
        print "Did it work?!"
    else:
        print "Still working..."
    if boo == True:
        test()

But it would be even better this way:

def test():
    enter = int(raw_input("Enter something: "))
    while enter <= 0:
        print "Still working..."
        enter = int(raw_input("Enter something: "))
    print "Did it work?!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM