简体   繁体   中英

Breaking out of nested loops with user input

Is there an efficient way to break out of a nested loop by having a user simply providing an input at the particular time they want to break out (eg press a key)? I have conditional statements in the loops themselves that I can use to break the loops, but if for example I simply want to stop the loops at any time yet still want the rest of the code to run, is there a simple way to do that? To clarify the motivation, I would like to do something like:

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

I have considered using raw input, but would not want the loops to wait each iteration for the user as there will be numerous iterations. There appear to be some proposed solutions when using different packages , but even these seem to only be Windows-specific. I am running this code on multiple computers so would ideally want it to function on different OS.

You can break out of the nested loops if the user issues a Ctrl + C keystroke, since it throws a KeyboardInterrupt exception:

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

If you want the loop to break whenever any key is pressed by the user, then you can try this import:

from msvcrt import getch
while True:
    key = getch()
    if (key is not None): 
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM