FAQ: Introduction to Functions - Returns

age is not a global variable, only a return value from the function. You could do this…

age = calculate_age(2021, 1993)
print (age)

thanks so much! so is it safe to safe calling out age in this exercise was completely pointless? just trying to understand the utility of why it was included in the instructions.

1 Like

While it may be superfluous in production code, it is not pointless for this example. It does have a point by way of describing the difference being evaluated.

Hello there,

I think I got how return syntax works. Let me recap it in few steps:

  • You define a function
  • You define the action of the function inside the body
  • You call the action of the function
  • The result gets saved with return
  • You can than call the results of the function via return syntax for different variables

To better understand the whole problematic here I tried is to do same thing still using a function but this time without using the “return” syntax.

def calculate_age(birth_year1, birth_year2, current_year=2049):
my_age = current_year - birth_year1
dads_age = current_year - birth_year2
print(“I am " + str(my_age) + " years old and my dad is " + str(dads_age) + " years old”)

calculate_age(1993, 1953)

And it works fine. I than realized that we can not call variables that are inside the function outside.

The difference with return is that we can pull these calculations outside of the function and assign it to their own variables which can be later used trough other commands. Return also simplifies the code as well, because washout return you have to use different variables for birth year. Now imagine when you need to calculate age of your mother, sister and for 100 of people more.

Can we get the same result print(“I am " + str(my_age) + " years old and my dad is " + str(dads_age) + " years old”) with it being outside the function in any way without the return syntax?

I know that it would be a longer procedure and that is why we use the the return syntax, but I am just curious and it will help me to even better understand the problematic here.

Kind regards