如何让raw_input重复直到我想退出?

时间:2009-11-23 06:36:17

标签: python raw-input

说我想这样使用raw_input

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

下:

if __name__=="__main__": 

我怎样才能让它重复多次,而不是每次运行程序时都重复一次? 另一个问题是编写什么代码可以满足条件“或空行退出(程序)”。

4 个答案:

答案 0 :(得分:6)

最好的:

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)

答案 1 :(得分:4)

while 1:
    choice=raw_input("Enter: ")
    if choice in ["Q","q"]: break
    print choice
    #do something else

答案 2 :(得分: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

答案 3 :(得分: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: ")