Functions

Learn how to define functions in Python and how to use them.

Introduction to functions

We spent a lot of time earlier working with mathematical functions. We thought of these as machines that can take input, do work, and produce the result. These functions can be used again and again.

Many computer languages, Python included, make it easy to create reusable computer instructions. Like mathematical functions, these reusable snippets of code stand on their own if we define them sufficiently. Plus, they allow us to write shorter, more elegant code. Why do we want shorter code? Because invoking a function by its name many times is better than writing out the entire function code many times.

What do we mean by “sufficiently well defined”? It means being clear about what kinds of input a function expects, and what kind of output it produces. Some functions will only take numbers as input, so we can’t supply them with a word made up of letters.

Coding example

Again, the best way to understand this simple idea of a function is to see a simple one and play with it. Let’s run the following code:

Press + to interact
# function that takes 2 numbers as input
# and outputs their average
def avg(x,y):
print('first input is', x)
print('second input is', y)
a = (x + y) / 2.0
print('average is', a)
return a

Code explanation

Lines 1–2: Python ignores the first two lines starting with #, but they can be used as comments for future readers.

Line 4: The next bit, def avg(x,y), tells Python that we’re about ...

Access this course and 1400+ top-rated courses and projects.