Custom Search

PYTHON: Functions

Common needs of a programmer can be turned into functions in Python.

 

A function saves the programmer having to repeatedly type out lines of code. Using a function shorten the coding document and makes it easier to understand, because the function's name can explicitly state what the code is doing - and when defining it at the head of your program, you can add 'comments' to explain that more fully.

What does a function do?

A function takes some data (the function's input) and returns some other data (the function's output).

For example the 'sum function' can take a list of numbers as its input and return the sum of all of the numbers in the list as a single number as output.

numbers = [9, 2, 14, 22, 5, 67, 208, 90, 56]
total= sum(numbers)
print ("Addition sum total = ",total)

To apply a function to some data (whether it's a variable, a number or a string), you just write the name of the function followed by the data in parenthesis.

The computer will then calculate the function's output, which can be used in further calculations or assigned to a variable.

Library of pre-written functions for Python 3

There is a library of functions that are already written for you to call upon - 'sum' being one of them. There is a vast array - and some of them can prove very useful.

They are listed here. Do take a look. If you scroll down you will see an explanation of what each one does.

Functions that have a page of their own within this site:

input()

list()

type()

Making your own functions

A function is a block of code which only runs when it is called.

A function must be written in the head of your program. It can then be called upon - as it has been defined.

You can put anything you like into a function - but it only makes sense to write one if it will be used several times within your program.

You pass data, known as parameters, into a function, then the function can return data as a result of its action upon that data.

When coding in Basic in the 'olden days' I used subroutines to do a similar thing.

For example.

Let's write a 'heading function' that takes some text as an input, capitalises all of the letters in it and rules off under it with a row of asterixes. Then leaves a blank line before any further printing.

First of all we need to define the variable and the function:

headerText= ("my heading")

def header():

HEADER = headerText.upper()

print(HEADER)

print("*******************")

print("")

(Note that the function content block has to be indented)

Finally we have to call on the function in our program:

headerText()