Simple coding
Simple coding

Start this free course now. Just create an account and sign in. Enrol and complete the course for a free statement of participation or digital badge if available.

5 Functions

Learn about functions in Python programming language. 

Totting up the bill is basically calculating the sum of a list of numbers. This is such a common need that Python already provides a function for that, appropriately called sum. A function takes some data (the function’s input) and returns some other data (the function’s output). In this case, the sum function takes a list of numbers as input and returns a single number as output.

To apply a function to some data (whether it’s a variable, a number or a string), just write the name of the function followed by the data in parenthesis. The computer will calculate the function’s output, which can be used in further calculations or assigned to a variable.

Interactive feature not available in single page view (see it in standard view).

As you can see, using the sum function shortens our code and makes it easier to understand, because the function’s name explicitly states what the code is doing. Good programmers don’t just write code, they write readable code. They know that code always changes to accommodate further customer requests, and trying to modify cryptic code you wrote some weeks or months ago is no fun. Using comments and descriptive names for variables and functions helps making code readable.

The length function

Counting the number of items in a list is also so common, that Python has a function for that too, called len, which returns the length of the list.

Change the code above to show the number of ordered items, using the len function.

Take your learning further

Making the decision to study can be a big step, which is why you'll want a trusted University. The Open University has 50 years’ experience delivering flexible learning and 170,000 students are studying with us right now. Take a look at all Open University courses.

If you are new to University-level study, we offer two introductory routes to our qualifications. You could either choose to start with an Access module, or a module which allows you to count your previous learning towards an Open University qualification. Read our guide on Where to take your learning next for more information.

Not ready for formal University study? Then browse over 1000 free courses on OpenLearn and sign up to our newsletter to hear about new free courses as they are released.

Every year, thousands of students decide to study with The Open University. With over 120 qualifications, we’ve got the right course for you.

Request an Open University prospectus371