Page 52 - Programming the Raspberry Pi Getting Started with Python
P. 52
So, if a tuple is just a list that you cannot do much with, you might be wondering why you would
want to use one. The answer is, tuples provide a useful way of creating a temporary collection of
items. Python lets you do a couple of next tricks using tuples, as described in the next two subsections.
Multiple Assignment
To assign a value to a variable, you just use = operator, like this:
Python also lets you do multiple assignments in a single line, like this:
Multiple Return Values
Sometimes in a function, you want to return more than one value at a time. As an example, imagine a
function that takes a list of numbers and returns the minimum and the maximum. Here is such an
example:
This method of finding the minimum and maximum is not terribly efficient, but it is a simple
example. The list is sorted and then we take the first and last numbers. Note that numbers[-1] returns
the last number because when you supply a negative index to an array or string, Python counts
backward from the end of the list or string. Therefore, the position -1 indicates the last element, -2
the second to last, and so on.
Exceptions
Python uses exceptions to flag that something has gone wrong in your program. Errors can occur in
any number of ways while your program is running. A common way we have already discussed is
when you try to access an element of a list or string that is outside of the allowed range. Here’s an
example:
If someone gets an error message like this while they are using your program, they will find it
confusing to say the least. Therefore, Python provides a mechanism for intercepting such errors and
allowing you to handle them in your own way: