View Full Version : A beginner's guide to Python

27th November 2005, 06:30 PM
topA beginner's guide to Python
(Under construction; please do not post, as this guide may take up multiple posts)

toc1. Table of Contents
Table of Contents
Control structures
Advanced concepts

27th November 2005, 09:02 PM
intro2. Introduction

1. What is Python?
Python (http://www.python.org/) is an interpreted, dynamically typed, high-level, object-oriented, extensible programming language. This means, in layman's terms, that it is easy to learn and use, extremely powerful, can be run on almost any operating system/CPU combination, and can be modified to change or add features. The one downside is that it is somewhat slow to run, but most who use Python find its benefits far outweigh this inconvenience.

2. How do I get it?
Python, being FOSS (free/open-source software), is freely available for download (http://www.python.org/) at its website (http://www.python.org/). As of the time of this writing, the latest Python version was 2.4.2 (http://www.python.org/2.4.2/), although the Mac OS X version was only 2.3. Installers are available for Windows and for Mac OS X, as is source code for Unix variants such as Linux. If you run Linux, you likely already have Python installed, although you may want to update your version; RPMs and Debian packages are available from third-party sources. If you run one of the *BSDs or another operating system, good luck; you may have Python already installed, but if not, you're on your own.

3. How do I use it?
Once you have Python installed, you should be able to open the interactive Python shell from a command line. If you are using Windows, go to Start > Run, type "cmd", and press Enter to get a command line. If you use Mac OS X, then there should be a terminal application available somewhere in the Apple menu. Once you are in a terminal, type in "python". If nothing happens or you get an error, type in the location where you installed the python executable/application/binary, and press enter. (For Windows, this should be something like "C:\Python\python.exe".) If you follow these steps, you should end up looking at something like this, although the second line will probably look different:
Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> Now, you have completed your Python installation, and are ready to learn how to program in Python. Advanced Windows users may want to ensure that the path to the Python executable is in the PATH system variable using the control panel, so that they merely have to type "python" to get to the interactive shell; Linux users should put a symbolic link to the python binary in their /usr/bin/ directory.

Return to Table of Contents

variable3. Variables

1. What's a variable?
Variables are how you store information in Python. Each variable has a name and a value. The name of the variable is how you refer to it; it can be almost any assortment of alphanumeric (only letters and numbers are alphanumeric), but must begin with a letter. The value of a variable is the data it is storing; this could be an integer value, the name of a person using your program, a list containing many different values, and just about anything else.

2. How do I use them?
To create a variable, you assign a value to its name, like so:
>>> some_variable = 5Now, this variable will contain the value 5:
>>> some_variable
5You can re-assign variables at any time in the same fashion. You can even assign a variable to contain the value of another variable:
>>> another_variable = some_variableNote that if, for example, you now assign some_variable to the value 10, another_variable will still have the value 5:
>>> some_variable = 10
>>> another_variable

3. What can variables contain?
A variable can contain any piece of data that has a defined type. Now, in Python, everything has a type, so a variable can essentially contain anything that has been defined. We'll take a look at how to define a type later, but Python already has many useful types of data built into it. In order to represent these types of data, we use literals. A literal is just a string of characters that Python interprets as data of a predefined type.

To take an example, let us look at a type that we've already seen: the integer. An integer means exactly what it does in math: essentially, any number without a decimal point. Integers are therefore represented by a bunch of digits without decimal point. For example:
>>> foobar = 205In this example, the '205' we entered is a literal representing the integer value two hundred and five.

Python has many built-in types and corresponding literals. We'll take a look at the most important of these. In addition to integers (or ints), python has: Floats - Numbers with decimal places ('float' stands for 'floating-point number'); they are represented by digits surrounding a decimal place; for example:
>>> some_float = 23.421

Strings - Sequences of characters, like the sentence you're reading now. String literals are formed by putting quotes around the letters they are supposed to represent:
>>> some_string = "this is a string literal" The quotes can be single (') or double ("). Certain characters can only be represented within a string literal by prefixing them with the escape character, the backslash (\). For example, to represent a quote within a string, you would do like so:
>>> some_string = "this: \" is a quote"

Lists - A list of values. Lists consist of other literals and variable names, separated by commas, and surrounded by matching square brackets. For example:
>>> foo = 3.0
>>> some_list = [1, 'two', foo, 4]Now, the list in some_list would contain, in order, the integer 1, the string "two", the float 3.0, and the integer 4. Note that if foo was reassigned, some_list would still contain the same values:
>>> foo = "hello"
>>> some_list
[1, 'two', 3.0, 4]Note also that one can have an empty list (represented simply by two square brackets, []) or a list containing only one element ([4], for example).

The values contained in a list are called its elements, and they can be individually accessed using square-bracket notation. To do this, take the variable name of the list, add square brackets ("[]") to the end, and put the index of the element you want to access between the brackets. Note that lists are zero-indexed, meaning that the first element of a list is at the index 0:
>>> some_list[0]
>>> some_list[1]
>>> some_list[2]
3.0Negative indexes are treated as if they begin at the end of the list; thus, -1 refers to the last element of the list, -2 to the second-to-last, and so on:
>>> some_list[-1]
>>> some_list[-2]
3.0Indexes beyond the end (if positive) or beginning (if negative) of the list generate errors:
>>> some_list[4]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
>>> some_list[-5]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of rangeDon't worry about what the error output means right now; just accept that it's an error.

In addition to simple indexing, lists can use slice notation. Slice notation is used to refer to all the elements in a list between certain indices. To use slice notation, put two numbers separated by a colon between the square brackets. This will yield a new list, starting with the element at the index of the first number, and ending with the element at the index one before the second number. For example, to get a list containing the first through third elements of the list, inclusive, you do like so:
>>> some_list[0:3]
[1, 'two', 3.0]Slice notation can be used with negative indices, but the index of the first element must always come first. If the first index corresponds with an element after that of the last index, the slice notation will yield an empty list:
>>> some_list[-4:2]
[1, 'two']
>>> some_list[-3:-2]
>>> some_list[3:-3]
[]Slice notation can also be used with one of the indices missing. In this case, the 'slice' will start from the beginning or end at the end of the list, depending on which index was left out. Likewise, if one of the indices is beyond the beginning or the end of the list, it will be treated as the beginning or the end of the list:
>>> some_list[1:]
['two', 3.0, 4]
>>> some_list[:3]
[1, 'two', 3.0]
>>> some_list[2:6]
[3.0, 4]
>>> some_list[-13232451:2]
[1, 'two']Finally, slice notation may use a third number, again separated by a comma, to denote the step size. For example, a step size of 2 would mean only every other element was included in the resultant list. The step size and/or any of the other numbers may be left out as before; the step size is assumed to be one if unspecified.
>>> some_list[0:3:2]
[1, 3.0]
>>> some_list[0:4:3]
[1, 4]
>>> some_list[1:3:]
['two', 3.0]
>>> some_list[1::2]
['two', 4]
>>> some_list[:-2:2]
>>> some_list[::3]
[1, 4]
>>> some_list[::]
[1, 'two', 3.0, 4]

Tuples - Tuples are exactly like lists, except that they are immutable, meaning that the value of a tuple cannot be changed once it's created; however, it is impossible to fully explain why this is until we get to the Objects section. Note that this does not mean that you cannot reassign a variable whose value is a tuple, because reassigning does not change the tuple; it merely gives the variable a new value to 'hold on to'. The tuple itself is unchanged, but the variable does not refer to that tuple any more. Tuple literals have the same form as lists, but are delimited by parentheses, not square brackets:
>>> some_tuple = (1.0, 2, 'three')

Dictionaries - Dictionaries are mappings from one set of values onto another. The notion may be unfamiliar, but it's not difficult to comprehend: given a certain key, the dictionary will yield a certain value. The dictionary is said to map keys to values. This is analogous to real-world dictionary, which matches words (keys) to their definitions (values). A dictionary is represented by a comma-separated list of key-value pairs enclosed by curly brackets. The key-value pairs have the key, then a colon (:), then the value. The keys and values can be literals or variables of (almost) any type, and there can be spaces anywhere you like. For example:
>>> foo = "hello"
>>> bar = "bar"
>>> some_dictionary = {2 : 1.23, bar: 12, "message" :foo}Now, some_dictionary will map 2 onto 1.23, "bar" onto 12, and "message" onto "hello". This mapping can be accessed by using square-bracket notation, but instead of putting an index in the brackets, we use the key instead:
>>> some_dictionary[2]
>>> some_dictionary["message"]
'hello'Dictionaries are one-way: though we can easily get a value if we have the key, there is no simple way to get the key given its corresponding value. Also note that dictionaries are not ordered, and do not support slice notation. Also, a dictionary's keys must be immutable; thus, a dictionary cannot use a list or another dictionary as a key, but can use a tuple. There are no restrictions on the values that can be assigned to a dictionaries' keys.