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

6 投票
4 回答
20245 浏览
提问于 2025-04-15 16:17

假设我想像这样使用 raw_input

code = raw_input("请输入你的三位字母代码,或者输入空行退出程序:")

在:

if __name__=="__main__": 

我该怎么做才能让它每次运行程序时都重复多次,而不是只执行一次呢?
还有一个问题是,怎样写代码才能满足“或者输入空行退出程序”的条件呢?

4 个回答

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
while 1:
    choice=raw_input("Enter: ")
    if choice in ["Q","q"]: break
    print choice
    #do something else

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

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)

撰写回答