Lesson Notes
How can we get a data result from our function?
Definition of a function:
f(x) = y
Luckily, by definition, functions MUST return a result (y).
But we haven't been returning results and everything works, right?
def foo():
x = 5
print(foo())
Since computers don’t understand the concept of nothing, the None
keyword is a value that stands in for no value at all.
NoneType
, and the only value is None
print(None is 0, None is False)
print(type(None))
Actually, you cannot write a function in Python without returning a value. Python returns None
for you if you don’t return anything in your code.
The return
keyword tells the program to leave the function and return to the line directly after where the function was called.
def foo(x = 9):
y = x + 1
return y # ends the function, and goes back to where the function was called
print("This will never print")
var = foo() # return here the call when function complete
print(var)
Functions can only return one value. However, Python is tricky and uses tuples to fake returning more than one object
def foo():
x = 5
y = 6
return x, y #same as (x, y)
a, b = foo() #same as (a,b) = foo()
print(a, b)
A function can be treated as the data it returns. The below lines are all the same in terms of results.
print(max( abs(-5), abs(-7) ))
print(max( 5, 7))
print(7)
If I have the following:
def myFunc(x=0):
return x + x
myFunc(x=5)
where did the return value go?
Return values from functions must be saved in a variable using assignment:
abs(-1) #the value is lost
num = abs(-1) #the return value is saved in memory
Scope: lifetime of a variable
When a local variable has the same name as a global variable, which one gets used?
Python picks the one closest in scope or the local variable.
def powerof(x=0, p=0):
#not the global power
power = p
y = x ** power
return y
power = 3
result = powerof(x=10, p=2)
print(result)
Any variable name that is assigned a value (with the ‘=’) in the function will automatically be treated as a local variable, even if a global variable with the same name already exists
What is the algorithmic difference between the following two functions:
def foo(num=0):
return num * num
def foo(num=0):
print(num * num)
Printing is a side effect and has no effect on the logic of the program
Return moves data from the current scope to a higher scope