0

I'm running into an issue with the following python 3.x code in which the while(keepAlive): continues, even after keepAlive is false. When the user enters "1", Killing Program... is displayed but while loop continues. I'm familiar with other languages, but just starting out with python. It seems like I must have made a simple mistake... I'd appreciate it if someone could point it out.

keepAlive = True

def main():
    if(input("Enter 1 to end program") == "1"):
        print("Killing program...")
        keepAlive = False

while(keepAlive):
    main()

Thanks

2

2 Answers 2

1

Currently, the module keepAlive and the local keepAlive within main are two independent names. To tie them together, declare keepAlive within main to be global. The following works.

keepAlive = True

def main():
    global keepAlive
    if(input("Enter 1 to end program") == "1"):
        print("Killing program...")
        keepAlive = False

while(keepAlive):
    main()

Look up 'global' in the Python doc index and you should find an explanation.

Sign up to request clarification or add additional context in comments.

Comments

0

As variable scoping had been mentioned, try putting the if statement in the while loop and declaring keepAlive before the while.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.