Как закончить функцию python

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

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

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

Источник

Как закончить функцию python

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

def имя_функции ([параметры]): инструкции return возвращаемое_значение

Определим простейшую функцию, которая возвращает значение:

def get_message(): return "Hello METANIT.COM"

Здесь после оператора return идет строка «Hello METANIT.COM» — это значение и будет возвращать функция get_message() .

Затем это результат функции можно присвоить переменной или использовать как обычное значение:

def get_message(): return "Hello METANIT.COM" message = get_message() # получаем результат функции get_message в переменную message print(message) # Hello METANIT.COM # можно напрямую передать результат функции get_message print(get_message()) # Hello METANIT.COM

После оператора return может идти и сложное вычислямое выражение, резлуьтат которого будет возвращаться из функции. Например, определим функцию, которая увеличивает число в два раза:

def double(number): return 2 * number

Здесь функция double будет возвращать результат выражения 2 * number :

def double(number): return 2 * number result1 = double(4) # result1 = 8 result2 = double(5) # result2 = 10 print(f"result1 = ") # result1 = 8 print(f"result2 = ") # result2 = 10

Или другой пример — получение суммы чисел:

def sum(a, b): return a + b result = sum(4, 6) # result = 0 print(f"sum(4, 6) = ") # sum(4, 6) = 10 print(f"sum(3, 5) = ") # sum(3, 5) = 8

Выход из функции

Оператор return не только возвращает значение, но и производит выход из функции. Поэтому он должен определяться после остальных инструкций. Например:

def get_message(): return "Hello METANIT.COM" print("End of the function") print(get_message())

С точки зрения синтаксиса данная функция корректна, однако ее инструкция print(«End of the function») не имеет смысла — она никогда не выполнится, так как до ее выполнения оператор return возвратит значение и произведет выход из функции.

Однако мы можем использовать оператор return и в таких функциях, которые не возвращают никакого значения. В этом случае после оператора return не ставится никакого возвращаемого значения. Типичная ситуация — в зависимости от опеределенных условий произвести выход из функции:

def print_person(name, age): if age > 120 or age < 1: print("Invalid age") return print(f"Name: Age: ") print_person("Tom", 22) print_person("Bob", -102)

Здесь функция print_person в качестве параметров принимает имя и возраст пользователя. Однако в функции вначале мы проверяем, соответствует ли возраст некоторому диапазону (меньше 120 и больше 0). Если возраст находится вне этого диапазона, то выводим сообщение о недопустимом возрасте и с помощью оператора return выходим из функции. После этого функция заканчивает свою работу.

Однако если возраст корректен, то выводим информацию о пользователе на консоль. Консольный вывод:

Name: Tom Age: 22 Invalid age

Источник

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

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

Источник

Читайте также:  Java date parse online
Оцените статью