When you call a function like math.sqrt( 9 ) or random.randint( 3, 7 ) by itself, and run it, your code will not appear to do anything. That's because the purpose of these functions is just to return a value. They do this with the return keyword.
If you make a function that only returns a value, this function call can be used in place of that value's variable type when printing, assigning variables, performing calculations. You call the function any time you need access to that value.
For example:
math.sqrt(9) doesn't do anything by itself
print(math.sqrt(9)) prints the square root of 9
answer = math.sqrt(9) + 5 adds the square root of 9 to 5, then stores it in the variable answer
The average() function returns a float and can be used in a calculation.
def average(n1, n2):
return (n1 + n2)/2 returns the average of the two numbers, a float
expected_total = average(count1, count2) * number_of_entries
The is_working_age() function returns a boolean and can be used as a condition in an if statement.
def is_working_age(age):
return 15 <= age < 65 returns True if the age is 15 to 64 and False otherwise
if(is_working_age(user_age)):
print("Get a job!")
The return keyword does two things:
returns the value
ends the function
Because it ends the function, if there is any code that would run after you return, it won't run. For example:
def is_working_age(age):
return 15 <= age < 65
print("You are working age.") This line of code will never run.