Mat*_*s24 1 python user-interface nested-loops python-2.7
是否有一种有效的方法可以通过让用户在他们想要突破的特定时间(例如按键)简单地提供输入来打破嵌套循环?我在循环中有条件语句,我可以用它来打破循环,但是如果我只是想在任何时候停止循环但仍然希望其余的代码运行,有没有一种简单的方法来做到这一点?为了澄清动机,我想做一些事情:
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
Run Code Online (Sandbox Code Playgroud)
我考虑过使用原始输入,但不希望循环等待用户的每次迭代,因为会有很多次迭代.在使用不同的软件包时,似乎有一些建议的解决方案,但即使这些也似乎只是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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |