Why can’t we use return in the same line where you calculate the variable age?
If i define the function
def calculate_age(current_year,birth_year)
return age = current_year - birth_year
This return a syntax error message
Why can’t we use return in the same line where you calculate the variable age?
If i define the function
def calculate_age(current_year,birth_year)
return age = current_year - birth_year
This return a syntax error message
We cannot return a statement, only an expression.
return current_year - birth_year
Ok. That makes sense. Thank you very much!
Amazing… subtle but important difference between a statement and an expression.
I have a question regarding this example:
def calculate_age(current_year, birth_year):
age = current_year - birth_year
return current_year - birth_year
my_age = calculate_age(2049, 1993)
dads_age = calculate_age(2049, 1953)
print ("I am " + str (my_age) + " years old " + “and my dad is " + str (dads_age) + " years old”)
I don’t understand why they put: age = current_year - birth_year
when we already add the return fuction: return current_year - birth_year with the answer that we want.
We can rewrite the code and get the same answer.
def calculate_age(current_year, birth_year):
return current_year - birth_year
my_age = calculate_age(2049, 1993)
dads_age = calculate_age(2049, 1953)
print ("I am " + str (my_age) + " years old " + “and my dad is " + str (dads_age) + " years old”)
Hello @dato86, welcome to the forums! You are completely right in saying that you don’t need the age
variable. If it is an introductory lesson, it might be to demonstrate the use of return
, and how you can use it.
I had the same doubt. So, since "age = " isn’t required, putting just return current_year - birth_year works? (And also, is there a significant difference between using the two?)
Hello @tag7719331909, there isn’t a significance difference between the two.
It would work, but it may not pass CC’s test, as they may be getting you to work with variables.
Oh, okay. Thank you.