Exit program

Python Exit program

To exit the program in python, the user can directly make the use of Ctrl+C control which totally terminates the program. However, if the user wishes to handle it within the code, there are certain functions in python for this. They are quit(), exit(), sys.exit() etc which helps the user in terminating the program through the python code. Below is how you can use these in-built Python functions:

1.) quit() in Python

This function completely terminates the execution of a program. It can only be used in the interpreter in a real-world situation and not anywhere inside the program. It tends to raise an exception called SystemExit exception. Below is a python code to illustrate the use of quit() in python:

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


The output of the above code will be:

10

2.) exit() in Phyton

This function should also reside inside the interpreter. It is almost similar to the quit() function in python but is more user-friendly than that. It lets the user come out of the loop in the execution which in-turn terminates the execution of the program. This can only be made into execution when the module of the code is about to run. Below is a python program to illustrate the use of exit().

for i in range(5): 
    if i == 3:
        print(exit) 
        exit() 
    print(i)


The output of this python program will be:

0
1
2
Use exit() or Ctrl-D (i.e. EOF) to exit

3.) sys.exit([args]) in Python

This function in python is much better than using quit() and exit() functions. If the user gets an output a zero, it means he is successful in terminating the program. This method does not only work for integers but strings as well. To use this, the coder needs to import sys for the execution, as shown in the code below. Check out the code to understand the use of sys.exit() in python and how it differs from using quit() and exit().

import sys 
students = 20
if students < 18:
    sys.exit("Number less than 18")     
else: 
    print("Number is not less than 18")


The output of the above python code for termination of the program will be:

Number is not less than 18

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!