Что такое return в python
Перейти к содержимому

Что такое return в python

  • автор:

The return Statement in Python

Trending Articles on Technical and Non Technical topics

The return statement in python is an extremely useful statement used to return the flow of program from the function to the function caller. The keyword return is used to write the return statement.

Since everything in python is an object the return value can be any object such as – numeric (int, float, double) or collections (list, tuple, dictionary) or user defined functions and classes or packages.

The return statement has the following features —

  • Return statement cannot be used outside the function.
  • Any code written after return statement is called dead code as it will never be executed.
  • Return statement can pass any value implicitly or explicitly, if no value is given then None is returned.

Syntax

Following is the syntax of return statement in python —

def some_function(parameters): return print(some_function)

Example

Following is the simple example of return statement —

def welcome(str): return str + " from TutorialsPoint" print(welcome("Good morning"))

Output

Following is an output of the above code —

Good morning from TutorialsPoint

The return statement is useful in multiple ways and the below sections discuss the different use case of return statement along with examples.

Use of return statement in Python

Functions are core of any programming language as they allow for code modularity thereby reducing program complexity. Functions can display the result within itself, but it makes the program complex, hence it is best to pass the result from all the functions to a common place.

It is in this scenario that the return statement is useful as it terminates the currently executing function and passes control of the program to the statement that invoked the function.

Example

In the below code the sum_fibonacci function is used to calculate the sum of the first 15 terms in the fibonacci series. After calculating the sum, it prints and returns the sum to the sum_result variable. This is to show that printing inside the function and returning the value give the same output.

# Defining function to calculate sum of Fibonacci series def sum_fibonacci(terms): first_term = 0 second_term = 1 sum_series = 0 # Finding the sum of first 15 terms of Fibonacci series for i in range(0, terms): sum_series = sum_series + first_term next_term = first_term + second_term first_term = second_term second_term = next_term # Printing the sum inside the function print("Sum of Fibonacci series inside the function is = <>".format(sum_series)) # Returning the sum using return statement return sum_series # Invoking the sum_fibonacci function sum_result = sum_fibonacci(15) print("Sum of Fibonacci series outside the function is = <>".format(sum_result))

Output

The output shows that the sum from inside the function using print statement and the sum from outside the function using return statement is equal.

Sum of Fibonacci series inside the function is = 986 Sum of Fibonacci series outside the function is = 986

Returning a function using return statement

In python, functions are first class objects which means that they can be stored in a variable or can be passed as an argument to another function. Since functions are objects, return statement can be used to return a function as a value from another function. Functions that return a function or take a function as an argument are called higher-order functions.

Example

In this example, finding_sum function contains another function – add inside it. The finding_sum function is called first and receives the first number as the parameter. The add function receives the second number as parameter and returns the sum of the two numbers to finding_sum function. The finding_sum function then returns the add function as a value to sum variable.

# Defining function to return sum of two numbers # Function to get the first number def finding_sum(num1): # Function to get the second number def add(num2): return num1 + num2 # return sum of numbers to add function return add # return value present in add function to finding_sum function sum = finding_sum(5) print("The sum of the two numbers is: <>".format(sum(10)))

Output

The output of the program gives the sum of the two numbers – 5 and 10.

The sum of the two numbers is: 15

Returning None using return statement

Functions in python always return a value, even if the return statement is not written explicitly. Hence, python does not have procedures, which in other programming languages are functions without a return statement. If a return statement does not return a result or is omitted from a function, then python will implicitly return default value of None.

Explicit calling of return None should only be considered if the program contains multiple return statement to let other programmers know the termination point of the function.

Example

The program below gives a perfect illustration of using return None. In this program the check_prime() function is used to check if a list contains any prime numbers. If the list contains prime numbers, then all the prime numbers present in the list are printed. However, if there are no prime numbers in the list then None is returned, since this program contains multiple return statements, hence None is called explicitly.

def check_prime(list): prime_list = [] for i in list: counter = 0 for j in range(1, i): if i % j == 0: counter = counter + 1 if counter == 1: prime_list.append(i) if len(prime_list): return prime_list else: return None list = [4, 6, 8, 10, 12] print("The prime numbers in the list are: <>".format(check_prime(list)))

Output

The output prints None since there are no prime numbers in the list.

The prime numbers in the list are: [4]

Returning multiple values using return statement

The return statement in python can also be used to return multiple values from a single function using a ‘,’ to separate the values. This feature can be especially useful when multiple calculations need to be performed on the same dataset without changing the original dataset. The result from the return statement is a tuple of the values.

Example

In this example the built-in functions of the statistics library are used to compute the mean, median and mode which are returned using a single return statement showing how multiple values can be returned from a function.

import statistics as stat # Defining function to perform different statistical calculations def finding_stats(data): return stat.mean(data), stat.median(data), stat.mode(data) # returning multiple values list_numbers = [5, 7, 13, 17, 17, 19, 33, 47, 83, 89] print("The mean, median and mode of the data is: <>".format(finding_stats(list_numbers)))

Output

The output gives the mean, median and mode of the dataset with type as tuple.

The mean, median and mode of the data is: (33, 18.0, 17)

How does len function actually work for files?

Contents of the file: One two three Upon running this simple program I get as output: The input file is 14 bytes long Qutestion: I don’t understand, if my file has written in it only 11 characters(One two three) how can len return me 14 bytes and not just simply 11?(what’s with the bytes by the way?) In the python interpreter if I type s = «One two three» and then len(s) I get 13, so I am very confused.

What is the purpose of the return statement? How is it different from printing?

What does the return statement do? How should it be used in Python? How does return differ from print ?

See also

Often, people try to use print in a loop inside a function in order to see multiple values, and want to be able to use the results from outside. They need to be returned, but return exits the function the first time. See How can I use `return` to get back multiple values from a loop? Can I put them in a list?. Often, beginners will write a function that ultimately print s something rather than return ing it, and then also try to print the result, resulting in an unexpected None . See Why is «None» printed after my function’s output?. Occasionally in 3.x, people try to assign the result of print to a name, or use it in another expression, like input(print(‘prompt:’)) . In 3.x, print is a function, so this is not a syntax error, but it returns None rather than what was displayed. See Why does the print function return None?. Occasionally, people write code that tries to print the result from a recursive call, rather than return ing it properly. Just as if the function were merely called, this does not work to propagate the value back through the recursion. See Why does my recursive function return None?. Consider How do I get a result (output) from a function? How can I use the result later? for questions that are simply about how to use return , without considering print .

30.6k 9 9 gold badges 64 64 silver badges 86 86 bronze badges
asked Aug 20, 2011 at 2:44
Hitesh Kumar Hitesh Kumar
1,213 2 2 gold badges 9 9 silver badges 4 4 bronze badges

This is an important reference question, but there are many related questions that might be a better target for closing duplicates. Sorry about the length of the «see-also» section, but this time it really seems necessary.

Sep 14, 2022 at 13:28

15 Answers 15

The print() function writes, i.e., «prints», a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here’s a function utilizing both print() and return :

def foo(): print("hello from inside of foo") return 1 

Now you can run code that calls foo, like so:

if __name__ == '__main__': print("going to call foo") x = foo() print("called foo") print("foo returned " + str(x)) 

If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:

going to call foo hello from inside foo called foo foo returned 1 

I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.

Here’s another example from the interpreter that demonstrates that:

>>> def foo(): . print("hello within foo") . return 1 . >>> foo() hello within foo 1 >>> def bar(): . return 10 * foo() . >>> bar() hello within foo 10 

You can see that when foo() is called from bar() , 1 isn’t written to the console. Instead it is used to calculate the value returned from bar() .

print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.

30.6k 9 9 gold badges 64 64 silver badges 86 86 bronze badges
answered Aug 20, 2011 at 2:47
Nathan Hughes Nathan Hughes
95.4k 20 20 gold badges 187 187 silver badges 279 279 bronze badges

Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can’t be used by another function.

I’ll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input?

def square(n): return n * n def add_one(n): return n + 1 print square(12) # square(12) is the same as writing 144 print add_one(square(12)) print add_one(144) #These both have the same output 

There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.

Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program

It might be a bit hard to grasp what this means if you’re just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.

Just remember that when you use return you are basically saying «A call to this function is the same as writing the value that gets returned»

Python will actually insert a return value for you if you decline to put in your own, it’s called «None», and it’s a special type that simply means nothing, or null.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *