You can call functions in python without using print() when your function has a print() statement inside of it.
Example:
def my_function():
print(4)
my_function()#outputs 4
In the example above you called my_function by doing my_function(), and that calls (returns basically) anything inside of my_function. There is a print statement inside of my_function, so that is why it will output (or print) 4 when called.
However, you must call my_function without printing the results, because a function without a return statement automatically returns None. If you were to print my_function, you would get an output of 4 and None.
Alternatively, you can look at it like this:
def my_function():
print(4)
return None #if you don't have a return statement, this is automatically added to your function when it is called
my_function() #outputs 4
print(my_function()) #outputs 4 and None
You must print your function whenever you have a return statement inside of it. (That’s assuming you want to see your function results).
Example:
def my_function():
return 4
print(my_function())#outputs 4
You cannot see the results of a return statement simply by calling it. You must print the result.
def my_function():
return 4
print(6)
my_function()#outputs 6 but not 4
current_year = 2048
def calculate_age(birth_year):
age = current_year - birth_year
return age
print(calculate_age(1970))
Same thing here. You must print a function to see the results of return age
.
current_year = 2048
def calculate_age(birth_year):
age = current_year - birth_year
return age
calculate_age(1970)#doesn't output anything
Now, just because you cannot see the results of a return statement doesn’t mean the result wasn’t returned.
Example:
def my_function():
return 4
my_function()#will return 4 so I can save this to a variable and print that variable.
my_function_results = my_function()
print(my_function_results)#will output 4
Case in point. But you must still no matter what print a function with a return statement to see the results.
All printing a function does is print EVERYTHING inside of it. That’s why when you print a function without a return statement, the added return None is printed as well.
As I made a bad joke about this:
What does a function return when it doesn’t return anything?
None-thing!
Ooh one more thing if you didn’t already know this! WHENEVER you try to call or print a function to get its results, you must write it like this:
my_function()#the parenthesis is what allows the results to be called.
print(my_function)#will give you something like <function object at #&*^$#>
Hope this helps!