While loops are used to repeatedly execute a block of code until a condition is met. But what if you want the user to stop the loop manually, say by pressing a key? Then you can do so by pressing a key. This article covers three simple ways to break a while loop using a keystroke:
- Using KeyboardInterrupt
- Using keyboard Library
- Utilizing msvcrt Module
Let's discuss them one by one:
Method 1: Using KeyboardInterrupt (Ctrl+C)
This method allows you to manually stop the loop by pressing Ctrl+C.
import time
try:
num = 11
while True:
if num % 2 == 0:
break
print(num)
num = num + 2
time.sleep(1) # Wait 1 second before next iteration
except KeyboardInterrupt:
pass
print("Continuing with the program")
Output:
11
13
15
17
Continuing with the program
Explanation:
- try...except KeyboardInterrupt catches manual interruption (Ctrl+C).
- loop prints odd numbers and stops once an even number is found or interrupted.
Method 2: Using the keyboard Library
This approach allows the user to press a specific key (like q) to exit the loop. But to implement this in our code we need to first install the keyboard library using this command:
pip install keyboardExample:
import keyboard
def main_loop():
while True:
print("Working...")
# Press 'q' to exit
if keyboard.is_pressed('q'):
print("Loop terminated by user.")
break
if __name__ == "__main__":
main_loop()
Output:
Working...
Working...
Working...
Working...
Loop terminated by user.
Method 3: Using msvcrt Module (Windows Only)
For Windows users, this method captures key presses without extra libraries.
import msvcrt
def main_loop():
while True:
print("Working...")
# Check if any key is pressed
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...
Loop terminated by user.
Explanation:
- msvcrt.kbhit() checks for any key press.
- msvcrt.getch() captures the pressed key (e.g., 'q') to break the loop.
Also read: KeyboardInterrupt, keyboard library.