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)


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

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.

def calculate_age(current_year, birth_year):

  age = current_year - birth_year

  return age



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

Someone has asked this question above, although, I’m still unclear on the reason for the “return age” line. I assume at the time (without looking ahead to the next steps in the exercise), that I would reference age at some point.

Per first paragraph in the “Returns” chapter:

Functions can also return a value to the user so that this value can be modified or used later.

Not once did I actually build on the value stored in “return age”. Instead, I used the function to calculate new ages. I’m not sure this exercise actually taught me how to use return.

The example within the chapter, uses return and then references it again for a new calculation:
Here’s an example of a function divide_by_four that takes an integer argument, divides it by four, and return s the result:

def divide_by_four(input_number):  return input_number/4

The program that calls divide_by_four can then use the result later:

result = divide_by_four(16)# result now holds 4print("16 divided by 4 is " + str(result) + "!")result2 = divide_by_four(result)print(str(result) + " divided by 4 is " + str(result2) + "!")

This would print out:

16 divided by 4 is 4!4 divided by 4 is 1!

Could anyone provide clarification on the use of “return age” in the first step? TIA!

You calculate a value and assign it to age within your function. Your return is passing that value back to the caller. If you didn’t pass a value back then your couldn’t assign your ‘new’ ages, namely the variables my_age and dads_age.

There’s not a lot of difference between this and your example divide_by_four, it could for example be rewritten as-

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

This operates in the same manner but assigns a name for the calculation new_number locally within the function. For these examples you could skip this assignment but for more complex functions you’d want to keep your code readable likely with multiple local assignments in the function.

Why does the following code not work in the “Write a Function exercise”? I realize this is not part of the lesson. I was trying to write a function that called for user input, and found that did not work. I then simplified the code and found that even the following did not work.

# Taking input from the user
string = input()
# Output

It might help if you specify the error you’re getting but a lot of CC lessons aren’t set-up to take user input. You’ll get a rather unclear error (end of file I believe) for using input in this case. Try it on your own system if you just went to practice using input.

1 Like

Thanks for your reply. I was wondering if the problem was related to the what CC has set up for this exercise, but I want to make sure that it is not with my code first.

Here is the error message I got. Keep in mind that these lines where pretty far down in my code, because I wrote other (successful) code in the lines above.

Traceback (most recent call last):
  File "script.py", line 25, in <module>
    string = input()
EOFError: EOF when reading a line

Why not test it cleanly? Save the working code for that lesson elsewhere, clear it all and include a single line that uses input, no print statements or otherwise. Just the one line using e.g. test = input() and I’m pretty sure you’ll still get that error. Replace the working code when you’re done.

1 Like

Fair point, but I got the same result.

Traceback (most recent call last):
  File "script.py", line 2, in <module>
    string = input()
EOFError: EOF when reading a line

The exercise instructions are as follows:
The function calculate_age in script.py creates a variable called age that is the difference between the current year, and a birth year, both of which are inputs of the function. Add a line to return age .

what is the point of writing “age = current_year - birth_year” in the function if I cannot print(age)?