A function is a block of code designed to perform a particular task. A function encloses a set of statements and is a fundamental modular unit of Python. They you reuse code, and provide a way for you to organize your programs, keeping them easier to understand and easier to modify. It’s often said that the craft of programming is the creation of a set of functions and data structures which implement a solution to some problem or set of requirements.
Functions are objects, like many things in Python. They can be stored in variables, other objects, or even collected into lists. Functions are very powerful because in Python, they can be passed as arguments to other functions and returned from functions. The most important thing that functions can do is get invoked.
You create functions easily.
An example of how you write a function definition:
def add(p1, p2):
return p1 + p2You end up with a function named 'add' that takes two parameters and adds them, returning the result. (Yes, you could just write (p1 + p2) and everyone would understand. It’s just a very simple example.) Here is another example:
def greetUser(username):
print( "Hello " + username)
return
# calling/Invoking the function
greetUser("Mike Jones"); # "Hello Mike Jones"Functions are meant to be invoked. So you can have one function call another function which calls a third function and so on; it’s very common.
Imagine we have a program that gets an airplane ready for flight. We can imagine a whole series of functions we’d have to write. Things like 'loadPassengers', 'loadBaggage', 'loadFuel', 'checkTirePressures', and so on. Then we might have a 'higher level' functions which brings all these pieces together:
def prepFlight(airplane):
loadBaggage(airplane)
loadPassengers(airplane)
loadFuel(airplane)
performPreflightChecklist(airplane[copilot])
askTowerToDepart(airplane[pilot])
departGate(airplane)
taxiToRunway(airplane, mainRunway90)
takeoff(airplane[pilot], airplane)
returnYou can see how functions you perform different things in a particular order, and while you might have no idea how 'loadBaggage' does what it does, you can see how the program preps the airplane object for flight and makes sure everything important is done. Each of the functions from 'loadBaggage' to 'takeoff' is invoked and returns so the next one can be invoked. This is the power of functions - the ability to take some code and put it a function so that it much easier to understand.
A common pattern used in Python revolves around an lambda function. Something like:
double = lambda x: x * 2
print(double(5))This gives us another way to wrap up a little code into a function. We could redo the first example in this chapter with a lambda function.
add2 = lambda p1, p2: p1 + p2
print(add2(5,7))Once Python reaches a return statement, the function will stop executing. Functions often compute a return value. The return value is "returned" back to the "caller". You can have many returns in a functions, depending on how the flow of control is changed.
def greetUser(username):
return "Hello " + username
result = greetUser("Welcome back, Mike Jones")
print(result); # will print "Hello Welcome back, Mike Jones"Or like this:
def determineWinner(home, visitor):
if (home[score] > visitor[score]):
return "Home Team Wins! Let's have a Parade!"
elif (home[score] < visitor[score]):
return "Visitors Win! (oh Well)"
return "It's a Tie!"Notice how in this case, we check to see the scoring results with two conditions (which are, what? yes, boolean expressions). If neither condition is true, the third one must be the case. But if either condition is true, then we return right away, and the function is done.
Again, to be clear, we might use this function like this:
home = {'name': "Fightin Cats", 'score': 0 }
visitor = {
'name': "Wild Horses",
'score': 0
}
playGame(home, visitor) # a lot of work done in this function(!)
# game is done
result = determineWinner(home, visitor)
# and then print the result..
print(result)As you just saw, functions can also take parameters to be used within a function.
def addThreeNumbers(a, b, c):
return (a + b + c)
def determineWinner(home, visitor):
if (home['score'] > visitor['score']):
return "Home Team Wins! Let's have a Parade!";
elif (home['score'] < visitor['score']):
return "Visitors Win! (oh Well)";
return "It's a Tie!"
def makeNegative(number):
if (number > 0):
return -(number)
# already negative, it's less than 0
return numberRemember how we had the expression ot see if a number was even? ( x % 2 === 0) Now, here’s a way to decide is number was divisible cleanly by another, it’s a standard arithmetic expression:
(number % divisor == 0)So to see if a number is even, we could use '(number % 2 == 0)':
print((8 % 2 == 0)); # true
print((7 % 2 == 0)); # false
print((4 % 2 == 0)); # trueAnd we can use the same technique to see if a number is evenly divisible by 3 or 5.
Try to write a function that will perform the following requirements:
|
Tip
|
|
OKAY! Write it yourself!
Do it.
Just write it yourself.
C’mon, write your own version first.
No, really.
Wait.
Do you want to be a ZipCoder, or just a Copy-Paste Stylist?
Well, here’s one solution:
# Function ZipCoder
def zipCoder(aNumber):
if (aNumber % 15 == 0):
print("ZipCoder")
elif (aNumber % 3 == 0):
print("Zip")
elif (aNumber % 5 == 0):
print("Coder")
zipCoder(45) # -> ZipCoder