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

96ethanh
  • 128
  • 2
  • 6
  • 1
    [Variable scope](http://stackoverflow.com/questions/370357/python-variable-scope-error) – Luigi Nov 08 '14 at 23:01
  • 1
    The `keepAlive` *inside* `main` is unrelated to the one outside. Read up on Python's scoping http://stackoverflow.com/q/291978/3001761 – jonrsharpe Nov 08 '14 at 23:02

2 Answers2

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.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
0

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

T.Woody
  • 1,142
  • 2
  • 11
  • 25