How to End Program in Python? 

TechDyer

Python has grown to be one of the most widely used programming languages in the world thanks to its straightforward syntax and strong features. It is crucial to understand How to end Program in Python correctly, regardless of experience level or level of expertise. Even though it might seem like a simple task, knowing the different ways that programs terminate can help you write code that is more effective and manageable. We’ll look at various methods for gracefully terminating a Python program in this guide.

End Program in Python via KeyboardInterrupt

In Python, one way to terminate a program is to manually interrupt it with the keyboard. On Windows, you can stop Python scripts by pressing Ctrl + C, and on Unix, you can pause (freeze) the Python script’s execution by pressing Ctrl + Z. If you hit CTRL + C while a script is running on the terminal, it will stop and throw an exception. Let’s examine the example below to gain a deeper understanding of it.

Code:

# Python code to demonstrate 

# How to end the Python program 

# Through keyboard interruption

# importing time

import time

i = 0

# running an infinite loop

while True:

    # sleep for 1 second

    # in each iteration

    time.sleep(1)

    print(“The value of i = “,i)

    i += 1

Output:

The value of i = 0

The value of i = 1

See also  Online Java Compiler: Simplify Your Coding Process

The value of i = 2

The value of i = 3

The value of i = 4

The value of i = 5

The value of i = 6

The value of i = 7

The value of i = 8

The value of i = 9

Traceback (most recent call last):

  File “E:\Python\key.py”, line 3, in <module>

    time.sleep(1)

KeyboardInterrupt

^C

End Program in Python via Exceptions and sys. exit()

Whenever your program encounters an error, you may want to terminate it. This can be accomplished by combining sys. exit() with exceptions.

import sys

try:

    user_input = int(input(“Enter a number: “))

except ValueError:

    sys.exit(“You did not enter a number.”)

End Program in Python via exit() Command

Python comes with a built-in function called exit(), which is defined in the site.py module. It can be thought of as a stand-in for the quit() command, which we will discover later in the article. Because the exit() command only functions once the site modules have loaded, production-level codes shouldn’t use it. The exit() command raises the SystemExit exception. In this instance, exit(0) indicates a problem-free, clean exit, while exit(1) indicates a problem that arose during the program’s termination.

Syntax: The syntax for exit() is quite simple. Since Python already has it built in, we don’t need to import or install any additional modules. Furthermore, it requires no parameters.

Code:

# Python program to demonstrate the 

# How to end the Python program 

# through the exit() command in Python

for x in range(5,10):

    print(“The value of x = “,x)

    # Use the exit() command to exit from the code

    exit()

# this line would not be reached 

# since the code will terminate earlier 

# in the loop itself

print(“Hey! I’m after exit()”)

See also  Unraveling Inheritance in CSS: Mastering the Cascade

Output:

The value of x = 5

End Program in Python Through os._exit() Function

Under certain conditions, a Python program can be ended with a specific status using the os._exit() command without triggering any cleaning handlers, flushing studio buffers, etc. To use this function, you must import the os module before using os. exit() to end the program. After the os. fork() system call, the child processes typically use the os. exit() function. It should be noted that this is an unusual method of ending a process.

Code:

# Python program to demonstrate the 

# How to end the Python program 

# through the os._exit(0) command in Python

# importing os module

import os

for number in range(100):

    if number == 7:

        print(exit)

        # exiting the program with status code 0

        os._exit(0)

    print(“The number is = “,number)

Output:

The number is = 0

The number is = 1

The number is = 2

The number is = 3

The number is = 4

The number is = 5

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

How to End Program in Python by using the quit() Command

One Python function that can be used instead of the exit() function is quit(). The termination of Python codes is also accomplished by an internal Python function. The system closes the Python file to end the Python program when it encounters the quit() function. The site.py module must also be imported to use the quit() command. The quit() command raises the SystemExit exception in the background.

Syntax: The syntax for quit() is quite simple. Since it is built into Python, we do not need to import or install any additional modules. Furthermore, no parameters are required.

See also  How to Fix Not Secure Website in Chrome? Complete Guide

Code:

# Python program to demonstrate the 

# How to end the Python program 

# through the quit() command in Python

i  = 25

while i < 100:

    print(f”The value of i = {i}”)

    i += 1

    # quit command to exit from the code

    quit()

# this line would not be reached 

# since the code will terminate earlier 

# in the loop itself

print(“Hey! I’m after quit()”)

Output:

The value of i = 25

The Graceful Exit: Finally

The final keyword in Python can be used to designate a block of code that will always be run, regardless of whether an error occurred or the program is about to terminate. It’s similar to tidying up a room before leaving it. Even though you may not be able to choose when to leave, you can still make sure the room is cleaned when you leave.

Code:

try:

    user_input = int(input(“Enter a number: “))

except ValueError:

    sys.exit(“You did not enter a number.”)

finally:

    print(“This is the end of the program.”)

Conclusion

Writing solid and maintainable code requires knowing How to end Program in Python correctly. Whether you’re handling errors, implementing clean exits from loops, or ending the program under certain circumstances, picking the appropriate approach guarantees consistent and effective behavior from your code. To improve the overall quality of your code and gain proficiency in program termination, practice applying these techniques to your Python projects.

Read more

Share This Article
Follow:
I'm a tech enthusiast and content writer at TechDyer.com. With a passion for simplifying complex tech concepts, delivers engaging content to readers. Follow for insightful updates on the latest in technology.
Leave a comment

Leave a Reply

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