How to Kill a While Loop with a Keystroke in Python?
Last Updated :
06 Mar, 2024
Loops are fundamental structures in Python programming for executing a block of code repeatedly until a certain condition is met. However, there are scenarios where you might want to terminate a while loop prematurely, especially when you want to give the user the ability to interrupt the loop with a keystroke. In this article, we’ll explore some simple methods to achieve this using Python.
Kill a While Loop with a Keystroke in Python
Below are some of the methods to kill a While Loop with a keystroke in Python:
Kill a While Loop with a Keystroke Using KeyboardInterrupt
In this example, below code a variable num
with 11 and enters an infinite loop, printing and incrementing num
by 2 in each iteration until an even number is encountered. The loop is slowed down by one second. If interrupted by a keyboard interrupt (Ctrl+C), it passes and continues with the program, printing “Continuing with the program.”.
Python3
import time
try :
num = 11
while True :
if num % 2 = = 0 :
break
print (num)
num = num + 2
time.sleep( 1 )
except KeyboardInterrupt:
pass
print ( "Continuing with the program" )
|
Output:
11
13
15
17
Continuing with the program
Kill a While Loop with a Keystroke Using keyboard
Library
The keyboard
library provides a straightforward way to capture keyboard events, making it an excellent choice for handling keystrokes within your Python programs. First, install the library using the following command:
pip install keyboard
In this example, below code uses the keyboard
library to create an infinite loop (main_loop
) where “Working…” is printed continuously. It checks for the ‘q’ key press using keyboard.is_pressed('q')
, and if detected, it prints “Loop terminated by user” and breaks out of the loop.
Python3
import keyboard
def main_loop():
while True :
print ( "Working..." )
if keyboard.is_pressed( 'q' ):
print ( "Loop terminated by user." )
break
if __name__ = = "__main__" :
main_loop()
|
Output:
Working...
Working...
Working...
Working...
Working...
Working...
Working...
Loop terminated by user.
Kill a While Loop with a Keystroke Utilizing msvcrt
Module
The msvcrt
module, specific to Windows systems, allows capturing keystrokes without the need for external libraries. Here’s an example of using it to terminate a while loop: This method works on Windows and is more suitable for scenarios where external libraries are not preferred.
Python3
import msvcrt
def main_loop():
while True :
print ( "Working..." )
if msvcrt.kbhit():
key = msvcrt.getch().decode()
if key = = 'q' :
print ( "Loop terminated by user." )
break
if __name__ = = "__main__" :
main_loop()
|
Output:
Working...
Working...
Working...
Working...
Working...
Working...
Working...
Loop terminated by user.
Share your thoughts in the comments
Please Login to comment...