How to allow raw_input to repeat until I want to exit?

Let's say I want to use raw_input as follows:

code = raw_input("Please enter your three-letter code or a blank line to quit: ")

in:

 if __name__=="__main__": 

How can I let it repeat several times, and not once every time the program starts?
Another question is to write which code can satisfy the condition "or an empty line for exit (program)".

+6
python raw-input
source share
4 answers

the best thing:

 if __name__ == '__main__': while True: entered = raw_input("Please enter your three-letter code or leave a blank line to quit: ") if not entered: break if len(entered) != 3: print "%r is NOT three letters, it %d" % (entered, len(entered)) continue if not entered.isalpha(): print "%r are NOT all letters -- please enter exactly three letters, nothing else!" continue process(entered) 
+6
source share
 while 1: choice=raw_input("Enter: ") if choice in ["Q","q"]: break print choice #do something else 
+4
source share
 def myInput(): return raw_input("Please enter your three-letter code or a blank line to quit: ") for code in iter(myInput, ""): if len(code) != 3 or not code.isalpha(): print 'invalid code' continue #do something with the code 
+1
source share
 if __name__ == '__main__': input = raw_input("Please enter your three-letter code or leave a blank line to quit: ") while input: input = raw_input("Please enter your three-letter code or leave a blank line to quit: ") 
0
source share

All Articles