How to let a raw_input repeat until I want to quit?
Asked Answered
S

4

6

Say I want to use raw_input like this:

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

under:

if __name__=="__main__": 

How can I let it repeat multiple times rather than just once every time I run the program?
Another question is to write what code can satisfy the condition "or a blank line to quit (the program)".

Sunken answered 23/11, 2009 at 6:36 Comment(0)
Z
6

best:

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's %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)
Zoologist answered 23/11, 2009 at 6:58 Comment(0)
D
3
while 1:
    choice=raw_input("Enter: ")
    if choice in ["Q","q"]: break
    print choice
    #do something else
Dyane answered 23/11, 2009 at 7:17 Comment(0)
T
1
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
Thursby answered 16/10, 2013 at 2:5 Comment(0)
E
0
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: ")
Efferent answered 23/11, 2009 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.