Thanks. From the examples in the exercises, I have come to understand that we use return if our function contains any calculations and we need to use the numerical results later in our code; And, if the function contains a print statement, there’s no need for using ‘return’. Is that right?
It’s not a question of if, but what we plan to do with the result. When all we wish to do is print, then it’s okay to print inside the function. However a function is more useful (can be called from anywhere) if it has a return that can be printed at the caller. We can capture that value, which means we might not even want to print it, but use it in further computations.
def add(a, b):
print (a + b)
The utility of this function is limited. What if we want to use the sum in a further computation?
def add(a, b):
return a + b
Now we have options at the caller to either print, store and print, or just store.
print (add(6, 7))
# 13
c = add(6, 7)
print (c)
# 13
def mul(a, b):
return a * b
Now we can even use the previous call as an argument…
Okay, why DOESN’T the example function work/ how can you make it work? I’m referring to:
def create_special_string(special_item):
return "Our special is " + special_item + “.”
print("I don’t like " + special_item)
My attempt at fixing it was:
special_item = grapes
def create_special_string(special_item):
return "Our special is " + special_item + “.”
print("I don’t like " + special_item)
print(create_special_string)
and that didn’t work, says I did not define ‘grapes’. I also tried the same except with print (create_special_string(grapes)) and it gave the same error that I had not defined grapes. I feel I need to grasp this to really understand the lesson, but I don’t understand why it doesn’t work.
Is there any difference between defining the global variable before the definition of the function vs defining the global variable before the function call?
for instance:
def calculate_age(birth_year):
age = current_year - birth_year
return age
current_year=2048
age=calculate_age(1970)
print (current_year)
print(age)
vs
current_year=2048
def calculate_age(birth_year):
age = current_year - birth_year
return age
age=calculate_age(1970)
print (current_year)
print(age)
The output is the same here but i wanted to check if something could be different.
That is the main concern. Where it is written makes no difference just as long as it is declared before the first call to the function.
Ideally, there would be no global, only parameters. You could, for instance either pass in a current year, or better still invoke the datetime object to get the current year so your function is timely.
from datetime import datetime
def ....(birth_year):
return datetime.now().year - birth_year