Python Functions

Outside Resources:

TheNewBoston Functions

TheNewBoston Return Values

LearnPython.org Functions

TutorialsPoint Python Functions

W3Schools Python Functions


A function is one or more lines of code that you can call whenever you want.

Some of the reasons to use functions:

  • Reduce repetitive work by reusing your code in multiple places
  • Break code into chunks so it is easier to read, debug, and modify

Python uses the def keyword to define functions like so:

def myfunction():
    print("Hello")
    print("My function has two commands.")

Notice that the def line ends with a colon, similar to an if statement. Then the commands in the function are all tabbed on the following lines.

Defining a function doesn’t actually cause the function to execute. It makes the function available to be called whenever it is needed. After it is defined, Python now knows what commands to run every time the function is called.

To make the function run, you have to call the function.

Calling a Function

To call a function, type its name of the function followed by parentheses, ().

You can call a function in your program (editor window) OR in the python window. Try it both ways! Type myfunction() except with your function’s name instead of “myfunction.” If you forget the parentheses, it won’t work!

Functions can return a value. This means that a function is equal to the return value, and this value can be stored in a variable or used in another function. This is different than printing a value! Printing something doesn’t store it in memory – it only shows that value in the console.

def greeting():
    return "Hello!"

#save the function's return value to a variable:
text = greeting()
print(text)

#use the function inside a command; greeting() is equal to "Hello!"
print(greeting() + " How are you doing today?")

Note: the function ends as soon as a value is returned. If there are commands after the return command, they will not be executed! You can see that if you try this function:

def oops():
    return "abc"
    print("This command will never be executed.")

Make that function, then call it by typing oops() in your python window. Python will NOT print that last command, because the function ends at return "abc".

Functions can receive input values, which are called arguments. Parameters are variables that are used inside a function, and the value for those variables can be different every time a function is called. This makes functions much more flexible.

Example: Let’s calculate the circumference of a circle. This first function can only calculate circles with a diameter of 5.0:

def circumference():
    pi = 3.1415
    d = 5.0
    c = pi*d
    return c

This function will always return the same value, so it’s not very useful.

The next version allows us to calculate circumference for any diameter:

def circumference(d):
    pi = 3.1415
    c = pi*d
    return c

Notice that there’s a d parameter in the first line, inside the parentheses. This means that the parameter, d, has been defined as part of this function’s signature (the first line of the function).

When you call this function, you have to enter a number for d, as shown below:

area(2.2)  #Not a useful way to call your function*
a = area(5)
print('The area is: ', a)
print(area(7.5))
total_area = area(0.51) + area(1.0)

The actual number that you enter in the function call (in the parentheses) is an argument. The named variable being used in the function is the parameter.

*Using “area(2)” by itself as a line of your program doesn’t actually store the result of the function anywhere. Since the function is equal to its numerical result, this is the equivalent of typing something like “6.283” as the only text in a line of Python code. Python will accept it (no error messages), but nothing interesting will happen.

Try typing area() into your Python window to see what type of error message you get when you forget to enter the d parameter.

The following example shows a function being called in the main program:

def cm(inches):
    cm_num = inches * 2.54
    #convert to string to make it easier to print out
    cm_str = str(cm_num)
    return cm_str

print("125 inches equals " + cm(125) + " centimeters.")
print("0.36 inches equals " + cm(0.36) + " centimeters.")
print("72 inches equals " + cm(72) + " centimeters.")

Notice that after the function is defined, the next lines (starting with print) are NOT indented or tabbed. You can see the cm() function in all of the print commands. Those functions will all be executed when the “run” button is clicked.

Variables in Functions:

You will soon run into two problems with variables as you learn to write functions.

1) Variables created in functions are local variables. This means they disappear from memory after the function call is finished.

2) Functions are not allowed to change global variables, although they are allowed to read them. There are ways around this limitation.

Read about Variable Scope to see details on these two topics.