Loops let us run a bit of code over and over and over. Sometimes, we want to use a chunk of code more than once, but we want a little more control over how it happens. In that case, we’ll use a function. A function is kind of like a variable, but it stores actual code instead of a value. The print() and input() functions are built-in functions, but we can also create our own. The code below defines a new function on lines 1 and 2, then calls it on line 5.

  • The def is short for define. It tells Python that we’re about to define a new function.
  • The person inside the parentheses in the definition line is called a parameter. It’s a placeholder for information that we’ll put into the function when we call it. A function can have as many parameters as you want, separated by commas. You can also have no parameters at all—the function will do the same thing every time it runs.
  • Again, notice the colon and the indentation. Indented line 2 is part of the function, but unindented lines 4 and 5 are not.

Use the repl above to practice writing your own functions. Try using some of the other structures we’ve learned so far!

Functions can do another important thing: they can return information back to the program or function that called them. For example, you might write a function to calculate how old you are in cat years:

def catYearCalculator(humanAge):
    catAge = humanAge * 7
    return catAge
age = input("How old are you?")
ageInCatYears = catYearCalculator(age)

The last line of the function uses the return keyword to output the calculated cat age, which is saved to the variable ageInCatYears. In order to save a function’s output, you have to create a variable that calls the function.