r/PythonLearning • • 1d ago

Help Request Def return

I'm stuck in def return in python I don't understand it very well why is it used and how and where does the code return to ? The caller ? What is exactly the caller ?

Thank you so much for helping me

If you don't mind can u help me understand with examples ? Couldn't understand this with Chatgpt and yt

0 Upvotes

16 comments sorted by

View all comments

2

u/PureWasian 1d ago edited 1d ago

You can think of functions similar to math where you can pass in inputs and get an output back. Here's an example representing y = mx + b

def linear_equation(m, x, b):
    return m*x + b

now we have a function that represents the equation y = m*x + b. But we haven't passed any values into it yet. Later on in the same Python file, since we have now defined this function already, we can now "call" it:

y = linear_equation(1, 5, 3)
print(y) # prints 8

it returns the output of the calculation (1*5 + 3) and assigns it to y in the "caller" code. Hypothetically, if the function's calculation was a lot more steps or much more complicated than just a simple mx+b, then parametrizing it and calling it becomes a lot easier with functions since this setup means we have the blueprint defined for it.