Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
10327 views
ubuntu2004
Kernel: Python 3 (system-wide)

Functions I - Defining a function

Functions are blocks of reusable code used to perform a specific task usually more than once in a program. We have already been using some of Python's inbuilt functions such as print(), len() and range().

When we run the command

print( 'Hello' )

Python uses code that has already been written by someone else to output "Hello" to our screen. The command

len( 'Hello' )

tells Python to run already written code that counts the number of characters in the string "Hello".

These functions are inbuilt into Python, meaning they are always available for us to run from our code. However, we can also define our own functions so that we can reuse pieces of our code throughout our programs.

Reusing code not only makes our programs shorter and more organised, it makes our code easier to maintain as we only have to modify the single function rather than find and edit the code wherever we have performed the specific task.

The concept of functions can be hard to grasp. So let's start with a simple function to print the string "Hello" and then we'll slowly introduce more complex functionality.

A simple function

A simple function to print "Hello" is shown in the following code.

Run this code and nothing will (appear to) happen.
# Define the function called say_hello(). The function, when called, prints "Hello". def say_hello(): # Call the inbuilt function print() to output the string "Hello". print('Hello')

Why wasn't "Hello" printed when you ran this code?

This is because all we are doing is defining a function called say_hello(). That is what def stands for. When we define a function it is saved in computer memory ready to be used (just like a variable).

In order to get the function to do something we need to call it by using its name with the parentheses.

This is shown in the following code. Run it and you will see that it outputs "Hello".
def say_hello(): print('Hello') # Call the function say_hello(). say_hello()
Hello

How functions work

Let's explain the syntax of a function definition. The line

def say_hello():

tells Python that what we are about to do is define a function called say_hello(). The parentheses are necessary as will become clear later. The colon is also necessary.

The next line is

print('Hello')

which calls the inbuilt function print() that simply prints "Hello" to the screen. The important thing here is that the line is indented. Which means that it is inside the function. Any code lines that are indented below def are inside that particular function.

If you un-indent the print('Hello') statement you will get an IndentationError just like for conditional statements and for loops (try it).

The end of the function occurs at the first non-indented line after def.

When we call a function, Python jumps into the function and executes the commands inside it. Python then returns to the end of the call. The figure below shows the order of execution of lines of code for the say_hello() function.

Notice that the program begins execution at the first non-indented line just after the function definition. When we call say_hello() the code jumps into the function at the line def say_hello():. It executes the print('Hello') function (which entails jumping into the inbuilt code of the print() function which we cannot see but is there in computer memory). It then returns from the function to the next line in the main code (which in this case is the end of the program).

Functions must be defined before they are called

In the following code the function hi() is called before it is defined. If you run it you will see it gives a NameError because Python has not saved the function's definition in memory when it was called.

Modify the following code to make it work.
def hi(): print('h') hi()
h

Doc-strings

There is a special way of adding a comment at the start of a function to say what the function does. These are called doc-strings. They are enclosed in triple quotes as shown in the following code.

You should always add a doc-string to any of your functions, however simple they may be.

def say_hello(): '''Print the word "Hello"''' print('Hello')

Doc-strings are used by Python to provide documentation to users. You can get documentation on any of Python's functions by typing

help( function_name )

So if we type

help( say_hello )

Python prints out the doc-string we wrote in our function.

help( say_hello )
Help on function say_hello in module __main__: say_hello() Print the word "Hello"

Try typing help( function_name ) for other functions like print, type, round, len, input, float, int, sorted, range and help.

As you will find, the documentation of inbuilt functions assumes quite a high degree of knowledge about Python. So it's better to use online websites to help you code.

help(help)

Exercise Notebook

Next Notebook