Home > other >  how to exit this loop in python
how to exit this loop in python

Time:04-29

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related