Skip to main content
 首页 » 编程设计

python之使用用户输入打破嵌套循环

2025年05月04日24qlqwjy

是否有一种有效的方法可以让用户在他们想要跳出的特定时间提供输入(例如,按一个键)来跳出嵌套循环?我在循环本身中有条件语句,我可以用它来打破循环,但是例如,如果我只是想随时停止循环但仍然希望其余代码运行,是否有一种简单的方法可以做到这一点?为了阐明动机,我想做类似的事情:

for x in xrange(1000): 
    for y in xrange(1000): 
        for z in xrange(1000): 
            print x,y,z #function of loop 
            if (user_has_pressed_key) == True: #a user input that  
                                               #can come at any time 
                                               #but there should NOT be  
                                               #a prompt needed for each iteration to run 
                break 
        else: 
            continue 
        break 
    else: 
        continue 
    break 

我考虑过使用原始输入,但不希望循环等待用户的每次迭代,因为会有多次迭代。似乎有一些proposed solutions when using different packages ,但即使是这些似乎也只是 Windows 特有的。我在多台计算机上运行此代码,因此理想情况下希望它在不同的操作系统上运行。

请您参考如下方法:

如果用户发出 Ctrl+C 击键,您可以跳出嵌套循环,因为它会抛出 KeyboardInterrupt 异常:

try: 
    for x in xrange(1000): 
        for y in xrange(1000): 
            for z in xrange(1000): 
                print x,y,z #function of loop 
 
except KeyboardInterrupt: 
    print("Stopped nested loops")