Как выйти из функции python
Функция может возвращать результат. Для этого в функции используется оператор return , после которого указывается возвращаемое значение:
Определим простейшую функцию, которая возвращает значение:
Здесь после оператора return идет строка «Hello METANIT.COM» — это значение и будет возвращать функция get_message() .
Затем это результат функции можно присвоить переменной или использовать как обычное значение:
После оператора return может идти и сложное вычислямое выражение, резлуьтат которого будет возвращаться из функции. Например, определим функцию, которая увеличивает число в два раза:
Здесь функция double будет возвращать результат выражения 2 * number :
Или другой пример — получение суммы чисел:
Выход из функции
Оператор return не только возвращает значение, но и производит выход из функции. Поэтому он должен определяться после остальных инструкций. Например:
С точки зрения синтаксиса данная функция корректна, однако ее инструкция print(«End of the function») не имеет смысла — она никогда не выполнится, так как до ее выполнения оператор return возвратит значение и произведет выход из функции.
Однако мы можем использовать оператор return и в таких функциях, которые не возвращают никакого значения. В этом случае после оператора return не ставится никакого возвращаемого значения. Типичная ситуация — в зависимости от опеределенных условий произвести выход из функции:
Здесь функция print_person в качестве параметров принимает имя и возраст пользователя. Однако в функции вначале мы проверяем, соответствует ли возраст некоторому диапазону (меньше 120 и больше 0). Если возраст находится вне этого диапазона, то выводим сообщение о недопустимом возрасте и с помощью оператора return выходим из функции. После этого функция заканчивает свою работу.
Однако если возраст корректен, то выводим информацию о пользователе на консоль. Консольный вывод:
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?
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:
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 .
This will end the function, and you can even customize the «Error» message:
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.
Exit a Function 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.
Please enable JavaScript
- 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.
- When we want to stop the execution of the function at a given moment.
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.
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.
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.
Python: как остановить функцию?
Моя проблема в том, что если какое-то условие становится истинным (в функции check_winner) и функция end() выполняется, он вернется к компьютеру() или плееру(), потому что нет строки, которая говорит компьютеру прекратить выполнение проигрывателя ( ) или computer(). Как вы останавливаете функции в Python?
3 ответа
Простой оператор возврата будет «останавливаться» или возвращать функцию, в точном выражении, «возвращает» выполнение функции в точку, в которой была вызвана функция, — функция прекращается без дальнейших действий.
Это означает, что у вас может быть несколько мест в вашей функции, где она может вернуться. Вот так:
Выше — довольно простой пример. Я составил инструкцию для check_winner , используя score = 100 , чтобы обозначить игру.
Вам понадобится использовать аналогичный метод передачи score в check_winner , используя game_over = check_winner(score) . Затем вы можете создать оценку в начале вашей программы и передать ее до computer и player , как обрабатывается game_over .