Back to articles list Articles
7 minutes read

How Do You End Scripts in Python?

Programming means giving instructions to a computer on how to perform a task. These instructions are written using a programming language. An organized sequence of such instructions is called a script.

As a programmer, your main job is to write scripts (i.e. programs). However, you also need to know how scripts can end. In this article, we will go over different ways a Python script can end. There is no prerequisite knowledge for this article, but it is better if you are familiar with basic Python terms.

If you are new to programming or plan to start learning it, Python is the best way to start your programming adventure. It is an easy and intuitive language, and the code is as understandable as plain English.

Scripts are written to perform a task; they are supposed to end after the task is completed. If a script never ends, we have a serious problem. For instance, if there is an infinite while loop in the script, the code theoretically never ends and might require an external interruption.

It is important to note that an infinite while loop might be created on purpose. A script can be written to create a service that is supposed to run forever. In this case, the infinite loop is intentional and there is no problem with that.

The end of a Python script can be frustrating or satisfying, depending on the result. If the script does what it is supposed to do, then it’s awesome. On the other hand, if it ends by raising an exception or throwing an error, then we will not be very happy.

5 Ways to End Python Scripts

Let’s start with the most common and obvious case: a script ends when there are no more lines to execute.

1. All the Lines Are Executed

The following is a simple script that prints the names in the list, along with the number of characters they contain:

mylist = ["Jane", "John", "Ashley", "Matt"]

for name in mylist:
    print(name, len(name))

Output:

Jane 4
John 4
Ashley 6
Matt 4

The script does its job and ends. We all are happy.

Python scripts, or scripts in any other programming language, can perform a wide range of operations. In many cases, we cannot visually check the results. For instance, the job of a script might be reading data from a database, doing a set of transformations, and writing the transformed data to another database.

In scripts that perform a series of operations, it’s a good practice to keep a log file or add print statements after each individual task. It lets us do simple debugging in case of a problem. We can also check the log file or read the output of print statements to make sure the operation was completed successfully.

2. Uncaught Exception

It usually takes several iterations to write a script that runs without an error; it’s rare to get it right the first time. Thus, a common way that a script ends is an uncaught exception; this means there is an error in the script.

When writing scripts, we can think of some possible issues and place try-except blocks in the script to handle them. These are the exceptions that we are able to catch. The other ones can be considered uncaught exceptions.

Consider the following code:

mylist = ["Jane", "John", 2, "Max"]

for i in mylist:
   print(f"The length of {i} is {len(i)}")

Output:

The length of Jane is 4
The length of John is 4
Traceback (most recent call last):
  File "", line 4, in 
TypeError: object of type 'int' has no len()

The code prints the length of each item in the list. It executes without a problem until the third item, which is an integer. Since we cannot apply the len function to an integer, the script throws an error and ends.

We can make the script continue by adding a try-except block.

mylist = ["Jane", "John", 2, "Max"]

for i in mylist:
    try:
        print(f"The length of {i} is {len(i)}")
    except TypeError:
        print(f"{i} does not have a length!")

Output:

The length of Jane is 4
The length of John is 4
2 does not have a length!
The length of Max is 3

What does this try-except block do?

  • It prints the f-string that includes the values and their lengths.
  • If the execution in the try block returns a TypeError, it is caught in the except block.
  • The script continues the execution.

The script still ends, but without an error. This case is an example of what we explained in the first section.

3. sys.exit()

The sys module is part of the Python standard library. It provides system-specific parameters and functions.

One of the functions in the sys module is exit, which simply exits Python. Although the exit behavior is the same, the output might be slightly different depending on the environment. For instance, the following block of code is executed in the PyCharm IDE:

import sys
number = 29

if number < 30:
    sys.exit()
else:
    print(number)

It provides this output:

Process finished with exit code 0

Now, let’s run the same code in Jupyter Notebook:

import sys
number = 29

if number < 30:
    sys.exit()
else:
    print(number)

Here’s the output:

An exception has occurred, use %tb to see the full traceback.

SystemExit

The sys.exit function accepts an optional argument that can be used to output an error message. The default value is 0, which indicates successful termination; any nonzero value is an abnormal termination.

We can also pass a non-integer object as the optional argument:

import sys
number = 29

if number < 30:
    sys.exit("The number is less than 30.")
else:
    print(number)

Output:

An exception has occurred, use %tb to see the full traceback.

SystemExit: The number is less than 30.

The sys.exit() function raises the SystemExit exception, so the cleanup functions used in the final clause of a try-except-finally block will work. In other words, we can catch the exception and handle the necessary cleanup operations or tasks.

4. exit() and quit()

The exit() and quit() functions are built into Python for terminating a script. They can be used interchangeably.

The following script prints the integers in the range from 0 to 10. If the value becomes 3, it exits Python:

for i in range(10):
   print(i)
   if i == 4:
       exit()

Output

0
1
2
3

Process finished with exit code 0

Note: The  exit() function also raises an exception, but it is not intercepted (unlike sys.exit()). Therefore, it is better to use the sys.exit() function in production code to terminate Python scripts.

5. External Interruption

Another way to terminate a Python script is to interrupt it manually using the keyboard. Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts.

If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

Traceback (most recent call last):
  File "", line 2, in 
KeyboardInterrupt

We can implement a try-except block in the script to do a system exit in case of a KeyboardInterrupt exception. Consider the following script that prints the integers in the given range.

for i in range(1000000):
   print(i)

We may want to exit Python if the script is terminated by using Ctrl + C while its running. The following block of code catches the KeyboardInterrupt exception and performs a system exit.

for i in range(1000000):
   try:
       print(i)
   except KeyboardInterrupt:
       print("Program terminated manually!")
       raise SystemExit

Output:

Program terminated manually!
Process finished with exit code 0

We have covered 5 different ways a Python script can end. They all are quite simple and easy to implement.

Python is one of the most preferred programming languages. Start your Python journey with our beginner-friendly Learn Programming with Python track. It consists of 5 interactive Python courses that gradually increase in complexity. Plus, it’s all interactive; our online console lets you instantly test everything you learn. It is a great way to practice and it makes learning more fun.

What's more, you don't need to install or set anything up on your computer. You only need to be willing to learn; we'll take care of the rest. Wait no more – start learning Python today!