Hey, all. In this article, we will be having a look at some functions that can be considered as handy to perform this task — Exit a Python program.
Technique 1: Using quit() function
The in-built quit() function
offered by the Python functions, can be used to exit a Python program.
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()
As seen above, after the first iteration of the for loop, the interpreter encounters the quit() function and terminates the program.
Output:
10
Technique 2: Python sys.exit() function
Python sys module
contains an in-built function to exit the program and come out of the execution process — sys.exit()
function.
The sys.exit() function can be used at any point of time without having to worry about the 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
Technique 3: Using exit() function
Apart from the above mentioned techniques, we can use the in-built exit() function
to quit and come out of the execution loop of the program in Python.
Syntax:
exit()
Example:
for x in range(1,10): print(x*10) exit()
The exit() function can be considered as an alternative to the quit() function, which enables us to terminate the execution of the program.
Output:
10
Conclusion
By this, we have come to the end of this topic. The exit()
and quit()
functions cannot be used in the operational and production codes. Because, these two functions can be implemented only if the site module is imported.
Thus, out of the above mentioned methods, the most preferred method is sys.exit()
method.
Feel free to comment below, in case you come across any question.
Till then, Happy Learning!!