【问题标题】:Program Looping:Making a certain statement loop forever in Python程序循环:在 Python 中使某个语句永远循环
【发布时间】:2014-12-07 05:48:42
【问题描述】:

我找到的其他问题的答案没有帮助

while 1 == 1:
    do = raw_input('What would you like to do?')

在上面的示例中,您可以看到代码是为了让某些东西永远循环,例如:

if do == 'x':
    print 'y'
elif do == 'z':
    print 'a'

所以这个'if'语句已经执行,我希望'raw_input'再次执行,以便该人可以输入其他内容并且程序再次继续。 我不想把整个程序放在一个 真时: 程序或 而 1 != 2: 声明。只是干净的语法。 谢谢!

【问题讨论】:

  • 如果你的程序只这样做,那为什么不把整个事情包装在一个while 1==1(又名while True)循环中呢?
  • 这只是一个示例程序。
  • 如果你想在 Python 中创建一个无限循环,通常的方法是使用while True:。它肯定比 while 1==1: 或 while 1!=2:` 更干净,后者非常难看。如果你想要一个没有深度嵌套代码块的干净的程序,那么将你的程序分解为函数。

标签: python python-2.7 loops infinite-loop nested-loops


【解决方案1】:

通常你会这样做直到满足某个条件,例如,用户键入q 退出;否则它只是一个无限循环,你需要强制退出整个程序。

试试这个逻辑:

result = raw_input('What would you like to do? Type q to quit: ')

while result.lower() != 'q':
    if result == 'x':
       print 'y'
    if result == 'z':
       print 'a'
    result = raw_input('What would you like to do? Type q to quit: ')
print('Quitting. Good bye!')

【讨论】:

    【解决方案2】:
    def user_input():
    
        do = raw_input('What would you like to do?')
    
        if do == 'x':
            print 'y'
            user_input()
    
        elif do == 'z':
            print 'a'
            user_input()
    
        elif do =='quit':
            print 'exiting user input'
    
        else:
            user_input()
    
    user_input()
    

    上面使用了一些递归调用,不如 while 语句简洁,但如果您希望避免使用 while 语句,则可以使用。

    【讨论】:

    • 是的,它确实避免了使用while,但这是否足以证明使用递归?请记住,Python 不会优化尾调用递归,并且它有递归限制,因此应尽可能避免 Python 中的递归。
    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2021-03-20
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多