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


Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ILikeToCode
Solution 2 Jonah
Solution 3 Mitul