Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your problem here is scope - <code>exit</code> is local to the function <code>exit()</code> so doesn't affect the variable <code>exit</code> in the loop scope.</p> <p>A better solution is this:</p> <pre><code>exit = False while not exit: option = raw_input("What would you like to do?") if option == "exit": exit = True </code></pre> <p>Or simply:</p> <pre><code>while True: option = raw_input("What would you like to do?") if option == "exit": break </code></pre> <p>Note the use of <code>True</code> and <code>False</code> over <code>1</code> and <code>0</code> - this is more pythonic, as what you mean here is truth values, not integers. I also changed to compare to the string <code>"exit"</code>, as I presumed that was what you wanted, not comparing the user input to the value of <code>exit</code>.</p> <p>If your problem is you want to have the same scope, you might want to make your code part of a class.</p> <pre><code>class Doer: #Naturally, give it a real name based on it's purpose. def __init__(self): self.exit = False while not self.exit: option = raw_input("What would you like to do?") if option == "exit": self.exit() def exit(self): self.exit = True </code></pre> <p>Here <code>exit</code> is an instance variable (hence being accessed from <code>self</code>) and therefore both times we are referencing the same variable.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload