How to write a loop that can be terminated at any time in python?

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

Insert image description here

Insert image description here

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.
Insert image description here

2. Study notes

Insert image description here

3. Learning videos

Insert image description here

3. Essential manual for Python beginners

Insert image description here

4. Python practical cases

Insert image description here

5. Python crawler tips

picture

6. A complete set of resources for data analysis

Insert image description here

7. Python interview highlights

Insert image description here

Insert image description here

2. Resume template

Insert image description here
Insert image description here

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.

Insert image description here

Guess you like

Origin blog.csdn.net/xiqng17111342931/article/details/134991926