Home > Software design >  Why does not the variable in the while loop, change the boolean from True to False?
Why does not the variable in the while loop, change the boolean from True to False?

Time:08-28

Why does not the variable check in the while loop, change the boolean from True to False?

def word_valid():
    words = input("Your word: ").upper()

    global check
    check = False
    return words

def main():
    check = True
    while check is True:
        words = word_valid()
    print(words) #Won't print out

if __name__ == '__main__':
    main()

CodePudding user response:

global refers to the global scope, but the check in main is local to main's scope. That is, the check you're mutating in word_valid is a different check to the one in main

Without thinking too much about how to do this nicely, you could return check

def word_valid():
    words = input("Your word: ").upper()

    check = False
    return words, check

def main():
    check = True
    while check is True:
        words, check = word_valid()
    print(words) #Won't print out

if __name__ == '__main__':
    main()
  • Related