Exit a Python Program in 3 Easy Ways!

Exit A Python Program Thumbnail

Sometimes a program is written to be built and run forever but needs to be stopped when certain specific things happen. There are many methods in Python that help to stop or exit a program.

This tutorial will cover the different functions to exit a Python program.

Using the quit() function

The easiest way to quit a Python program is by using the built-in function quit(). The quit() function is provided by Python and can be used to exit a Python program quickly.

Syntax:

quit()

As soon as the system encounters the quit() function, it terminates the execution of the program completely.

Example:

for x in range(1,10):
    print(x*10)
    quit()

In the above code, we have used the quit() function inside a for loop to see if it terminates.

Output:

10

Here we can see that the first iteration completes and then the quit() function executes immediately which ends the program, hence the statement print only once.

Python sys.exit() function

Another useful function to exit a Python program is sys.exit() provided by the sys module which can be imported directly into Python programs.

An additional feature of this function is that it can take a string as an argument and print it after it is executed. The sys.exit() function can be used at any point in time without worrying about corruption in the code.

Syntax:

sys.exit(argument)

Let us have a look at the below example to understand sys.exit() function.

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

There are many more functions in the sys module that you might find useful in learning, click here to see the full guide on this.

Using exit() function

Apart from the above-mentioned techniques, we can use another in-built exit()function to quit and come out of the execution loop of a program in Python. This function is similar to the function quit().

Syntax:

exit()

Example:

for x in range(1,10):
    print(x*10)
    exit()

As already mentioned, the exit() function can be considered an alternative to the quit() function, which enables us to terminate the execution of a Python program.

Output:

10

After the first iteration completes and the exit() function executes immediately which ends the program, hence the statement print only once.

Conclusion

In this tutorial, we have learned three methods to exit a Python program, among them sys.exit() is more beneficial as it can print a final message by taking it as an argument, but it is complex as you need to import the sys module in order to use it whereas the quit() and exit() functions can be called directly. You can choose one according to your need.

Reference

https://stackoverflow.com/questions/19782075/how-to-stop-terminate-a-python-script-from-running/