Остановить работу функции python

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))
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.

Читайте также:  Php curl request with header

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 is ")
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 is ") except TypeError: print(f" does not have a length!")
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)
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)
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)
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()
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.

Читайте также:  Как сделать css кроссбраузерным

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
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!

Источник

Как остановить выполнение функции в Python?

Для остановки выполнения функции в Python можно использовать ключевой оператор return . Когда функция достигает этого оператора, она прекращает выполнение и возвращает указанное значение.

def func(): print('Часть функции, где код сработает') x = 11 return x # Функция возвращает значение переменной x и завершает свою работу. print('Эта часть функции - нет') y = 22 return y a = func() print(a) # => Часть функции, где код сработает # => 11 

Источник

Exit a Function in Python

Exit a Function in Python

  1. Implicit Return Type in Python
  2. Explicit Return Type in Python

Every program has some flow of execution. A flow is nothing but how the program is executed. The return statement is used to exit Python’s function, which can be used in many different cases inside the program. But the two most common ways where we use this statement are below.

  1. When we want to return a value from a function after it has exited or executed. And we will use the value later in the program.
def add(a, b):  return a+b  value = add(1,2) print(value) 

Here, it returns the value computed by a+b and then stores that value which is 3 , inside the value variable.

def add(a, b):   if(a == 0):  return  elif(b == 0):  return  else:  sum = a + b  return sum  value = add(0,2) print(value) 

Here, if the values of either a or b are 0 , it will directly return without calculating the numbers’ sum. If they are not 0 then only it will calculate and return the sum .

Читайте также:  Вставить в html часы

Now, if you implement this statement in your program, then depending upon where you have added this statement in your program, the program execution will change. Let’s see how it works.

Implicit Return Type in Python

Suppose we have a function inside which we have written using an if statement, then let’s see how the program behaves.

def solution():  name = "john"   if(name == "john"):  print('My name ',name)  solution() 

The solution() function takes no arguments. Inside it, we have a variable called name and then check its value matches the string john using the if statement. If it matches, we print the value of the name variable and then exit the function; otherwise, if the string doesn’t match, we will simply exit it without doing anything.

Here, you might think that since there is no return statement written in the code, there is no return statement present. Note that the return statement is not compulsory to write. Whenever you exit any Python function, it calls return with the value of None only if you have not specified the return statement. The value None means that the function has completed its execution and is returning nothing. If you have specified the return statement without any parameter, it is also the same as return None . If you don’t specify any return type inside a function, then that function will call a return statement. It is called an implicit return type in Python.

Explicit Return Type in Python

Whenever you add a return statement explicitly by yourself inside the code, the return type is called an explicit return type. There are many advantages of having an explicit return type, like you can pass a value computed by a function and store it inside a variable for later use or stop the execution of the function based on some conditions with the help of a return statement and so on. Let’s see an example of the explicit type in Python.

def Fibonacci(n):   if n  0:  print("Fibo of negative num does not exist")  elif n == 0:  return 0  elif n == 1 or n == 2:  return 1  else:  return Fibonacci(n-1) + Fibonacci(n-2)  print(Fibonacci(0)) 

This is a program for finding Fibonacci numbers. Notice how the code is return with the help of an explicit return statement. Here, the main thing to note is that we will directly return some value if the number passed to this function is 2 or lesser than 2 and exit the function ignoring the code written below that. We will only execute our main code (present inside the else block) only when the value passed to this function is greater than 2 .

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article - Python Function

Источник

Оцените статью