[Tutor] (no subject)

Steven D'Aprano steve at pearwood.info
Sun Mar 31 04:02:57 CEST 2013


On 31/03/13 12:49, Soliman, Yasmin wrote:
> Hello everyone. How can I get a program to stop only when the user enters 'Quit'?

First you need a program that never stops. Most programs automatically stop when they're done, so you need to have a program which repeats forever. Do you have that?

Then you need to add code that asks the user for input.

Then you need to add code that compares that input to "Quit".

And finally you need to add code that exits when they match.


# Step 1. A program that never stops.
while True:
     print "Hello world"  # Or do something useful.


# Step 2. Add code that repeatedly gets input from the user.
while True:
     print "Hello world"
     response = raw_input("What do you want to do? ")


# Step 3. Inspect that input.
while True:
     print "Hello world"
     response = raw_input("What do you want to do? ")
     if response == "Quit":
         print "Exiting now" # Well, not now, but soon.


# Step 4. Exit when done.
while True:
     print "Hello world"
     response = raw_input("What do you want to do? ")
     if response == "Quit":
         break  # escapes from the while loop



Step 5. Make the program useful. That's up to you.





-- 
Steven


More information about the Tutor mailing list