简体   繁体   中英

how to exit this loop in python

why does break doesn't work? I want the code to stop when I click the specific key

import keyboard


def loop():
    x = 1
    while True:
        print(x)
        x = x+1


while True:
    if keyboard.is_pressed('q'):
        print("q pressed")
        break
    loop()

This is because you are in the function loop(). There is no break statement in the loop. Maybe try this?

import keyboard


def loop():
    x = 1
    while True:
        print(x)
        x = x+1
        if keyboard.is_pressed('q'):
            print("q pressed")
            break
    

      
loop()

This is because the break isn't inside the loop (function), to fix this we put the condition inside the desired loop.

import keyboard


def loop():
    x = 1
    while True:
        if keyboard.is_pressed('q'):
            print("q pressed")
            break
        print(x)
        x = x+1


while True:
    loop()

I presume the second loop is necessary, to not close the program.

Here you can just simply solve the error just by making 1 change.

Just delete the while True command in last when you call loop() function. That is the only thing that is causing an issue.

import keyboard
    
    def loop():
        x = 1
        while True:
            if keyboard.is_pressed("q"):
                print("\n q pressed")
                break
            print(x)
            x = x+1
    
    loop()

FYI: You can add some delay if you want counts to slow down. For that you will have to import time library.

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