Reputation: 128
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
Upvotes: 0
Views: 1231
Reputation: 19144
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.
Upvotes: 1
Reputation: 1228
As variable scoping had been mentioned, try putting the if
statement in the while loop and declaring keepAlive before the while
.
Upvotes: 0