Python Programming Reference


1. Basic concepts


Python is an interpreted scripting language. This means that Python programs are, in their most basic form, just text files with a list of commands, which are executed by a program called the Python interpreter. Compiling Python programs, or "scripts", into binary 1s and 0s is not necessary, as the interpreter can read the source code directly. In general, commands are executed in order, starting with the first line of the program and on down to the last, although certain statements give the possibility of repeating or skipping over chunks of code (cf. Section 5.4, Control Flow). In addition, a Python program may start with the following line:

#!/usr/bin/env python

which is ignored on Windows systems, but not on a Unix or Linux system. Its use is to tell the operating system that it should ask the Python interpreter to run this script, if the script has been marked as executable and the user attempts to run it.

1.1. Data


Any useful computer program, in a general sense, is a construct that takes some type of input and produces some type of output. The inputs and outputs, and anything else the program might work with in between, are all treated as data. For example, an audio recording program takes as its input data a sequence of volumes and frequencies, and produces a sound file listing these, or some subset of these. The data one usually works with in a simple program can be broadly separated into two groups:

Literals. A literal is exactly what it says (literally!). For example, the number 5 is a literal:

print 5

will print the number 5 on the screen.

A sequence of letters (a string) is also a literal, if enclosed by single or double quotes:

print "Hello, World!"

or

print 'Hello, World!"

will print the sentence on a line on the screen, but

print Hello, World!

will not, because there's no quotation marks to tell Python that the string is a literal.

Variables

Python can store values in containers called variables. This allows you to do things like storing the result of a calculation and calculating something else with it:

a = 2
b = 3
c = a+b
d = c*c

a now holds the value 2; b holds 3; c holds their sum (5); and d holds the square of c (25).

It's important to remember that the equal signs assign the value on the right to the variable on the left:

a = 5
b = 4
a = b

a was originally assigned the value 5, but now has the value 4, and b still has the value 4.

Conversion

Data comes in various types, such as strings, integers and floats. It's important to know that different data types are treated differently by Python:

print 5+5

outputs the number 10, but

print "5"+"5"

outputs "55", because Python thinks the 5s with quotations are strings, not numbers. To get Python to do what you want, you may need to convert your data to the appropriate type. See Section 5.4.5 for more information on data type conversion.

1.2. Comments and docstrings

For your own convenience, and to help others understand your code, it is strongly recommended to include remarks (or comments) about what your code is doing together with the code. Comments in Python are designated with a # symbol: anything after the # is ignored by the Python interpreter.

a = (2+3)2 # a has 5 squared now

A different method of documenting your code is by a docstring. Docstrings are a sort of introductory explanation of the program you're writing, put at the start of the program. These are started and ended by three double-quote symbols in a row. For example:

def printHelloWorldFunction
"""This function prints out a greeting to the world!
Written July 1st, 2010 by A. Programmer.
This comment will end after this triple quote--->"""

Docstrings are not exactly comments, in that they're not ignored by Python, but they're still a form of documentation.

Comments are also very useful when your code doesn't work--a time-honoured debugging method is to 'comment out' everything except the bare essentials to isolate what isn't doing what it should.

2. Operators


An operator is, in general, a typographical symbol that means something special to the Python interpreter, and tells it to do something with the literals or variables next to it. Many are basic mathematical functions like addition and subtraction. Comparison functions are also operators, and will be listed here, but will be treated in more depth in Section 5.3, Control Flow.

Functions are similar, but tend to be user-defined, tend to be full words and the syntax is often different. Some examples should help.

2.1. Mathematical operators


You may have noticed the * symbol in this line of the preceding section:

print "Five squared is ", 5*5

This is an example of an operator; it tells Python to take the two literals next to it and multiply them. Python recognizes the following operators:

+ Addition; also used for string concatenation

e.g. 1

five = 2+3

e.g. 2
company = "Abercrombie" + " and " + "Fitch"

- Subtraction; will also yield the negative of a number

e.g. 1

three = 5-2

e.g. 2

minusfive = -5

  • Multiplication; can also be used for repeating strings
e.g. 1

fivesquared = 5*5

e.g. 2

threecheers = "Rah! "*3 # produces "Rah! Rah! Rah! "

    • Exponentiation
The double asterisk indicates that the first number is to be taken to the power of the second:

e.g. fivesquared = 52

/ Division

e.g. three = 6/2

There is a big caveat here. The result you get will actually be different here depending on which version of Python you are using. In general it's very important to use the correct data types, and you must realize that numbers with decimal points like 2.0 (floats) are a different type from numbers without a decimal point like 2 (integers).

(Note: You are probably using Python 2.x.)

In Python 3.x and above, if you divide two integers, or an integer and a float, or two floats, the result will be a float. So you always get the full value of the quotient.

quotient = 7/2 # result: 3.5 (a float, not an integer)

In Python 2.x and below, if you divide two integers, the result will be an integer, with any remainder rounded down. So:

quotient = 7/2 # result: 3, not 3.5

In general it is safest to always use floats when you want a full decimal answer.

Truncating division

This gives the quotient sans remainder; i.e., what you would get in Python 2.x if you divide two integers.

quotient = 7
2 # result is 3 in any version of Python

% Modulo operator

This gives the remainder of a division:

remainder = 72 # result is 1, since 7/2 = 3 + 1/2


remainder = 72 # result is 1, since 7/2 = 3 + 1/2

2.2. Comparison operators


The other major class of operators you will use in Python are comparison operators. These take two quantities, perform the comparison indicated, and return a 'True' or 'False' value which can be used in further computations.

< Less than, > Greater than

e.g. 1
2 < 5 # yields 'True'

e.g. 2
2 > 5 # yields 'False'

<= Less than or equal to, => Greater than or equal to

e.g. 1
2 < 5 # yields 'True'

e.g. 2
2 <= 2 # yields 'True'

Equal to, != Not equal to

e.g. 1

3==5 # yields 'False'

"Cat" != "Dog" # yields 'True'

Note that it's very important to use two equal signs when testing for equality, as just one equal sign indicates assignment. In other words:

a==5 # Returns 'True' if a is equal to 5, and 'False' otherwise
a=5 # Assigns the value 5 to the variable a

2.3. Boolean operators

These operators, in contrast to the symbols seen thus far, are simple words, which perform Boolean logic on 'True' and 'False' data.

and - Boolean AND

a and b # Returns 'True' if both a and b are 'True' and 'False' otherwise

or - Boolean OR

a or b # Returns 'True' if either a or b are 'True' and 'False' otherwise

not - Boolean NOT

not a # Returns 'True' if a is 'False' and 'False' if a is 'True'

2.6. Operator precedence

There is an order of operations for operators, just like in standard algebra, and it generally follows the same rules. The top-priority operators are executed first, then the lower-priority ones. Here is the list of operators in descending order of priority:

- Negation (i.e., a negative sign in front of one number takes priority over all else)
    • Exponentiation
*, /, //, % Multiplication, division, floor division, modulo (all same priority; evaluated in left-to-right order)

+,- Addition, subtraction

All comparison operators (<, >, <=, =>,=, != )

All Boolean operators (and, or, not)

So for a complex example:

-52 < 2 or 2+5*2==12

This line will:

1. Square the number -5 (get +25) and see if it's less than 2 (returns False)
2. Multiply 5 by 2 and add 2 (get 10+2, or 12) and see if it's the same as 12 (returns True)
3. Check if either the left hand side or right hand side were True (the right side was), and return True if so

So the line has the value 'True'.

Parentheses can be used to order operations just like in algebra, and are recommended if only for your own sanity!

( ((-5)2) < 2 ) or ( (2+(5*2)) == 12 )

is, at the least, much easier to read.

3. Basic I/O functions


This section discusses two functions you'll be using a lot: print, for putting information on the screen, and

3.1. The print statement


This is by far the most important function for a basic program. The word 'print' tells Python to take a value and output it to the screen. Here's the traditional "Hello, World!" program in Python:

print "Hello, World!"

That's it, really. You can do some other tricks with print:

Printing a blank line
print

Printing a variable
string = "Hello, World"
print string

Printing multiple things on one line
fivesquared = 5*5
print "Five squared is ", fivesquared

You can even do the math inside the statement:

print "Five squared is ", 5*5

Note that the comma is important here to distinguish the items to be printed.

Incidentally, a trailing comma at the end of a print statement will cause the carriage return to be omitted (so the next thing that the program outputs will be on the same line).

3.2. Getting user input: the raw_input function


The raw_input function is what you use to get information from your user interactively. When the Python interpreter runs into a raw_input statement, it pauses execution of the script to allow the user to enter some keyboard data, reads it until the Enter key is pressed, and then returns the data the user entered as a string. Since this data is a string, it may need to be processed to be used further:

print "Enter a number:"
number = raw_input()
print "Your number, squared: ", (float(number))2

Running this code results in:

Enter a number:
1.1
Your number, squared: 1.21

You can also present a prompting question to the user on the same line as the data requested by giving a string argument to the raw_input function:

number = float(raw_input("Enter a number: "))
print "Your number, squared: ", number2

Running this code results in:

Enter a number: 1.2
Your number, squared: 1.44

3.3. File operations


Frequently you will want to get data from a file, or save program output to a file. You do both of these via the "open" statement, which opens a connection (a filehandle, so called as it gives you a handle on the file to manipulate it) to a file for reading or writing. The syntax for the open statement is as follows:

filehandle = open(filelocation, mode)

filelocation must be a string that can be interpreted as the location on your system of a file (for example, "C:\Windows\MyData.dat" or "MyData.dat").

The different modes in which a file can be accessed are:

r - Read-only: The file must exist previously; it will not be modified and data will be read from it
a - Append: The file does not need to exist previously; new data will be added to the file starting at the end of the file. If the file does not exist it will be created and writing will start from the first line.
w - Write-only: The file does not need to exist previously (in fact, if it already exists, it will be erased!), and data will be written to it but cannot be read from it.
r+ - Read-write: The file can be both written to and read from. (Avoid using this unless you really need to! it is easy to lose data with this mode)

As an example:

filehandle = open("/tmp/MyOutputData.dat', 'w')

Note that if no mode is specified, Python assumed read mode.
Note also that if, on a Windows or Mac computer, you need to read or write binary data, you may add a 'b' to the mode string (e.g. 'wb'). Unix/Linux systems make no distinction between binary and text files, so the 'b' is ignored on these systems.

If you are having trouble getting this command to work, check to make sure you have permissions to do what you are trying to do--for example, you can't write to a read-only file, or read a file that you don't have access to. (This happens more often than you might suspect.)

Once a file handle has been opened, manipulation of the file operates via a few different mechanisms.

Reading from a file:

To read a line from a file that's been opened for reading as 'filehandle', use the 'readline' method:

filehandle.readline()

Repeated calls of this function will return successive lines in the file.

For example:

print filehandle.readline(), # prints the first line of the file

print filehandle.readline(), # prints the next line of the file

(The comma in these print statements is included because the lines already have a newline character in them, so without the comma, you would get an extra space after the line!)

Usually you will want to do something to every line in the file. It is possible to repeat the readline() call until you run out of lines, but it's faster to use one of the two following options:

a) filehandle.readlines() will return an array containing all the lines in the file:

for line in filehandle.readlines:
print line, # prints every line in the file.

b) or, you can directly iterate over the filehandle object:

for line in filehandle:
print line,

If you use method b), do not also use the readline() or readlines() function (or the read(size) function, which returns a specific number of characters).

Writing to a file:

To write a string to a file, use the write() method of the filehandle:

line = "Hello, World!\n" #the \n is a special symbol that adds a carriage return after the line
filehandle.write(line)

The data printed must of course be a string (you may wish to refer to Section 5.5.1 on string methods).

After you're done with a file, whether reading or writing, you must close the filehandle:

filehandle.close()

Storing & Restoring data

Say you have an array of data that your Python program calculated, and you'd like to use this data in another Python program later. Rather than writing some complex text file interpretation code for writing the data to a file and then reading it later, you can use the 'pickle' module (so named because you're preserving the data!). You need a filehandle that's open for writing (let's call it filehandle), and some data (which can be pretty much anything - a string, an array, an array of arrays, whatever), which we'll call data.

pickle.dump(data, filehandle)

To get the data back, you must open the same file for reading, and use the following code:

data = pickle.load(filehandle)

4. Control flow, or, how Python knows what happens when


This section covers how to get the Python interpreter to execute commands, or not to execute them, in the order you want it to. As was stated in Section 5.1, in the simplest case, Python merely runs through the source file executing each command one after another, from top to bottom.

4.1. Blocks and whitespace in Python

In most programming languages, tabs, new lines and spaces (so-called 'whitespace') have no meaning to the computer, and are merely added to make the code more legible to the programmer. In Python, whitespace is 'syntactically significant'. To be specific:

a) a command written on one line can't just run over to the next line (unless you add a backslash: \ at the end of the line). For example:

print
"Hello, World"

will not work, but:

print "Hello, World!"

and

print \
"Hello, World!"

will.

b) Lines of code with different levels of indentation are treated differently. In other words, if you have more whitespace characters at the front of one line than another, Python thinks of it as part of a different 'block':

print "This is part of one block!"
print "This is a different block!"
print "Back to the first block."

Blocks are key to using IF statements and loops.

Although you can use both spaces and tabs to indent your code, it is recommended that you pick one and only use that one (since one tab looks like four spaces to you, but to Python, one tab = indentation level 1, and four spaces = indentation level 4).

4.2. The IF statement

This is how you get Python to do interesting things. An IF statement is basically a function that takes something that can be evaluated as a Boolean argument and, if true, executes the block following the statement:

a = 2
if ( a > 1):
print "Yes, ", a, " is greater than 1!"

Note the key elements:
a) a Boolean comparison inside the parentheses
b) a colon after the if (telling it to apply the statement to the entire following block
c) a block, delimited by a higher indentation level.

You can append 'elif' statements to an if statement, which also take a Boolean argument, and only attempt to evaluate if the initial if statement failed:

a = 1
if ( a < 1 ):
print "Yes, ", a, " is greater than 1!"
elif( a == 1 ):
print "Yes, ", a, " is equal to 1!"

After any if and elif statements, you can add an 'else' clause, which will execute only when the if clause and all elifs failed:

a = 9
if ( a < 1 ):
print "Yes, ", a, " is greater than 1!"
elif( a == 1 ):
print "Yes, ", a, " is equal to 1!"
else:
print a, " is less than 1!"

The colon and indentation can be omitted if you are only executing one command, by putting everything on one line:

a = 2
if (a == 2) print "The value is two."

4.3. Loops

Loops are how you get Python to repeat code a number of times without having to repeat it forever. There are two types of loop in python: while and for.

The while loop takes a Boolean argument, like an if statement, and executes the subsequent block as long as the argument evaluates as true. For example, the following code will print the numbers 1 through 9:

a = 1

while a < 10:
print a
a = a+1

You must be cautious to make sure that this sort of loop will end! In general it is important to be careful about termination conditions for loops. What is the final value of the variable a in the above code? Make sure you understand why the loop above only gets to the number 9.

The for loop is probably the loop you'll use most often. It is rather different from for loops in other languages. You can iterate over any sort of list. You first specify an arbitrary name for one item of the list, and then the list:

list = [0, 1, 2, 3]

for item in list:
print item

If, as is frequent, you need to iterate over a list of numbers, the range function is useful. This function produces an array with the specified number sequence in it.

for number in range(3):
print number # prints 0, then 1, then 2, then 3

The function can take several other parameters. If a second parameter is added, the two numbers are treated as the starting point and end point:

for number in range (1,3):
print number # prints 1,2,3

If a third parameter is added, this number is treated as the increment between successive numbers. This number can be positive or negative:

for number in range (2,-2,-2)
print number # prints 2, 0, -2

5. Data types


This section covers the basics of what any programming language works with: data

Data comes in two basic forms: literals, (for example, the number 2, or the string "Hello, World") and variables (which are words or symbols that are used just like a literal, but can have any value). You can think of a variable as being a container that stores a value.

5.1. Strings


Strings are like sentences (and in fact, often are). They're sequences of typographical characters, like numbers and letters, and are delimited by several types of quotation marks:

a) Single quotes: 'This is a string'
b) Double quotes: "This is a string"
c) Triple quotes:
"""This is a string
that extends over several lines"""

Generally speaking, there is no difference what sort of delimiter you choose to enclose your string in. The differences arise due to the symbols that mean special things to Python. For example, you can't use a simple single quote mark in a string delimited by single quotes, since Python will interpret it as the end of the string. So if you have text that has a lot of single quotes, it's better to use double quotes to enclose your text, and vice-versa. To display a special character in a string, you need to tell Python that it's not what it seems to be, via the 'escape symbol', the backslash:

print ''Hello, it's me!" # prints: Hello, it's me!
print 'Hello, it\'s me!" # same thing
print "Your dad said: \"I'm coming home late.\"" # prints: Your dad said: "I'm coming home late."

You can also indicate certain whitespace characters by escape sequences:

print "This is one line.\nThis will appear on the next line." # the \n tells Python to output a newline

You also need to escape the backslash, to output a backslash:

print "The Windows system folder is C:\\Windows\\System" #prints: The Windows system folder is C:\Windows\System

A list of escape sequences follows:

\n Newline
\t Tab
\' Single quote
\" Double quote
\\ Backslash

You can use triple-quoted strings for text that ignores all escape sequences (previously mentioned with respect to docstrings):

"""This text won't care that there are double quotes "" single quotes ' ' or backslashes\ strewn
about
it even preserves tabs and newlines! it only ends when it sees another triple quote mark ---> """

5.1.1. String operations


String manipulation is one of the number one things that simple programs are written to do. There are a few key functions that you'll use frequently: concatenating strings; getting the length of a string; extracting subsets of a string; modifying subsets of a string; and checking if a string includes a given substring.

Concatenating strings is easy in Python: you just add them with +:

firstword="Hello"
secondword="world!"
phrase = firstword+", "+secondword
print phrase # prints "Hello, world!"

As mentioned previously, you can also repeat strings with *:

phrasetwice = phrase*2 #"Hello, world!Hello, world!"

To extract a substring from a string, you should understand how array indexing works. Consider the string "phrase" in the example above ("Hello, world!"). This string is a list of characters, each of which has a unique number that indicates its position in the string, starting with 0. So phrase[0] = "H", phrase [1] = "e" and so on. You can also refer to characters by a negative number starting from the end of the string: phrase[-1] = "!", phrase[-2] = "d" and so on. To refer to a substring of more than one letter, use a colon:

phrase[1:4] = "ello"
phrase[-6:-2] = "world"
phrase[1:-1] = ello, world!"

Including the colon but omitting one of the numbers extends the reference to the beginning or end of the string:

phrase[1:] = "ello, world!"
phrase [:-2] = "Hello, world"

This functionality can be useful for cutting out the last letter of a string, for example.

To find out the length of a string, use the following method:

len(phrase) # returns the integer number 13

There are two useful ways of finding if a string includes a particular substring (without getting into the wide world of regular expressions).

Using the "find" method searches for the given substring and returns the position index of the first matching spot and -1 otherwise:

phrase.find("world") # returns 7

Using the "count" method returns the number of times the given substring occurs in the test string:

phrase.count("l") # returns 3

To replace one substring with another, the replace method works well:

greeting = phrase.replace("world", "Mom") # greeting = "Hello, Mom!"

You can split a string into an array of its component words:

array = phrase.split(); array[0] = "Hello,"; array[1] = "World!"

(You could specify a different separator character by giving an argument inside the parentheses of the split method. This is occasionally useful when turning string data delimited by tabs or commas into arrays.)

Lastly you can convert strings into upper or lower case with the 'upper' and 'lower' methods:

print phrase.upper # outputs "HELLO, WORLD!"

5.2. Lists & Arrays


Arrays are rather like matrices in linear algebra. In regular Python, what is generally dealt with is lists: They are lists of things, indexed in all the same ways strings are:

list = ["an", "apple", "a", "day]

print list[0]# "an"
print list[2] # "a"
print list[1:3] # "["apple" "a" "day"]"

You can have lists of lists (multidimensional lists):

threesquarematrix = [[1,2,3],[4,5,6],[7,8,9]]

Lists can be treated in much the same way strings can,

There is also something called a tuple, which is mostly the same as a list, but created with round parentheses rather than square brackets, and whose contents cannot be changed after creation (i.e., trying to assign tuple[3] = "orange" will result in an error).

5.2.1. Array operators


There is actually a true array data type, which can be created from a list or tuple with the 'array' function:

array([1,2,3,4])

Note the presence of both the parentheses and square brackets. the square brackets denote a list, while the parentheses turn that list into an array.

To use arrays, you must include one of the following lines at the start of your code:

import numpy

or

from numpy import *

For more on arrays, refer to the numpy tutorial.

5.3. Objects; conversion of data types


Python is an object-oriented programming language, which means that basically, everything in Python is an object. Python hides most of this functionality from you unless you need it. In general, when you write a line such as the following:

phrase.replace("world", "Mom")

you are invoking the "method" 'replace' on the string object named phrase with the arguments given in the parentheses.

Remember, while every variable in Python is an object, different objects may be of different type even if they contain the same information (e.g. the string "5" is not the same as the number 5) which is why data type conversion is important.

The following functions are useful:

b = int(a) # interprets variable 'a' as an integer number and puts it into variable 'b' (truncating--i.e., rounding down--any decimals)
b = float(a) # interprets variable 'a' as a floating point (decimal) number and puts it into variable 'b'
b = str(a) # formats the variable 'a' into a nicely-printable string
b = bin(a) # turns the number 'a' into a binary string (i.e. a string consisting of 1s and 0s)

N.B. Remember, the raw_input function always returns a string! So convert your result to the appropriate type before doing anything with it.

6. Functions & Includes

These are the two major ways of saving yourself programming time, by reusing the code you or other people have already written (and hopefully tested). Small functions will make , while some judiciously-chosen includes will save you hours and hours of rewriting.

6.1 Functions

Functions are probably the most useful way of saving yourself time. Most programs involve repeatedly performing some simple operation. Putting this calculation into a function and then calling the function results in code that is easier to read, less buggy (you only need to debug it once) and faster to write. A function looks like this:

def functionname(argument1, argument2):
#code
return returnvalue

6.1.1. Return values

The primary way of getting data out of a function is with the return value. The return value can be an array, which allows you to return multiple things to the main program.

Return values are optional; a function's output may not need any further processing (for example, if you had a function which merely printed out a warning message, you wouldn't need to do any further calculation).

You can accomplish the same task with global variables, but this is messier.

Here's an example of getting multiple return values:

(five, twentyfive, onetwentyfive) = listexample(5) # gives 5, 25, 125 to the corresponding variables

def listexample(input):
num = input
numsquared = num*input
numcubed = numsquared*input
return num, numsquared, numcubed

6.1.2. Arguments

The primary way of getting input to a function is with arguments. Like return values, these are not required (although most useful functions, like most useful programs, take some input and produce some output). In the example above, the variable 'input' (with the given value 5) is the argument.

You can make a function more flexible by assigning default values to arguments:

a = 2
b = 3
print sum(a,b) # prints 5
print sum(a,b,10) # prints 15

def sum (a, b, c=0):
return (a+b+c)

Note that specifying a default value for c allows you to skip it when it's not needed.

6.1.3. Global variables

Python is much looser on 'scope' than many other programming languages. That said, to modify one of your program's variables inside a function, you will need to use the 'global' operator:

fruit = "apples"
gotomarket() # converts apples into oranges
print "I like to eat ", fruit, "!" #prints "I like to eat oranges!"
def gotomarket():
global fruit
fruit = "oranges"
return

In the above program, fruit (originally defined as 'apples') is converted to 'oranges' by the function 'gotomarket()', and then printed.

As an aside, global variables are deprecated in computer science. According to most modern computer scientists, as well as in my own experience, cleaner, less-buggy code results from strict scoping-- i.e., only passing data between the main program and subroutines via return values and arguments:

fruit = "apples"
fruit = gotomarket(fruit) # converts apples into oranges
print "I like to eat ", fruit, "!" #prints "I like to eat oranges!"
def gotomarket(foodin): #passes data to the function via an argument
foodout = "oranges"
return foodout # passes data back to the main program via a return value

But it's a matter of style; some people are much more comfortable with global variables.

6.1.4. Recursion

A neat trick for making functions simpler (or at least, shorter!) is to include the function inside itself. This is probably best explained by an example:

def fact(n):
if (n<=1):
return 1
else:
return n*fact(n-1)

When you call fact(3), the following happens:

fact(3)?
return 3* fact(2)
fact(2)?
return 2*fact(1)
fact(1)?
return 1
return 3*2*1 = 6

When writing recursive functions, it is very important to ensure that the recursion ends somewhere! Note that although the function keeps calling itself over and over, it ends once it reaches the number 1.

Python does have a built-in recursion limit (1000 recursions) but this may be modified via the sys module.

6.2. Includes


One of Python's strengths is its vast quantity of community-created content. available to be inserted into your code in the form of modules. These are typically added using one of the following lines:

from module import *

or

import module

In general it is better to use the second form, and best to only import those methods you need. For example:

from math import cos

Importing only those functions you need will result in faster, smaller and less buggy code.

The functions you've imported can be used like regular functions:

cos(0) # 1

6.2.1. Some common includes

  • math - Mathematical operations
  • sys - python built-in system settings and variables (such as the recursion limit, program arguments, etc)
  • vpython - Visual programming routines
  • numpy - numeric routines
  • scipy - scientific routines
  • RS - R / S-Plus bindings for Python
  • Matplotlib - Plotting functions
  • getopt - advanced command-line argument processing
  • os - Operating system commands (path manipulation, etc.)
  • random - Better way to generate random numbers (random.random) [can also be done with os.urandom()]
  • time - Time functions (get current time, calculate time later, etc)
  • datetime - Date & time functions

7. Miscellanea

7.1. System variables


  • os.getcwd() - The current working directory
  • os.chdir(newpath) - Changes current working directory to newpath
  • sys.argv - Program name, and command-line arguments
  • sys.path - Python path (list of folders that Python looks in for functions and modules)
  • sys.version - Version of Python running

7.2. Program arguments

One of the more important variables in the sys module is sys.argv, which is a list containing all the arguments passed to the program at run time. This is sort of the standard way of interacting with command-line programs in Unix: you type the name of the program, followed by any parameters, at the command prompt:

[example unix prompt]# python pythontest.py Arg1 Arg2

After importing the sys module, you may access the list sys.argv, which is a list of strings, the first of which is the name of the program running, and the rest of which are the command-line arguments:

print sys.argv # "[pythontest.py Arg1 Arg2]"

For complex argument processing, you should probably use the Getopt module.