
Concepts: Functions
Grouping related code under a name with Python functions.
Functions in Python
A "function" is a pre-defined set of code with a given name. That code can be run anywhere by using its name. Up until now, you've been running a lot of built-in functions. One example is the print function:
print()
>
The code that makes up the print function's definition (i.e. what it should do when it's run later) is loaded when the Python engine starts up. However, it doesn't run on its own: there needs to be code that causes it to run. The way to run a Python function is by writing the name of function, followed immediately by a pair of parentheses (()). There are many pre-built functions available in Python.
Defining Custom Functions
However, the programmer can also define their own functions in Python using the def keyword. The def keyword is followed by the name of the function, a set of parentheses, a colon (:), and an indented set of code that makes up the definition:
def print_animal():
color = "Orange"
animal = "Orangutan"
colored_animal = color + " " + animal
print(colored_animal)
>
Note that defining a function does not cause its code to run: it needs to be run manually. It can be run multiple times without having to be re-defined:
def print_animal():
color = "Orange"
animal = "Orangutan"
colored_animal = color + " " + animal
print(colored_animal)
print_animal()
print_animal()
print_animal()
> "Orange Orangutan"
> "Orange Orangutan"
> "Orange Orangutan"
Function Inputs and Outputs
If you look at the print_animal example function above, you'll notice that it does the same thing every single time it is run. While this is useful for some things, it's not very flexible. Fortunately, Python functions can be set up to take inputs that change their functionality. When defining a function, this is done by adding a comma-separated list of variables between the function's parentheses. These are called "parameters".
def print_animal(color, animal):
colored_animal = color + " " + animal
print(colored_animal)
print_animal("Orange", "Orangutan")
print_animal("Blue", "Dolphin")
print_animal("Red", "Squirrel")
> "Orange Orangutan"
> "Blue Dolphin"
> "Red Squirrel"
Python functions can also output values to be used by other code with the return keyword.
def color_animal(color, animal):
colored_animal = color + " " + animal
return colored_animal
animal_1 = color_animal("Orange", "Orangutan")
animal_2 = color_animal("Blue", "Dolphin")
animal_3 = color_animal("Red", "Squirrel")
print(animal_1 + ", " + animal_2 + ", and " + animal_3 + " Balloons Now Available!")
> "Orange Orangutan, Blue Dolphin, and Red Squirrel Balloons Now Available!"
Note: The return keyword also immediately ends the function, so any indented code on the following lines will not run.