Solving problem is about exposing yourself to as many situations as possible like What is the purpose of the return statement? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about What is the purpose of the return statement?, which can be followed any time. Take easy to follow this discuss.
What is the simple basic explanation of what the return statement is, how to use it in Python?
And what is the difference between it and 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
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 from within foo") return 1 ... foo() hello from within foo 1 def bar(): return 10 * foo() ... bar() hello from 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
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.
I think the dictionary is your best reference here
return gives something back or replies to the caller of the function while print produces text
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.
In python, we start defining a function with “def” and generally, but not necessarily, end the function with “return”.
A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2
Now, the code of this function will be:
def A_function (x): return x + 2
After defining the function, you can use that for any variable and get result. Such as:
print A_function (2) 4
We could just write the code slightly differently, such as:
def A_function (x): y = x + 2 return y print A_function (2)
That would also give “4”.
Now, we can even use this code:
def A_function (x): x = x + 2 return x print A_function (2)
That would also give 4. See, that the “x” beside return actually means (x+2), not x of “A_function(x)”.
I guess from this simple example, you would understand the meaning of return command.
This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.
In line number 4:
def ret(n): if n > 9: temp = "two digits" return temp #Line 4 else: temp = "one digit" return temp #Line 8 print("return statement") ret(10)
After the conditional statement gets executed the
ret() function gets terminated due to
return temp (line 4).
print("return statement") does not get executed.
This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.
To bring out the difference between print and return:
def ret(n): if n > 9: print("two digits") return "two digits" else : print("one digit") return "one digit" ret(25)
two digits 'two digits'
return means, “output this value from this function”.
In the Python REPL, a function return will be output to the screen by default (this isn’t quite the same as print).
This is an example of print:
"foonbar" #just assigning a variable. No output n #the value is output, but it is in a "raw form" 'foonbar' print n #the n is now a newline foo bar >>>n =
This is an example of return:
def getN(): return "foonbar" ... getN() #When this isn't assigned to something, it is just output 'foonbar' n = getN() # assigning a variable to the return value. No output n #the value is output, but it is in a "raw form" 'foonbar' print n #the n is now a newline foo bar >>>
Just to add to @Nathan Hughes’s excellent answer:
return statement can be used as a kind of control flow. By putting one (or more)
return statements in the middle of a function, we can say: “stop executing this function. We’ve either got what we wanted or something’s gone wrong!”
Here’s an example:
def make_3_characters_long(some_string): if len(some_string) == 3: return False if str(some_string) != some_string: return "Not a string!" if len(some_string) < 3: return ''.join(some_string,'x')[:,3] return some_string[:,3] threechars = make_3_characters_long('xyz') if threechars: print threechars else: print "threechars is already 3 characters long!" threechars is already 3 characters long!
See the Code Style section of the Python Guide for more advice on this way of using
Difference between “return” and “print” can also be found in the following example:
def bigger(a, b): if a > b: return a elif a <b: return b else: return a
The above code will give correct results for all inputs.
def bigger(a, b): if a > b: print a elif a <b: print b else: print a
NOTE: This will fail for many test cases.
: Test case input: 3, 8.
Expected result: 8
: Test case input: 4, 3.
Expected result: 4
: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases