Skip to main content

11.2) Functions


If there’s a task you want to repeat several times in a program (e.g. reading/writing a file or doing a specific calculation), rather than copy-pasting the code, write a function!

Here’s an example of a simple function followed by a few lines of code, write it out in a program and execute it:

def cube(x):
    # function that calculates the cube of a number
    c=x*x*x
    return c
# call the function:
y=cube(3)
print y
# here’s another call to the function:
a=5
print cube(a)

Our function looks a bit like an if statement, but with a few extra things.

  • def is a keyword that indicates you’re defining a function. It’s followed by a space and the name of the function, here 'cube'
  • the variable x within round brackets is the input of a function, we call it an argument in programming jargon. You can have more than one argument or none
  • the block of code associated with the function is delimited with a colon (:) and an indentation, just like for an if or while statement. That’s the code that will be executed every time you call your function. For example, in the function written out above, we calculate the cube of x and assign the result to the variable c