Hey, everybody. I started functions a few days ago in Python Crash Course. I like this chapter, I understand a function’s purpose, but I’m not understanding the differences between print and return. I also have a question about assigning a variable to a function. I want to know what’s going on under the hood rather than just trying to memorize what I have to do in order for something to work. For example, from the book:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!"
It seems like “formatted_name” is used as a variable of the function for organization, being specific when the function is called rather than just calling the function(please tell me if this is correct). In this case I can’t just call the function though. Why?
In some examples I’ve seen, if I used print and no return, it will show the result and “None”. Other instances it will show the same result, but people have said it’s different under the hood. My book said I could have easily made a function shorter with the same result, but says this, “However, when you consider working with a large program that needs to store many first and last names separately, functions like get_formatted_name() become very useful. You store first and last names separately and then call this function whenever you want to display a full name”, after it showed this code:
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
I can get the same result without using return and not using any variables for the function, but it seems like using return is good for if I want to have different variables for the same function in a program (musician, painter, etc.).
For the one in the first example with the while loop, I can’t just using the function.
Can someone explain all this to a beginner programmer? People have helped me understand what goes on with print before here when it comes to a while loop, and now printing is throwing me off again.