FAQ: Introduction to Functions - Returns

Maybe, and we can bypass it. However, sometimes it makes perfect sense to declare the variable so the return value has a concept that a reader can comprehend immediately.

current_year - birth_year

can be reasonably expected to be perceived as one’s age, but do we know that is what the programmer meant?

age = current_year - birth_year

Now there is no guess work or inference.

return age

It won’t affect the code since the age variable is immediately marked for garbage collection once the function is exited.

1 Like

def calculate_age(current_year, birth_year):

age = current_year - birth_year

return age

my_age = calculate_age(2049, 1993)

Hello,

Why can’t I define a function to a variable? When I do I get an error. Thanks in advance!

Be sure that line is not indented in any way. It should be tight to the left edge of the code.

1 Like

You’re right, it was indented. :stuck_out_tongue: Thanks for the help!

1 Like

Why did they have us convert the ages to strings? Aren’t strings reserved for words?

Strings aren’t reserved to words, they’re just a sequence of characters (as of python3-unicode characters and we’ll ignore binary encodings for now). I’m assuming they were converted to strings so as to make it easy to print and combine them other strings of text you added. For the example the following code would throw an error-

test = "this_string" + 3 

Much easier and more readable just to convert it to a string "string" + str(3) rather than play around with binary.

1 Like

“return g” in the code assigns the function “calculate _age” the value of an operation mentioned in g ??

so no matter how many new variables i create calling the function with different inputs , the base operation remains the same till i define the function again with a new operater and return ?