-4

This is a program to make the text print with each word beginning with a capital letter no matter how the input is.

So my question is why do we use return here :

def format_name(f_name, l_name):
    formatted_f_name = f_name.title()
    formatted_l_name = l_name.title()
    return f"{formatted_f_name}{formatted_l_name}"

print(format_name("ABcDeF", "Xy"))

when I could just do this :

def format_name(f_name, l_name):
    formatted_f_name = f_name.title()
    formatted_l_name = l_name.title()
    print(f"{formatted_f_name}{formatted_l_name}")
    
format_name("ABcDeF", "Xy")

What scenarios would it be really useful in?

AfterFray
  • 1,751
  • 3
  • 17
  • 22
  • 2
    Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – ruohola Nov 24 '21 at 06:58
  • On simple example: What if you want to send a mail with your formatted text? If you return the text from the function you can use the returned value. If you print the text in the function you can't. – Matthias Nov 24 '21 at 08:38

1 Answers1

0

The main reason that the return keyword is used is so that the value of the function can be stored for later, rather than just printing it out and losing it.

e.g.

def someFunction(a,b):
  return(a+b/3)
a=someFunction(1,2)

This means that what the function does can be stored for later. For example:

print(a)
print(a/2)
print(a+3) 

return statements don't just replace print, they allow you to do a load of other things by storing the end value (the value inside return) in a variable. print()ing in a function, however, only allows us to print the variable to the console, not allowing us to do anything or use the value that it prints. e.g.

def someFunction(a,b):
  print(a+b/3)
a=someFunction(1,2)
print(a)

Although the function already prints the value off for you, the variable I assigned it to shows that the function is practically useless unless you run it a bunch of times. a will print off None in the case above.

Hope that was helpful.

Agent Biscutt
  • 712
  • 4
  • 17