Python выйти из def

How to stop a function

My problem is that if a certain condition becomes true (in the function check_winner ) and function end() executes it will go back to computer() or player() because there’s no line that tells the computer to stop executing player() or computer() . How do you stop functions in Python?

I forgot to add 1 function (main) in the question, but I still have a problem, like others said return returns to a function that called the 2nd function (the one with return statement) so it will never stop, adding return to several places didn’t do anything and the program will still execute, where exactly do I need to write return?I want the program to go back to main() if the player wants to and if he doesn’t I want to completely stop the program.

5 Answers 5

A simple return statement will ‘stop’ or return the function; in precise terms, it ‘returns’ function execution to the point at which the function was called — the function is terminated without further action.

That means you could have a number of places throughout your function where it might return. Like this:

def player(): # do something here check_winner_variable = check_winner() # check something if check_winner_variable == '1': return second_test_variable = second_test() if second_test_variable == '1': return # let the computer do something computer() 

So I just need to add ‘return winner’ (or just return (None)?) before end() in the function check_winner?

Читайте также:  Эффект перекатывания

Yes,any point at which return is specified will terminate function execution and return to the calling code.

In this example, the line do_something_else() will not be executed if do_not_continue is True . Control will return, instead, to whichever function called some_function .

def some_function(): if do_not_continue: return # implicitly, this is the same as saying `return None` do_something_else() 

This will end the function, and you can even customize the «Error» message:

import sys def end(): if condition: # the player wants to play again: main() elif not condition: sys.exit("The player doesn't want to play again") #Right here 
def player(game_over): do something here game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false if not game_over: computer(game_over) #We are only going to do this if check_winner comes back as False def check_winner(): check something #here needs to be an if / then statement deciding if the game is over, return True if over, false if not if score == 100: return True else: return False def computer(game_over): do something here game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false if not game_over: player(game_over) #We are only going to do this if check_winner comes back as False game_over = False #We need a variable to hold wether the game is over or not, we'll start it out being false. player(game_over) #Start your loops, sending in the status of game_over 

Above is a pretty simple example. I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner , using game_over = check_winner(score) . Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

Источник

Python выйти из def

Функция может возвращать результат. Для этого в функции используется оператор 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

Источник

Как остановить выполнение функции в 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 .

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

Источник

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