Can I call a function inside of a print function?

current_year = 2048

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

print(current_year)

print(calculate_age(1970))

Does print(calculate_age(1970)) call the function? Or is the function not called in this example? I’m confused.

1 Like

Yes, it does. The return value is what will print.

1 Like

yes print(calculate_age(1970)) will call the function and since in the function calculate_age(1970) we asked it to return age hence the statement print(calculate_age(1970)) will print the age of the person (ie78)

1 Like

Yes but as a “call” they aren’t asking for a call in the context of a print function, they want you to “call” the defined parent function “calculate_age()”…

As noted above, print(calculate_age(1970)) absolutely does involve a function call.

I don’t see where calling the function is asked for in this exercise, but if you were to call the function without reference to any print() expression or assignment to a variable, the function would certainly run; its returned value would be “orphaned” (assigned to no variable or function call, thus eligible for garbage collection), and the function and its variables would disappear from the call stack.

In other words, from our standpoint as outside observers, nothing would happen (except that you might see “Run calculate_age.py” on your shell.)

1 Like

Got the correction thank you and the call is simply in the function print as to display the function on screen. Understood.

Or better… in the console.

thx , I was searching for an answer , so thr return is what did the trick?

As the above example shows, you can call a function in Python using Print.

Python allows different ways to accomplish the same task, and beginners may be confused by using print to call a function.

We might be inclined to call and then print the calculated result from the function like this:

current_year = 2048

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

print(current_year)
current_age=(calculate_age(1970))
print(current_age)

The results are the same. But either way, you would still need the Return to get the calculated result out of the function and assign to the variable: “current_age”

Yet another option is to Print the calculated result from inside the function. In that case Print would replace Return. Hope that helps.

Yeah thx, actually that is the way I imagined it first. I know now how both work and that print can actually call a function

Print does not call the function, it prints the return value. The call is made in the argument to the print function.

Any function may take a function as its argument.

1 Like