FAQ: Introduction to Functions - Returns

This community-built FAQ covers the “Returns” exercise from the lesson “Introduction to Functions”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Returns

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: How can I enter my code into a python shell?

I thought it a good idea to practice passing variables as function params. I also have done a little bit of documentation practice for the function.
Next step, pass dict values as func. params!

my_yb = 1950
dad_yb = 1920
def calculate_age(current_year, birth_year):
  """here is some documentation"""
  age = current_year - birth_year
  return age

my_age = calculate_age(2018,my_yb)
dads_age = calculate_age(2018,dad_yb)



print("I am " + str(my_age) + "  years old and my dad is " + str(dads_age) +" years old")
help(calculate_age)
6 Likes

5 posts were merged into an existing topic: How does Return work?

3 posts were split to a new topic: How can I utilize return on the same line as the calculation?

So I was experimenting with using the input function to define the variables I am passing to the function but when I run it in the window I’m getting and EOFError

def calculate_age(current_year, birth_year):
  age = current_year - birth_year
  return age

current_year = int(input('What is the current year : '))
my_birth = int(input('What year were you born : '))
dads_birth = int(input('What year was your father born : '))


my_age = calculate_age(current_year, my_birth)
dads_age = calculate_age(current_year, dads_birth)

print('I am ' + str(my_age)+ ' years old and my dad is ' + str(dads_age) + ' years old')

Output:

What is the current year : Traceback (most recent call last):
  File "script.py", line 5, in <module>
    current_year = int(input('What is the current year : '))
EOFError: EOF when reading a line

Why is the variable ‘age’ defined in the function, but ‘age’ isn’t called in the rest of the script?

‘my_age’ is called and ‘dads_age’ is called. So, why even define ‘age = current_year - birth_year’ … how does python use this variable even if it isn’t called in the script?

age

2 Likes

But it is used in the return statement which is akin to,

return current_year - birth_year
2 Likes

I still don’t understand. Can you explain another way? What is the purpose of the ‘age’ variable?

1 Like

I have spent at least an hour trying to figure out the same thing!

1 Like

The function takes two parameters: current_year, and birth_year. That means when we wish to call up the function we will pass in two arguments, such as,

dads_age = calculate_age(2020, 1953)  #  67

The function computes the difference and assigns it to the variable, age. It is then returned to the caller. Variables inside a function are local only to the function and cannot be accessed outside, or after return. The value is passed along, though. That’s what will be assigned to dads_age, above.

2 Likes

Maybe I missed the explanation of why we have to use +str() ??
I understand that it is to convert an integer into a string but I don’t understand why we have to do that in this exercise,
why can’t I use
print ( " I am " + my_age …directly…?..since it seems that we did that in previous exercises.
Maybe it was explained at some point but it is not clear to me.
Thanks for the help

The issue is that the two items you are trying to concatenate in your example are a string: “I am” and my_age which is an integer. Even without a print statement this would throw an error. They are stored in a different way* and cannot be concatenated without casting the integer value as a string: "I am " + str(my_age)

  • If you’re still curious about this and it’s not something you’ve come across before it might be worth doing a little background reading on how different data types, integers, floats, strings etc. are stored in binary.

The confusion may come from the that in previous assignments you can use statements like print(my_age) which work without explicit type casting. Under the hood I believe print actually makes use of the repr() function or similar which would effectively cast the value as a string to be printed in your console.
Since there’s nothing to state this happens without looking up the documentation it can be a source of confusion.

A little info on repr()-
https://docs.python.org/3/library/functions.html#repr

2 Likes

The key then is that they are stored in different ways so it needs to be cast as a string.
Thank you for claryfing!, this is very helpful.

1 Like

2.

Outside of the function, call calculate_age with values 2049 ( current_year ) and 1993 ( birth_year ) and save the value to a variable called my_age .

Forgive my lack of understanding, but I really think this is poorly written, can someone attempt to dissemble the task, is it not to give it a ‘default’, like it was described previously? and when you see the solution it (in my mind) certainly does not correspond to the task given

def foo(a, b):
    return a - b

print (foo(2049, 2001))    # this line is outside of the function.

def calculate_age(current_year, birth_year):
(space)(space)age = current_year - birth_year
(space)(space)return age
my_age = calculate_age(2049, 1993)
dads_age = calculate_age(2049, 1953)
print (“I am”, my_age, “years old and my dad is”, dads_age, “years old”)

My question is why do I need to add the str() when referring to the my_age and dads_age variables in the print statement? It seems to work just fine with the commas… plus I don’t have to account for the extra spaces inbetween either because it already adds them. The lesson said it would throw an error, but I didn’t get one when I did it like this. Thanks for the help

1 Like

Please have a quick look at this post on formatting before submitting code to the forums. It helps immensely-

Your print statement works the way it does because it you supplied the values separated by commas and it treated them like a sequence. This is because print uses an aribtraty argument list (*args) and it accepts any number of objects to print. Unpacking sequences and functions with an arbitraty number of arguments are things likely not covered until further in the course.

If you are curious about it still try the following code snippet and look up the docs on function arbitray argument lists (*args) and also the unpacking operator (*).

print("I am", my_age, "years old and my dad is", dads_age, "years old")
test_tuple = "I am", my_age, "years old and my dad is", dads_age, "years old"
print(*test_tuple)
# If printing from the name associated with a tuple you'll need to unpack it first so that it reads like the sequence you supplied.
# Here * is the unpacking operator.
1 Like

Use one of the three methods of string formatting, and not the above method.

%    => modulo placeholder

{}   => str.format()

f" " => f-string

age isn’t a very necessary variable since you could simply amend the return statement to
return current_year - birth_year and get one less line of code.

My question is: Generally, is using variables that are technically unnecessary such as age a superior coding practice in any way? Does it make code cleaner, more readable, or easier to understand? Because from my point of view, age unnecessarily bloats the code. But maybe I’m missing something.