Preface
You can use thekeyboard
library to listen for keyboard input and terminate the loop when a specified key is pressed. Here's a sample code that does what you describe:
import keyboard
import time
def print_loop():
while True:
print("1")
time.sleep(3)
print("2")
time.sleep(3)
# 检查是否有键盘输入
if keyboard.is_pressed('0') or keyboard.is_pressed('down'):
print("循环终止")
break
print_loop()
In this code, we use thekeyboard.is_pressed()
function to check whether a key on the keyboard is pressed. If the numeric key "0" or the direction key "↓" is pressed, a message is printed and the break
statement is used to jump out of the loop, thereby terminating the execution of the loop.
You need to make sure thekeyboard
library is installed before running the code. You can install it using the following command:
pip install keyboard
Please note that this code can only be run in the terminal and not in some integrated development environments (such as Jupyter Notebook) because the keyboard listening function may not work properly.
-END-
I have also compiled some introductory and advanced information on Python for you. If you need it, you can refer to the following information.
About Python technical reserves
Learning Python well is good whether you are getting a job or doing a side job to make money, but you still need to have a learning plan to learn Python. Finally, we share a complete set of Python learning materials to give some help to those who want to learn Python!
1. Python learning route
2. Basic learning of Python
1. Development tools
We will prepare you with the essential tools you need to use in the Python development process, including the latest version of PyCharm to install permanent activation tools.
2. Study notes
3. Learning videos
3. Essential manual for Python beginners
4. Python practical cases
5. Python crawler tips
6. A complete set of resources for data analysis
7. Python interview highlights
2. Resume template
Data collection
The complete set of Python learning materials mentioned above has been uploaded to CSDN official. If you need it, you can scan the CSDN official certification QR code below on WeChat and enter "receive materials" to get it.