How Exit Program Python: Easy Ways For Beginners

Solution 1: Use the quit() function in Python

Python’s built-in quit() method is utilized for the successful termination of a Python program.

When the system encounters the quit() function, the program terminates the entire execution.

Note: This function is not for production code and is only available for the Python interpreter.

Syntax:

quit()

Example:

for x in range(0,10):

  print(x*10)

  quit()

Output:

0

As seen above, the interpreter meets the quit() function after the first iteration of the for loop and ends the program.

You can also explore the how to end a program in Python tutorial to know more.

Solution 2: Use the sys.exit() function in Python

The sys.exit() function is an inbuilt function of the Python sys module that terminates the program and the execution process.

At any time, the sys.exit() method can be called without fear of code damage.

Syntax:

sys.exit(argument)

Example:

import sys

x = 50

if x != 100:

  sys.exit("Values do not match")

else:

  print("Validation of values completed!!")

Output:

Values do not match

In contrast to exit() and quit(), sys.exit() is acceptable for use in production programs because the sys module is always available.

The optional argument arg can either be an integer indicating the exit code or another object type.

Solution 3: Use the exit() function in Python

Python’s built-in exit() function can be used to exit and exit the program’s execution loop in addition to the techniques described above.

The exit() function can be viewed as an alternative to the quit() function, which terminates the current program execution.

Syntax:

exit()

Example:

for x in range(0,10):

  print(x*10)

  exit()

Output:

0

Remember:

The exit() and quit() functions are not available in the numerical and production code because these two functions are not applicable without importing the site module.

Consequently, of the aforementioned techniques, the sys.exit() method is the most preferable.

Solution 4: Use the os._exit(0) function in Python

The OS module in Python provides functions for operating system interaction.

The operating system is part of Python’s basic utility modules.

This module provides a portable method for utilizing capabilities depending on the operating system.

Python’s os._exit() method is used to exit a process without calling cleanup handlers, flushing stdio buffers, etc.

Example:

import os

pid = os.fork()

if pid > 0:

    print("\nThis is the main parent process")

    info = os.waitpid(pid, 0)

    if os.WIFEXITED(info[1]) :

        exit_code = os.WEXITSTATUS(info[1])

        print("Exit code of the child:",exit_code)

else:

    print("This is child process")

    print("PID of child process is :", os.getpid())

    print("Child is now exiting")

os._exit(os.EX_OK)

Typically, this procedure is invoked by child processes following the os.fork() system call.

The normal mechanism for terminating a process is the sys.exit(n) procedure.

Output:

This is the main parent process

This is child process

PID of child process is: 142

Child is now exiting

Exit code of the child: 0

The software spawns a child’s process and then exits using the os._exit() function once the child process has been completed.

Solution 5: Use the Keyboard Interrupt to force a system exit

The KeyBoardInterrupt exception applies when a user presses Ctrl+C or Ctrl+Z to interrupt a running Python script.

If the Python program does not catch the exception, it will terminate.

The exception can prevent Python from terminating when properly addressed.

SystemExit is a Python exception from Basn that can possibly end a program.

Example:

import time

try:

    count=0

    while 1==1:

        count=count+2

        print(f"Value of count {count}")

        time.sleep(1)

except KeyboardInterrupt:

    print("Raising SystemExit")

    raise SystemExit

The program uses a try-catch block to execute a loop that updates the count variable.

With proper handling of the KeyBoardInterrupt, the SystemExit exception will be able to end the program.

Output:

python .\exit.py

Value of count 2

Value of count 4

Value of count 6

Value of count 8

Value of count 10

Value of count 12

Raising SystemExit

Note: There is no distinct syntax for the KeyboardInterrupt exception in Python; the standard try and except block handles this exception.

The possibly problematic code within the try block is the raise keyword.

This happens when the Python interpreter automatically raises it, to raise the exception.

What does exit () do in Python?

Python’s built-in exit() method can be used to exit a running program. The exit() method should only be used by the interpreter.

It is a synonym for the quit() function and makes Python more user-friendly.

Moreover, you can use other methods to exit a program in Python.

For the Python exit program on Windows, Ctrl + C terminates Python scripts, but Ctrl + Z suspends (freezes) Python script execution on Unix.

When you press CTRL + C on the terminal while a script is running, the script terminates and raises an exception.

Is there an exit in Python?

To exit a Python program, we can use the built-in quit() method because this function completely ends the program.

This function only applies to the interpreter and never to the production code.

The Python site module also includes the exit() function.

This function performs the same action quit() and it adds these two functions to make Python more user-friendly.

Summary

In summary, this tutorial emphasizes Python exit program methods which you can use to exit a program in Python.

The methods of exiting a program in Python will help you in canceling the running Python script.

You may use built-in Python methods, and KeyBoard Interrupts to end or exit a program.

The application depends on your current program or the method you’re comfortable with.  

You may also check the Methods to Check if Python String Contains Substring.

Leave a Comment