How would I make a function where one variable (exit) determines whether a ‘while’ loop runs or not and be able to change it in a different function so that the while loop in the first function will stop
while exit == 0:
option = (raw_input("What would you like to do? "))
if option == exit:
exit()
def exit():
exit = 1
That is just an example of what I am trying to do.
When I try running it it doesnt leave the while loop and in doing so doesn’t end the program. How can I make it so that the while loop recognizes that exit is now 1 and leaves the loop?
Sorry if the question isn’t very good because this is my first time using stackoverflow to ask a question.
ADDITION: I want to kno how to change the variable across functions because I will be doing that in parts of the program. Also, I am going to be saving data before exit so that is why I have the ‘exit’ in a different function
Your problem here is scope –
exitis local to the functionexit()so doesn’t affect the variableexitin the loop scope.A better solution is this:
Or simply:
Note the use of
TrueandFalseover1and0– this is more pythonic, as what you mean here is truth values, not integers. I also changed to compare to the string"exit", as I presumed that was what you wanted, not comparing the user input to the value ofexit.If your problem is you want to have the same scope, you might want to make your code part of a class.
Here
exitis an instance variable (hence being accessed fromself) and therefore both times we are referencing the same variable.If your code is not a simplification of a more complex problem, this is largely overkill, as one of the first solutions would be more appropriate.