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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1781445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:02:38  来源:igfitidea点击:

How to let a raw_input repeat until I want to quit?

pythonraw-input

提问by timy

Say I want to use raw_inputlike this:

说我想这样使用raw_input

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

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)".

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

回答by Alex Martelli

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)

回答by ghostdog74

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

回答by Hyperboreus

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

回答by inspectorG4dget

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: ")