Organizing Information with Python
Python has powerful tools for organizing information and making decisions. For example, you can save time by creating reusable blocks of code.
Understanding Repeats and Decisions
Understanding Functions and Objects
Get Started with Lists
You can use a list to collect information of more than one type. Lists can hold numbers, strings, and the more complex types of data introduced later in this chapter. You can select an item by its index or by its value.
To create a list, place the elements in square brackets — [ ] — and put commas between each element. Lists are mutable, which means you can change their elements and even perform in-place arithmetic on one list element without changing the others.
Get Started with Lists
Launch the desktop and IDLE if they are not already open.
Type alist = [1, 2, 3, 'one', 'two', 'three'] and press .
Type alist and press .
A Python displays the items in the list, surrounded by square brackets.
B Python displays the first item in the list.
Type alist[4] and press .
C Python displays the fifth item in the list.
Type alist[1] = alist[1]+10 and press .
Type alist and press .
D The second element changes.
Type alist = alist+alist and press .
Type alist and press .
E The + operation adds one list to the end of another.
Note: This is called concatenation.
Using List Methods
You can use list methods to work with lists in more complex ways. The methods are a small library of built-in list processing tools. You can use them to count list items, join lists together, and modify them in various useful ways.
List methods save you the extra work needed to reinvent the wheel. You can use them to save time by adding useful features to your code without having to add them from scratch.
Using List Methods
Launch the desktop and IDLE if they are not already open.
Type alist = [1, 2, 3, 'one', 'two', 'three'] and press .
Type alist.append('four') and press .
Type alist and press .
A The append() method adds a single item to the end of a list.
Type alist.insert(3, 4) and press .
Type alist and press .
B The insert() method adds 4 at the fourth index.
Type alist.remove(4) and press .
Type alist and press .
C The remove() method removes an item by name/value instead of by index.
Note: Only the first matching item is removed. If there are further matching items, this method does not remove them.
Type alist.reverse() and press .
Type alist and press .
D The method reverses the list order.
Type alist.sort() and press .
Type alist and press .
E The method sorts the list.
Note: sort() always places numbers before strings. Strings are sorted alphabetically.
Explore Tuples
You can use a tuple for fixed information. You cannot add or remove elements from a tuple. The contents are fixed, or immutable. However, you can access all the elements in the usual ways. You can also check if an element is in a tuple. Tuples are faster and more efficient than lists. Use them when you have a list of elements that never changes.
Tuples are enclosed in round brackets — () — and tuple items are separated by commas. To avoid confusion with other Python features, a single item in a tuple always has a comma after it.
Explore Tuples
Launch the desktop and IDLE if they are not already open.
Type atuple = (1, 2, 3, 'one', 'two', 'three') and press .
Type atuple and press .
A Python displays the contents of the tuple.
Type atuple.append('four') and press .
B Python displays an error message.
Note: You cannot use any of the list editing methods to change a tuple.
Type 1 in atuple and press .
Type 'one' in atuple and press .
Type 'four' in atuple and press .
C Python returns True or False when you use in to check if an item is in a tuple.
Type anothertuple = atuple + atuple and press .
Type anothertuple and press .
D Python joins two tuples to create a third tuple.
Note: You cannot change individual tuples, but you can join them together to create a new tuple.
Type anothertuple[-1] and press .
E Python displays the last element of the new tuple.
Work with Dictionaries
You can use dictionaries to organize information in pairs. Where arrays use an index to access an item, dictionaries use a key. The key can be any string or number. You can also use a tuple as a key. The item linked to the key is the value.
Dictionaries are associative, which means they link one item of information with another. Use a dictionary when you want an easy and quick way to look up a value given a key. Unlike an array or list, you can pull a value out of a dictionary without having to search the contents in order.
Work with Dictionaries
Launch the desktop and IDLE if they are not already open.
Create a dictionary by typing a variable name, pressing , and typing some paired keys and values separated by colons, between curly braces.
Note: Separate keys and values with colons, and key/value pairs with commas. Include quote marks around strings.
Type the name of your dictionary and press .
A Python displays the paired keys and values you typed.
Type your dictionary name and one of the keys between square brackets.
B Python uses the key like an index and displays the corresponding value.
Type your dictionary name and one of the values between square brackets.
C Python displays an error message.
Type your dictionary name followed by .keys() and press .
D Python displays the keys in the dictionary as a list.
Type your dictionary name followed by .values() and press .
Note: You can use these methods to extract keys or values from a dictionary.
E Python displays the values in the dictionary as a list.
Type your dictionary name followed by .has_key('akeyname') and press .
F If akeyname is in the dictionary Python prints True, otherwise it prints False.
Type your dictionary name followed by .items() and press .
G Python creates a list of all the items in the dictionary. Each element is a tuple with a key and its value.
Understanding Repeats and Decisions
All computer languages, including Python, include many options for repeating code and for making decisions. You can use these features to make “smart” applications that can make decisions. For example, you can create an application that looks at a frame from a webcam and turns on a light when it gets dark. Repeats and decisions are often described with pseudocode, which is easy to understand because it looks more like English than real Python code. The illustrations in this section use pseudocode. You can find the equivalent practical Python code in the following sections.
Understanding Python Code Windows
To make use of repeats and decisions, you must write Python code over multiple lines. Rather like a Linux script, The Python shell works through each line in turn. You cannot write multiline code directly into the Python shell window. You must open another window, write the Python instructions into it, and save the file. To run the program, press . Results appear in the Python shell window.
Understanding if Statements
You can use an if statement to test for some condition and do something only if the result is true. You can add an optional else statement, which does something else if the result is not true. Python also includes a further test statement called elif. You can chain various possible tests between elif statements, and Python will keep testing them until it finds one that returns true.
You often need to write code that does something a set number of times. For example, you may want to write code that steps through every item in a list, or that repeats until some test becomes true. Python includes various tools for creating loops and controlling when they end. The two simplest and most useful options are for and while statements.
Understanding for Statements
You can use a for statement to count through a collection of items or values, usually so you can do something to each one. With an in statement you can count through an array, list, or tuple. To count numerically, you can use the range statement to define a range of numbers. By default, range counts up from 0. But you can add extra information to set the start of the count and the count step. You can even count backward.
Understanding while Statements
You can use a while statement to keep looping through code until the results of a test become true. while is useful when you do not know how often you need to repeat the loop, or do not know how much information you need to work through. In a game, you can use while to wait for key presses or mouse clicks.
Understanding break
Sometimes your code needs to break out of a loop — for example, when you do not need to finish the rest of the loop code because it is no longer relevant. You can use break to “break out” of a loop or an if statement, skipping past the rest of the code.
When you use while, if, for, and so on, you must tell Python which of the following lines belong to the decision or loop statement, and which are normal code. You do this by indenting the lines with . IDLE automatically adds four spaces (it does not insert tabs). Python understands that all indented lines belong to the conditional or loop statement, while all unindented lines are normal code. Note that you can nest a conditional or loop within another, and you must add further indentation whenever you do.
Make Decisions
You can use an if statement to include a test and select different code if the result is true or false. To use an if statement, include code for the test between round brackets, followed by a colon. When you press , the Python shell automatically indents the next line. Indented code “belongs to” the test and only runs if the test is true.
To continue with normal code, press to remove the indentation. Unindented code is not part of the test and runs normally. Optionally, you can include an else statement that only runs if the test fails.
Make Decisions
Launch the desktop and IDLE if they are not already open.
Click File.
Click New Window.
A Python opens a new window for your code.
Type if (a == 3): and press .
B Python automatically indents the cursor ready for the next line.
Note: Remember to include the colon at the end of the if statement.
Note: You must use == not = to test for equality.
Type print 'A is 3' and press .
Press .
The Save Before Run or Check dialog box appears.
Press or click OK.
The File Save dialog box appears.
Type a filename including the .py extension.
Click OK to save the file.
C Python opens a new shell window.
D The window displays the results of your code.
Note: In this example, A is 3 so the test passes and Python runs the code under the if line. To see what happens when A is not 3, change the first line.
Work with Loops and Repeats
You can use a for statement to repeat a block of code a number of times, and set by a range function. The last number in the range is not included, so range(0,10) counts from 0 to 9, not 0 to 10, as you might expect.
To keep repeating code until something happens or a test becomes true, use while, followed by the test, and a colon. while is useful when you do not know how many times you need to repeat something or when your code is waiting for something to happen — for example, for the user to press a key.
Work with Loops and Repeats
Launch the desktop and IDLE if they are not already open.
Click File.
Click New Window.
Python opens a new window for your code.
Type for a in range(0,10): and press .
Type print a and press .
The Save Before Run or Check dialog box appears.
Press or click OK.
The File Save dialog box appears.
Type a filename including the .py extension.
Click OK to save the file.
A Python opens a new shell window and counts from 0 to 9.
Note: The last item in a range is the stop value. The loop does not include the stop value. In this example, the count stops at 9, not 10.
Select all the code and press .
The code is deleted.
Type a = 0 and press .
Type while (a < 10): and press .
Python indents the code after the colon.
Type print a and press .
Type a += 1 and press .
Note: a += 1 is shorthand for a = a + 1.
Press and save the file with a .py extension.
B Python counts from 0 to 9 again, using a while statement instead of a for statement.
Understanding Functions and Objects
You can prepackage and reuse code using some of Python's more advanced features. Functions make it easy to reuse code. Objects make it easy to package information and create a collection of tools.
Understanding Functions
In complex projects, you often need to perform the same steps over and over on different information. For example, in a game you might want to check if any of the game objects have collided with any other game objects. Instead of copying and pasting the code and making minor changes every time you use it, you can package it into a function. The code in the function is kept in one place. You can use the function as a premade tool, passing information to it, and getting a result from it.
Understanding Parameter Passing
Some functions work as-is and do not need further data. For example, a function that returns the date and time does not need any input. Other functions work on information you pass to them. This is called parameter passing. Each item of information you send to the function is a separate parameter. Functions can take any number of parameters, but you do not usually pass more than a few. For conciseness and clarity, you can pass complex information into a single list, tuple, or array, and pass the array as a parameter.
When you define a parameter, it is valid for all the code inside the function. Even if you use the same name elsewhere, Python automatically keeps the names separate. Similarly, if you use variables inside a function, their names are “private” to the function. You cannot access them outside it. This separation is called variable scope. It helps keep code uncomplicated, because you do not have to think of a new name for every variable in your code.
Understanding Return Values
Functions usually return a result. (You can write functions that do not return a result, but functions that do are usually easier to work with and more useful.) Use return to specify the value or variable you want to return from a function.
Understanding Function Definitions
To create a function, type def followed by a name, add round brackets with a colon, place parameters between the brackets, and add indented code after the colon. When Python finds a return it ends the function, even if there is more code after it.
Understanding Classes
You can package code even more neatly by creating a class. A class is like a mould. It includes a list of variables you can access, and a list of methods, which are functions that are built in to the class. Classes are useful when you want to create a lot of similar objects and define what information they hold and what they do. For example, you might use a class to define a game tile, storing information about its position and color, and adding a library of methods to create the tile, remove it, and perhaps to move it from one location to another.
You use class followed by a class name and a colon to define a class. You can then define variables and functions — technically attributes. After you define a class, you can create instances of it. Each instance is an object made from the class mould with the same attributes. You give each object a standard variable name when you create it, so you can tell the instances apart. Python uses dot notation to access object attributes. For example, if you create an object called myTile with position attributes called x and y, you can access them with myTile.x and myTile.y.
Create a Function
You can use the def keyword to define a new function. Follow it with the name of the function, and zero or more parameters between round brackets. End the first line of the definition with a colon.
You can use the function by referring to its name. If you defined any parameters, include them between the round brackets. If you include a return statement the function returns a value. Otherwise, it returns a special value called none. This example creates a simple function that doubles a number.
Create a Function
Launch the desktop and IDLE if they are not already open.
Click File.
Click New Window.
Python opens a new window for your code.
Type def double(aValue): and press .
A Python indents the next line ready for the function code.
Type return 2*aValue and press .
B Python automatically ends the function and cancels indentation after a return.
Press , type a=4, and press .
Note: The first is not essential, but adding an extra space makes the code easier to read.
Type print double(a) and press .
Note: If you create any variables inside a function, they only exist inside the function. You cannot use them elsewhere. Technically, they are only in scope inside the function.
Press .
The Save Before Run or Check dialog box appears.
Press or click OK.
The File Save dialog box appears.
Type a filename including the .py extension.
Click OK to save the file.
C Python opens a new shell window and prints the doubled value returned by the function.
Replace a = 4 with a = 'string'.
Repeat steps 8 to 11 to save the file.
D Python runs the function on a string. The double operation duplicates the string.
Note: Functions process information exactly as normal Python code does. In this example, doubling a string makes sense. A function with different code might only work on numbers and returns an error with a string.
Define a Class
You can use class to create your own classes. To create a useful class, include a selection of variables and methods. After defining a class, you can create as many instances of it as you need. Each instance holds its own data.
Classes often include a special function called __init__ which runs automatically when you create an instance of it. You can use this method to set values for all the variables used in your class, or to return a useful value. Class definitions often refer to self, which is a short way of saying “this instance.”
Define a Class
Launch the desktop and IDLE, if they are not already open.
Click File.
Click New Window.
Python opens a new window for your code.
Type class myClass: and press .
A Python indents the code after the colon.
Type aVariable = 0 and press .
Note: This line creates a variable for the class called aVariable and sets it to 0.
Type def __init__(self): and press .
Note: This lines creates the special __init__ method. You must include (self) if you define an __init__ method.
Note: __ is two underscore characters.
B Python indents the code again after the colon.
Type self.myName = 'A new instance' and press .
Note: You can add as much code as you need to any method in a class. This simple one-line example creates a variable called myName and sets its value to a string.
Press to cancel one level of indentation.
Type def changeName(self, newName): and press .
Type self.myName = newName and press .
Note: These two lines create a new method that allows you to set myName to a new value.
Repeat steps 8 to 11 from the previous section, “Create a Function,” to save the file.
Python creates your class without errors. The code does not print any output.
Using a Class
To use a class, define a variable using the class name followed by round brackets. If you defined an __init__ method for the class, include the parameter values between the brackets. If your __init__ method includes a return statement, the variable takes the returned value. Otherwise, it is set to a special value called none.
After creating an instance, you can access the variables and methods you defined with dot notation. If the methods you define take a parameter, include it between round brackets. You do not need to specify a value for self because Python includes it automatically.
Using a Class
Continue from the end of the previous section, “Define a Class,” or repeat the steps in that section to create a class and open the shell window.
In the shell window, type anInstance = myClass() and press .
Python creates a new instance of the class.
Note: Python does not display any messages when you create an instance.
Type print anInstance.aVariable and press .
A Python prints 0, which is the default value your class code sets for aVariable.
Type print anInstance.myName and press .
B Python prints A new instance, which is the default value your class code sets for myName.
Note: Creating this class preassigns these variables. If you try to print a variable not defined in your class, Python displays an error.
Type anInstance.aVariable = 10 and press .
Type print anInstance.aVariable and press .
C Python prints 10, because you have changed the value of aVariable.
Type anInstance.changeName('Something else') and press .
Python runs the changeName method you defined, using Something else as the parameter.
Type print anInstance.myName and press .
D Python prints the new changed value of the myName variable in anInstance.
Load Modules
You can use modules to package and reuse code, and to extend Python's features. Modules are prewritten blocks of Python code. Many features of Python are only available if you import them from a module before you try to use them. import typically goes at the start of your code.
To use features from a module, import it by name and access its features with dot notation. For example, if you import math, you can use any of the features in the math module by putting math in front of the name. You can also selectively import specific features using from.
Load Modules
Launch the desktop and IDLE if they are not already open.
Type math.factorial(10) and press .
A Python displays an error message.
Note: You must import math before you can use the factorial method. This feature is not available until you do.
Note: factorial multiplies a number by itself, decreasing by 1 on each repeat: for example, 10 × 9 × 8 ×…2 × 1. It is often used in statistics.
Type import math and press .
Python imports the math module. It does not display a confirmation message.
Type math.factorial(10) and press .
B The factorial method runs correctly.
Type from decimal import * and press .
Python imports all methods from the decimal (special arithmetic) module.
Type 1.0/81 and press .
C Python displays the result using the built-in Python arithmetic library, which has limited precision.
Type getcontext().prec = 100 and press .
Note: This line sets up the imported decimal module to give results to 100 decimal places. Details are in the online Python documentation.
Type Decimal(1) / Decimal (81) and press .
D Python uses the decimal module to perform the calculation to 100 places, using and returning special “Decimal” numbers, which can calculate results with as much precision as you set.
Work with pickle
You can use pickle to save and load class instances, arrays, tuples, lists, and other complex information. Technically, the pickle process is called serialization. It converts complex information into a simple format that can be saved and read from the hard drive. Without pickle, you have to read, save, load, and reassign all the variables separately.
You must import the pickle module before you can use it. pickle is easy to use. For basic use, the code for loading and saving information is very simple.
Work with pickle
Launch the desktop and IDLE if they are not already open.
Type import pickle and press .
Python loads the pickle module, but does not generate a message.
Type aDict = {'a': 1, 'b': 15, 'z': -99} and press .
Note: This line creates a dictionary to give pickle something to save.
Type pickle.dump(aDict, open("aDict.pickle", "wb")) and press .
Python saves the dictionary to your /home folder, but does not generate a message.
Click the File Manager icon ().
Scroll down to check that the file exists in your /home directory.
Note: "wb" means “write binary.” You cannot open the file in a text editor such as Leafpad because it contains binary code, not text.
Click the shell window to reselect it and hide File Manager.
Type aDict = "".
Note: This line creates an empty dictionary.
Type aDict =pickle.load(open("aDict.pickle", "rb")) and press .
Type aDict and press .
A pickle reloads the contents of the dictionary.
Note: "rb" is short for “read binary” — the opposite of “write binary.” If you use "b" while writing, you must use it while reading.
Using the Debugger
In computing, a bug is an error that keeps your code from working as it should. You can use IDLE's debugger to step through code one line at a time, viewing variables and checking the contents of class instances.
The debugger is easy to use, but not very sophisticated. To load it, click Debug and then Debugger from the main IDLE menu. You can now use five buttons to control the debugger. Variable values appear in the lower part of the window.
Using the Debugger
Launch the desktop and IDLE if they are not already open.
Click Debug.
Click Debugger.
A Python prints a [DEBUG ON] message.
B A Debug Control window appears.
Either click File and then New and press and save the code from the section “Work with Loops and Repeats,” or reload the file if you saved it.
Press to run the code.
Python loads the code but stops at the first line.
Click Over repeatedly to step through the code line by line.
Note: This example has a single variable. In a more typical Python project, many variables appear in the window.
C The current line appears in the main window.
D Variables and their current values appear at the bottom of the window.
Click the Source check box ( changes to ).
Click Over repeatedly.
E Python highlights the current line in your original code, so you can see where you are in the code and what it is doing.
Note: Python locks you out of the shell window while your code runs.
18.118.119.229