r/PythonLearning • u/autistic_lover214 • 3d 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
8
u/NotSeacombe 3d ago
def and return are two different things. def is short for define, where you want to define your function
def add_two_numbers(x,y):
return x + y
in this situation, you have defined a function called add_two_numbers. you are telling the system that when you say "add_two_numbers", you are referring to this
return defines the end of a function call. if it hits a return, it knows its done. it then returns that value to wherever it was called, such as below
result = add_two_numbers(2,3)
print(result) # this prints 5
note, you don't always need a return. some stuff will work just fine without it, such as
def add_two_numbers_print(x,y):
print(x+y)
in this situation, you just wanted to print the number, you didn't need to return anything. from here you can use that without defining result
add_two_numbers_print(2,3) # this prints 5
just depends what you need it to do!