5 Functions
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). 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.
Here’s how we would calculate the expenses using the sum
function
instead of a for-loop.
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.
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.
Activity 5.1
Change the code to show the number of items ordered, using the
len
function. Like when using a for-loop, the output should be 5.You can compare your solution to mine.
5.1 The input
function
Another very useful function is input
: it takes a string that it prints on the
screen (the user’s prompt), and returns a string with what the user typed on the
keyboard until they pressed the RETURN or ENTER key. Run the code below and
click on the right-hand pane. You will see the grey rectangle blinking,
to indicate it’s waiting for your input. Type
in your name, followed by RETURN or ENTER.
The input
function always returns a string, even if the user typed in a number. To
see the implications of that, run the code below and type in your birth year.
The computer reports a type error, because the code is mixing two different
types of data. It is trying to subtract the string returned by input
from the
number 2022.
5.2 A conversion function
The solution is to use function int
, which takes a string and
converts it to an integer, a number like –2, –1, 0, 1, 2, etc. If the
string represents a decimal number, int
will give an error.
Activity 5.2
Change the restaurant program so that it asks the user for the number of people.
You can compare your solution to mine.
In the next section you will learn a different form of iteration.
⇦ Iteration: for-loops | ⇧ Start | Iteration: while-loops ⇨ |