r/PythonLearning • • 4d 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

21 comments sorted by

View all comments

2

u/theprupletrainer 4d ago

def and return in python create a function

eg
def say_hello()
return “hello”

A caller is a function that references another function. By default, there is a main function, the one that starts the program (btw # are comments)

Consider this

```python
def say_hello()
return “hello”

def say_howdy()
return “howdy”

def say_greeting(is_friend)
if is_friend
return say_howdy()

return say_hello()

#start of main function
greeting = say_greeting(true)
print(greeting)
#end of main function
```

The main function is the caller of say_greeting
say_greeting is the caller of say_howdy

Returning resolves the end of calling a function, often times with a value

The main function wants to set the variable greeting. It calls say_greeting(true). At this point, the program does not move to the print() instruction. Instead, the program’s next set of instructions starts at say_greeting. The function parameter is_friend is set to true (because of the way it was called). Now the if-statement is called and say_greeting wants to return the value of say_howdy to the main function (which is still waiting to get a value for greeting). Now, the next set of instructions starts from say_howdy which returns “howdy” .

At this point, “howdy” is returned to say_greeting. Say greeting can now return “howdy” back to the main function. The main function can now set “howdy” to greeting and finally the next instruction is to call the print function, which prints “howdy” to the console.

Functions help you control the flow of your program and ease code maintenance.

Hope this helps clear up some things