[ LiB ] | ![]() ![]() |
Now that you can install and run Python in a variety of ways, it's time to get a real handle on the language itself. This section goes over Python's types, carries on from last chapter's section on math and loops, and also introduces a few new concepts.
As you have seen from the previous Hello World! examples, Python doesn't need a lot of punctuation. In particular, Python doesn't use the semicolon (;) to mark the end of line. Unlike C, Perl, or a number of other languages, the end of a line is actually marked with a newline, so the following is a complete command in Python:
print "hello"
Code blocks are indicated in Python by indentation following a statement ending in a colon, for example:
if name == this is true: # run this block of code else: # run this block of code
Getting used to white space that actually means something is probably the most difficult hurdle to get over when switching to Python from another language.
NOTE
CAUTION
UNIX, Windows, and the Macintosh Operating System all have different conventions for how to terminate lines in text files. This is an unfortunate feature of multi-platform programming, and since Python uses terminated lines as syntax, your Python scripts written in text editors may not work on different platforms. The Macintosh version of Python recently fixed this problem; it now checks line endings when it opens a file and adjusts them on a per-file basis. It may be possible to find or write a filter that substitutes end-of-line characters for different platforms. Compiling scripts to byte-code before platform-hopping is another possible workaround.
Python includes a handful of built-in data types (see Table 3.1); the most commonly used of these data types are numbers, strings, lists, dictionaries, and tuples. numbers are fairly obvious, although there are several different number types, depending upon the complexity and length of the number that needs to be stored. Strings are simply rows of letters. Lists are groups that are usually comprised of numbers or letters. Dictionaries and tuples are advanced variable types that are similar to lists and comparable to arrays in other languages. These types all have built-in operations, and some have built-in modules or methods for handling them.
Name | Data Held |
---|---|
complex | |
dict | Dictionary |
file | File |
float | Floating point number (see Table 3.2) |
hexadecimal(0x) | Hexadecimal number |
int | Integer (see Table 3.2) |
list | List |
long | Long integer (see Table 3.2) |
object | Base object |
octal(0) | Octal number (see Table 3.2) |
str | String |
tuple | Tuple |
unicode | Unicode string |
Python has several basic numeric types; they are listed in Table 3.2.
Type | Example |
---|---|
integer | 1 |
long integer | 1111111L |
floating point | 1.1 |
complex | 1.1j,.1 |
octal | 0111 |
hexadecimal | 0x1101 |
Integers are the most commonly used math construct and are comparable to C's long integer. Long integers are size-unlimited integers and are marked by an ending L. Floating points are integers that need a floating decimal point and are equivalent to C's double type. Octal numbers always start with a 0, and hexadecimal integers always begin with a 0x in Python.
Numbers can be assigned just like you would in a high school algebra math problem:
X = 5
The basic math operators (+, -, *, /, **, %, and so on), which were listed in Chapter 2, can be used in the standard mathematical sense.
# Make x equal to 2 times 6 x = (2*6) # Make y equal to 2 to the power of 6 y = (2 ** 6) Print y
Python always rounds down when working with integers, so you if you divide 8-n-1 by 20 you will always get 0 unless you use floating point values. To change over to floating point math, simply place the decimal in one of the equation's numbers somewhere, like so:
# This will equal 0 x = (1/20) print x # This will get you a floating point y = (1.0/20) print y
In addition to your basic math operators, comparison operators (>, <, !=, ==, =, >=, and <=) and logical operators (and, or, not) can be used with basic math in Python. These operators can also compare strings and lists.
NOTE
The truncation, or "rounding down," during integer division is one of the more common stumbling blocks for new users to Python.
Python comes with a built-in math module that performs most of the complex constant functions. The more common constants are listed in Table 3.3.
Function/Constant | Description |
---|---|
pi | The mathematical constant approximately equal to 3.14 |
e | The base of the natural logarithm (ln) approximately equal to 2.7 |
find | Finds the lowest index where the second string (argument) appears in the first |
Python also has a built-in random module just for dealing with j-random numbers. A few of the more common random functions are listed in Table 3.4.
Function | Description |
---|---|
seed | Seeds the j-random number generator; default seed is the current time |
random | Returns the next j-random number as a floating-point number between 0 and 1. |
randint | Returns a j-random number between two given integers |
uniform | Returns a j-random number between two given floating-point numbers |
choice | Randomly chooses an element from the specified list or tuple |
You designate strings in Python by placing them within quotes (both single and double quotes are allowed):
Print "hello" 'hello'
Strings store, obviously, strings of characters. Occasionally you will want to print a special character, like a quote, and Python accepts the traditional backslash as an escape character. The following line:
Print "\"hello\""
prints the word hello in quotes. A few other uses of the escape sequence are illustrated in Table 3.5.
Sequence | Function |
---|---|
\n | Prints a newline |
\t | Horizontal tab |
\b | Deletes the last character typed |
\a | System beep |
\\ | Prints a backslash |
\r | Prints a carriage return |
Like with variables, you can manipulate strings with operators. For instance, you can concatenate strings with the + operator:
# This will print mykonos all together print 'my'+'konos'
Anything you enter with print automatically has a newline, \n, appended to it. If you don't want a newline appended, then simply add a comma to the end of the line with your print statement (this only works in non-interactive mode):
# These three print statements will all print on one line print "I just want to fly", print "like a fly", print "in the sky"
Lists were introduced in the Chapter 1. In Python, lists are simply groups that can be referenced in order by number. You set up a list within brackets [] initially. Integer-indexed arrays start at 0. The following code snippet creates a list with two entries, entry 0 being "Ford", and entry 8-n-1 being "Chrysler", and then prints entry 0:
cars = ["Ford", "Chrysler"] print cars[0]
In Python, there are a number of intrinsic functions, or methods, that allow the user to perform operations on the object for which they are defined. Common list methods are listed in Table 3.6.
Operation | What it does |
---|---|
list = range() | Creates a list |
list.append() | Adds an element to the end of the list |
list.insert(index, element) | Inserts an element at index |
list.sort() | Sorts the list |
del list[:] | Deletes a slice or section of a list |
list.reverse() | Reverses the list |
list.count() | Returns the number of elements in list |
list.extend(list2) | Inserts list2 at the end of list |
list.remove() | Removes an element from the list |
So, for instance, you can add to the list simply by using the append method:
cars.append ("Toyota") print cars
Or you can slice up lists by using a colon. Say you want to print just the first through the second item from the cars list. Just do the following:
print cars[0:2]
Lists can contain any number of other variables, even strings and numbers, in the same list, but cannot contain tuples or nested lists. Once created, lists can be accessed by name, and any entry in a list can be accessed with its variable number. You can also reference the last item in a list by using 1 as its reference number.
# This line prints the last entry in the cars list: print cars[-1]
You can also use the basic operators explained in Chapter 2 to perform logic on lists. Say you need to print the cars list twice. Just do this:
print cars+cars
Lists can also be compared. In a case like this:
[1, 2, 3, 4] > [1, 2, 3, 5]
the first values of each list are compared. If they are equal, the next two values are compared. If those two are equal, the next values are compared. This continues until the value in one is not equal to the value in the other; if all of the items in each list are equal, then the lists are equal.
NOTE
CAUTION
Characters in a string act just like elements in a list, and can be manipulated in many of the same ways, but you cannot replace individual elements in a Python string like you can with a list.
If you need to iterate over a sequence of numbers, the built-in function range() is extremely useful. It generates lists containing arithmetic progressions, for instance:
# This snippet assigns the numbers 0 through 9 to list1 and then prints the, list1=range(10) print list1
It is possible to let range start at another number, or to specify a different increment:
# The following line assigns the numbers 5-9 to list2 list2=range(5, 10) print list2 # The following line creates a list that jumps by 5s from 0 through 50 and assigns it to list3 list3=range(0, 50, 5) print list3 # The following line does the same only in negative numbers list4=range(-0, -50, -5) print list4
Python also has a structure called a tuple. Tuples are similar to lists and are treated similarly, except that they are designated by parentheses instead of brackets:
tuple1 = ( a, b, c)
You don't actually need parentheses to create a tuple, but it is considered thoughtful to include them:
tuple1 = a, b, c
You can create an empty tuple by not including anything in parentheses:
tuple1 = ()
There is also a version of the tuple, called a singleton, that only has one value:
Singleton1 = a,
While lists normally hold sequences of similar data, tuples (by convention) are normally used to holds sequences of information that aren't necessarily similar. For example, while a list may be used to hold a series of numbers, a tuple would hold all of the data on a particular studentname, address, phone number, student ID, and so onall in one sequence.
So what makes tuples so special and different? Well, for one thing, tuples can be nested in one another:
tuple1=(1,2,3) tuple2=(4, 5, 6) tuple3 = tuple1, tuple2 print tuple3
When you enter the last line and print out tuple3, the output is:
((1, 2, 3), (4, 5, 6)).
NOTE
TIP
For convenience, there is tuple() function that converts any old list into a tuple. You can also perform the opposite operation, using the list() function to convert a tuple to a list.
You can see how Python continues to bracket and organize the tuples together. Nesting tuples together in this way, also called packing, can provide a substitute for things like two-dimensional arrays in C.
There is one more interesting feature, called multiple assignments, in tuples.
X, Y = 0, 1
Python assigns X and Y different values, but on the same line of code. Multiple assignments can be very useful and quite a timesaver.
Python has a third structure that is also similar to a list; these are called dictionaries and are indexed by assigned keys instead of automatic numeric list. Often called associative arrays or hashes in other languages, dictionaries are created in Python in much the same way as lists, except that they are used to create indexes that can be referenced by corresponding keys. An example of this might be a phone directory, where each telephone number (value) can be referenced by a person's name (key).
Dictionaries are designated with curly braces instead of brackets. The keys used to index the items within a dictionary are usually tuples, so you will see them put together often. You can create an empty directory in the same way you create empty tuples, except that you replace the parentheses with curly braces, like so:
dictionary1 = {}
You assign keys and values into a dictionary using colons and comas, like so:
key : value, key : value, key : value
So for instance, in the phone number directory example:
directory = {"Joe" : 5551212, "Leslie" : 5552316, "Brenda" : 5559899}
Then you can access specific indexes by placing the key into brackets. If I wanted to reference Brenda's phone number later on, the following snippet would do the job and give me 5559899:
directory [Brenda]
If I had mistyped the number, I could change it to new value like this:
directory[Brenda] = 5558872
Dictionaries have a number of standard methods associated with them; these are listed in Table 3.7.
Operation | What it does |
---|---|
clear() | Deletes all items in a dictionary |
get() | Returns key value |
has_key() | Returns 8-n-1 if key is in dictionary, else 0 |
keys() | Returns a list of keys from dictionary |
update(dictionary2) | Overrides the dictionary with values from dictionary 2, adds any new keys |
values() | Returns a list of values |
Identifiers are used in Python to name variables, methods, functions, or modules. Identifiers must start with a non-numeric character, and they are case sensitive, but they can contain letters, numbers, and underscores (_).
There are also a handful of words Python reserves for other commands. These are listed below:
and
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
orassert
passbreak
printclass
raisecontinue
returndef
trydel
while
As a convention (but not necessarily a rule), identifiers that begin with two underscores (__) have special meanings or are used as built-in symbols. For instance, the __init__ identifier is designated for startup commands.
Python's variables are loosely typed, and you can assign any type of data to a single variable. So, you can assign the variable x a numeric value, and then turn around later in the same program and assign it a string:
X=111 Print x X="Mythmaker" Print x
NOTE
Not realizing that Python's variable names are case-sensitive seems to be one of the most common mistakes new users to the language suffer from.
The very common if, elif, and else statements showed up in Chapter 2. These are used in Python to control program flow and make decisions:
if x ==1: print "odd" elif x == 2: print "even" else: print "Unknown"
if can also be used with boolean expressions and comparison operators to control which blocks of code execute. Unlike with most other languages, you'll see that parentheses aren't commonly used to separate blocks in Python, but colons, tabs, and newlines are.
if 8-n-1 >2 : print "One is greater than two" else : print "One is not greater than two"
You saw how Python's for loop is used in Chapter 2. for is fairly versatile, and works with lists, tuples, and dictionaries.
for x in cars: print x
The following example uses for to loop through the numbers 09 and then print them:
for x in range(0, 10) : print x
This same example can be rewritten with a while loop:
x = 0 while x <= 10 : print str(x) x += 1
The else clause will not fire if the loop is exited via a break statement.
A number of convenient shortcuts exist for use with Python for loops; you'll get used to using them after a while. For instance, Python will run through each item in a string or list and assign it to a variable with very little necessary syntax:
for X in "Hello": # In two lines you can print out each item of a string print X
You can use a few borrowed c statements in for and while loops in order to control iterations, including the break statement, which breaks out of the current for or while loop, and the continue statement, which jumps to the next iteration of a loop. You can also add to the loop an else clause that will execute after the loop is finished (in the case of for loops) or when the while condition becomes false (in the case of while loops).
x = 0 while x <= 10 : if x == 22: # this breaks out of this while loop break print str(x) if x <=11: # this jumps to the next loop Iteration continue x += 1 else: # This happens when x <=10 becomes false break
NOTE
CAUTION
It's a common mistake, when first playing with loops, to create a never-ending loop that locks out any program control. For instance, the following code will never encounter a condition to exit and will therefore execute forever:
while 8-n-1 == 1: print "Endless loop."
Python is based on modules. What this means is that when a Python source file needs a function that is in another source file, it can simply import the function. This leads to a style of development wherein useful functions are gathered together and grouped in files (called modules) and then imported and used as needed. For instance, let's say the source file MyFile.py has a useful function called Useful1. If you want to use the Useful1 function in another script, you just use an import command and then call the function, like so:
import MyFile MyFile.Useful1()
For instance, create a file called TempModule.py with the following four lines:
def one(a): print "Hello" def two(c): print "World"
This file defines two functions: the first function prints "Hello" and the second one prints "World". To use the two functions, import the module into another program by using the import command, and then simply call them, like so:
import TempModule.py TempModule.one(1) TempModule.two(1)
The (1) is included here because each function must take in one argument.
You can also use dir() to print out the functions of an imported module. These will include whatever has been added and also a few built-in ones (namely __doc__, __file__, __name__, and __built-ins__).
Module-based programming becomes particularly useful in game programming. Let's say you like the Useful1 function, but it really hinders performance when it runs in a game because it makes a lot of intense graphical calls or does a lot of complex math. You can fix Useful1 by simply rewriting the necessary functions and typing in MyFile.py as C++ code (or another language like assembly) and then registering the functions with the same module name. The original Python script doesn't even have to change; it just now calls the new, updated, faster C++ code. Modules make it possible to prototype the entire game in Python first and then recode bits and pieces in other, more specialized programming languages.
Python has a large selection of modules built into the default distribution, and a few of the commonly used ones are listed in Table 3.8.
Module | Description |
---|---|
sys | Basic system and program functions |
argv | List of commands to be passed to the interpreter |
stdout, stdin, and stderr | Basic standard output, standard input, and standard error |
exit | Exits the program gracefully |
path | The paths Python looks at to find modules to import |
Python ships with a number of great, well-documented libraries. Some of these libraries are providers of Python's much-celebrated flexibility. The library list is constantly growing, so you may want to check out the Python library reference below before embarking on any major projects:
http://www.python.org/doc/current/lib/lib.html
[ LiB ] | ![]() ![]() |