A2oz

How to Stop Python Execution?

Published in Programming 2 mins read

You can stop the execution of a Python program in several ways, depending on the situation:

1. Using Keyboard Interrupts

  • Press Ctrl+C: This is the most common way to interrupt a running Python program. It sends a KeyboardInterrupt signal to the program, causing it to stop.
  • Example:
      while True:
          print("Running...")

    Pressing Ctrl+C while this program is running will interrupt it.

2. Using the sys.exit() Function

  • Import the sys module: import sys

  • Call sys.exit(): This function immediately terminates the program. You can also pass an exit code as an argument, which can be used to signal the program's exit status.

  • Example:

      import sys
    
      print("This program will exit now.")
      sys.exit(0)  # Exit with a code of 0, indicating successful termination.

3. Using break Statement (Within Loops)

  • Use break inside a loop: This statement immediately exits the current loop and continues execution from the next statement after the loop.
  • Example:
      for i in range(10):
          print(i)
          if i == 5:
              break

    This program will print numbers from 0 to 5, and then stop.

4. Using quit() Function (Within Interactive Mode)

  • Use quit() in the interactive interpreter: This function exits the interactive Python session.
  • Example:
      >>> print("Hello!")
      Hello!
      >>> quit()
      >>> 

    Typing quit() in the interactive mode will exit the session.

These are the most common ways to stop Python execution. Choose the method that best suits your specific situation and coding context.

Related Articles