🐍 Exit Function in Python
Understanding Program Termination
1. What is an Exit Function?
When Python encounters exit(), the program stops executing the remaining statements in that execution environment.
2. Syntax
exit()
A message can also be supplied:
exit("Program terminated")
3. Simple Example
print("Statement 1")
exit()
print("Statement 2")
Output
"Statement 2" is not executed because the program terminates when exit() is reached.
4. How exit() Works
5. Exit Using a Condition
An exit function is often used when a particular condition is satisfied.
age = 15
if age < 18:
print("You are not eligible.")
exit()
print("You are eligible.")
Output
Since the age is less than 18, the program terminates
before reaching the final print().
6. Exit with a Message
marks = 25
if marks < 30:
exit("Student has failed.")
print("Student has passed.")
Output
7. sys.exit()
import sys
print("Program started")
sys.exit()
print("Program ended")
Output
8. exit(), quit() and sys.exit()
| Function | Purpose | Typical Use |
|---|---|---|
| exit() | Terminates program execution. | Interactive Python use / simple examples. |
| quit() | Terminates the Python interpreter. | Interactive Python sessions. |
| sys.exit() | Raises SystemExit to terminate execution. | Python programs and scripts. |
9. Important Difference
exit() and quit() are mainly
intended as convenience helpers for interactive use.
In a Python script, it is better practice to use:
import sys
sys.exit()
10. exit() vs return
| exit() | return |
|---|---|
| Terminates the program/interpreter execution. | Leaves the current function. |
| Can stop the whole program. | Does not normally terminate the whole program. |
| Used for program termination. | Used to send a value back from a function. |
11. Example: return vs exit()
def check_number(n):
if n < 0:
return "Negative number"
return "Positive number"
print(check_number(-5))
print("Program continues...")
Output
Here, return only exits the function. The rest of the program continues.
12. Applications of Exit
Stop execution when invalid input is detected.
Stop execution when authentication fails.
Terminate execution when a critical condition occurs.
Exit a menu-driven program when the user chooses Exit.
13. Interactive Demonstration
Select an example to understand program termination.
14. Important Points for Examination
- exit() is used to terminate program execution.
- quit() is another interactive convenience for leaving Python.
- sys.exit() is commonly used in Python scripts for explicit program termination.
- return exits a function, not normally the entire program.
- Statements after an exit operation are not executed.
15. Quick Summary
exit()
exit("message")
import sys
sys.exit()
exit() → Stop program execution
return → Leave the current function
sys.exit() → Explicit program termination
No comments:
Post a Comment