FAQ: Introduction to Functions - Returns

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.

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 ?

I was doodeling around and trying out some things to see if I understood. I don’t (yet/fully/etc). Why doesn’t this work:

#test def

def divide_by_four(input_number):
return (input_number)/4

result=divide_by_four(16)
print (input_number+’ divided by 4 is '+str(result))

There’s an error in the print statement itself as you’re attempting use a name input_number that isn’t defined.

Remember that the names inside the function are not accessible outside the function, e.g.-

def pass_three():
    x = 3
    return x


print(x)  # inevitably throws an error. x does not exist in the main scope of your code

You could create a new name and use your print statement and function call in that fashion, e.g.-

intput_number = 16
# perhaps a different name would be appropriate to avoid confusion with the function name
result = divide_by_four(input_number)
print (input_number + ' divided by 4 is ' + str(result))

Thanks, I indeed learned this in a later lesson…

I want to include another return that allows me to calculate how many months it will take by using retainers_left/4 . I’m not sure how to approach this as I am running into syntax errors when I try

1 Like

You can only return once from the function so what you would need is to return one or more values at once. This is generally achieved with a different data type (e.g. a sequence like a list or tuple). You could for example return your two useful values in a list.

def calc(<example>): # skipped these bits for this example
    left = <example>
    months_remaining = left / 4.0  # If you need integers consider floor division (//)
    return [left, months_remaining]

retainers_left, months_left = calc(1, 1)

For an example like this one it would be typical to return a tuple rather than a list but they may not be introduced for a while (I may be wrong) so a list will do. The basic idea stands that you return a datatype that can store more than one value.