SoFunction
Updated on 2025-03-03

How to terminate and open a dead loop in Python

Python terminates the dead loop and opens the dead loop

Unfortunately, there is no such method...but

There is nothing difficult in the world, I am afraid of those who are determined.

theory

  • Since there is no way to turn on and stop the dead loop separately, we need to use other methods
  • Use process management methods to implement
  • Use global variables to control whether it is a dead loop

Let me talk about the function of the program. Keep scrolling downward when needed, and stopping when not needed.

Start Code

Selected modules

time # No morethreading # Used to start a new threadpyautogui # for operating system guikeyboard # Used to listen for key events

Module installation will not be introduced

# 1. Open a new thread to execute the dead loop function so that it does not affect the control of the main process# 2. The main process controls a global variable to control the dead loop of the child processimport threading
import keyboard
import time
import pyautogui
# Module import# Stop for three seconds to move the mouse to the required window(3)
# Set global variable to trues=True


# Define the scrolling mouse wheel functiondef myscoll(a,b): 
    while s:
        (0.2)
        (-600)
        if s==False:
            break


# Define global variable modification functions and enable the second dead loopdef cahnge(keyevent):
    s1= # This is a keyboard function, to determine the name of the key press    # print(s1)
    # Global variables    global s
    if s1=="1":
    	# When the "1" button is pressed, the global variable changes to false and the dead loop stops        s=False
    if s1=="2":
    	# When the "2" button is pressed, the global variable changes to true        s=True
        # Start the child process        threading._start_new_thread(myscoll,(1,1,))      


    
# Start the child processthreading._start_new_thread(myscoll,(1,1,))
(cahnge)
# () Used as a blocking until something is pressed. If you don't write it, it will be blocked here. Press and execute the previous statement once, press the key "3" to stop blocking.("3")

Python breaks out of the dead loop

1. Common methods of jumping out

While judgment conditions:

         Loop statement

Exit the loop when the judgment condition is not met

2. The number of cycles is uncertain and the cycle method is out of the cycle

Add an if judgment condition in the while loop and use the break statement to jump out of the loop.

Right now:

while 1:
    num = input("Please enter the number:")
    name = input("Please enter your name:")
    line = [num, name]
    a=input("Enter q to exit! Any key to continue!!")
    if ()=='q':   //Enter a uppercase or lowercase q to exit the loop        print("Exited input!!")
        break

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.