0
What is the purpose of return in python?
For example x = 1 def a(y): x = y return x*2 x*2 is returned, but not assigned to any variable, so what is the purpose of returning it?
5 Answers
+ 4
You seem to understand what return values are, so I'm not sure if I understand the point of your question. If nothing happens with the return value and there's no other function that "catches" the return value and does something with it, the return value will be lost. That's the case in your example. But that's true for every programming language, not just python. So it's the programmer's job to do something useful with the return value. Otherwise it's just a waste of time and memory to calculate it. You don't necessarily have to assign the return value to a variable, you can also just print it or use it in another function etc.
+ 3
Just to add to Anna ‘s answer:
If you were to call the function in your example with a simple...
a(10)
...statement, then the function is run with the answer returned, but nothing is done with it. This is pointless. But if you say...
x = a(10)
... then now x is assigned to the return value of your function and you can now use it for something else.
Another point, just in case you weren’t aware, if you were to add the statement...
print(x)
...after your function definition, it would give you 1 still. The x variable inside your function is ‘local’ only so it is different to your ‘global’ variable x that you set as 1 at the start. If you wanted a function that modifies your global variable x, you need...
def a(y):
global x #this statement means you can change your global variable x
...
Hope that makes sense and answers your question.
+ 2
you call funtion to return the value where you might need it.
for example you might have a string that has many special characters or profanity in it that you want to get rid of. you input the string as a variable for a function and the function will return the fixed text without them. after that you can further process the string for whatever purpose
+ 1
Looks like one of those creative-thinking quiz questions or possibly a demo from interactive mode.
The returned value prints in interactive mode.
Here is your code sent to the interactive Python interpreter. (I'm only doing this because you can't enter the console normally here)
It prints 64 without being told to print. Otherwise, unless this is some esoteric thing about bytecode, other answers apply.
import code
console=code.InteractiveConsole()
lines="""x=1
def a(y):
x=y
return x*2
a(32)
""".split("\n")
[console.push(lines[x]) for x in range(len(lines))]
# outputs 64
+ 1
Grr, I forgot. The other reason is to populate the variable named "_".
So after calling the above,
a(32) # outputs 64
_/4 # outputs 16.0



