I think this will be probably one of the most dumbests questions of all, but i'm not really understading very well the functions and one thing is about the use of "return"
So, let's imagine the simple example that I want to greet my function (by saying "Hi function!") and use a function for that.
So should I use the print statement in the function like this:
def hello_func (greeting):
print (f'{greeting} function!')
greeting = 'Hi'
hello_func(greeting)
Or should I return the value in the function:
def hello_func (greeting):
return (f'{greeting} function!')
greeting = 'Hi'
print (hello_func(greeting))
The output is the same (Hi function!)... so in this particular case it doesn't matter what I use or is there a "better" code?
Thank you.
CodePudding user response:
Returning would be a better practice.
CodePudding user response:
returning or printing both on your choice for this greet function.
there are times that you need to use function return value in other places; at that moment it's necessary to use return statement that you can use that function return value at another places.
CodePudding user response:
Functionally, the big difference is that in your second example, you can save the returned value into a variable. Then you can manipulate it however you want:
def hello_func (greeting):
return (f'{greeting} function!')
greeting = 'Hi'
result = hello_func(greeting) # Function is only called once
print(result) # Displays the result
print(result "!!!") # Does stuff with result
print(result "?????") # Does even more stuff with result
print(result == 'Hello') # Compares the result to something
newest_result = result "foo bar" # Creates a new variable based on result
print(newest_result) # Displays the new variable
This means that you only need to execute hello_func
once, then you save its result to a variable, which is then further processed by your program. This becomes even more crucial if hello_func
is an expensive function that takes a lot of time to execute.
The key question to ask when deciding whether to take your first or second approach is: do you only want to display the result on screen, or do you want to save the result to memory and use it later down on your program?