0

Return function in Python?

Hey, I just started learning Python, and I dont really understand the return function. I tried googling it, but the answers are a little too complicated for me to understand, considering that I JUST started learning. I especially struggle to understand how the print function differs from return? Can anyone try to explain it in the simplest way possible?

30th Dec 2018, 4:54 PM
Izabella
Izabella - avatar
4 Answers
+ 1
Izabella, do you understand what a function is, what it does, what it is good for? (You're still quite at the start of the tutorial.)
30th Dec 2018, 6:17 PM
HonFu
HonFu - avatar
+ 3
Okay, I see where you're at. A function is like a drawer where you put code into; whenever you need it, you take it out. def func(): That's the drawer. Now we put some code there, indenting, as we have to in Python: print('Hello World') This code is not executed even once! You have to explicitly call the function to play the code: func() And then the code is executed. Whatever happens in that function, after the function ends, it will be deleted. Say you want your function to calculate something, and you want to use it in your code later after the function has ended, then you need to preserve the result somehow. And that's what return does: def x_times_x(x): return x*x By putting that x into the parentheses, you define that you have to give a value to your function when you call it. The function takes that value, multiplies it and sends the result back to the main program to the place where you called the function. result=x_times_x(5) ...leads to the variable result being 25.
30th Dec 2018, 8:02 PM
HonFu
HonFu - avatar
+ 1
Hey all, thanks for the help! I think I understand it now!!
1st Jan 2019, 3:02 AM
Izabella
Izabella - avatar
0
HonFu ive been googling a bit and i also have encode, but youre right - im still at the very start. So i’m not 100% sure i actually understand it, but its like a way to make coding easier, so for example when you define a function you can lot a lot of stuff into it, and then when you recall the function it does what you made it do earlier, without you having to do it all over again? Ok so I’m still so new to this that it’s hard to explain, but i hope you understand what i mean, and hopefully my understanding of a function is not completely off
30th Dec 2018, 7:29 PM
Izabella
Izabella - avatar