Skip to main content

skip to main content

developerWorks  >  Linux  >

Python 101 cheat sheet

A quick reference document for newcomers to the language

developerWorks
Document options

Document options requiring JavaScript are not displayed


Rate this page

Help us improve this content


Level: Introductory

Evelyn Mitchell, CEO, Tummy.com

01 Feb 2000

Python columnist Evelyn Mitchell brings you a quick reference and learning tools for newbies who want to get to know the language. Print it, keep it close at hand, and get down to programming!

Running Python

Interpreter
To start the Python interpreter, type python:

$ python
Python 1.5.2 (#1, May 28 1999, 14:49:17)  [GCC 2.7.2.3] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>

A simple command:

>>> print "Hello World"
Hello World
>>>

To leave the interpreter, type Ctrl-D (on Linux) or Ctrl-Z (Windows) or:

>>> import sys
>>> sys.exit()
$ 

or:

$ python
Python 1.5.2 (#1, May 28 1999, 14:49:17) [GCC 2.7.2.3] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> raise SystemExit
$ 

Note: The examples above are in the interpreter (>>> denotes the prompt); some are as if they were run from a file.

Program files
You can also run Python programs from a file. The usual extension is .py

If we create a file called helloworld.py:

#!/usr/bin/env python

print "Hello World"

we can run it with the command:

$ python helloworld.py 
Hello World
$ 



Back to top


Language

Statements end in newlines, not with semicolons (;), for example). So the following is a complete command:

>>>print "hello"
hello

Blocks are indicated by indentation following a statement ending in a colon (:) as in:

>>> name = "Larry"
>>> if name == "George":
...    print "Hi George"
... else:
...    print "Who are you?"
...    print "You're not George!"
... 
Who are you?
You're not George!
>>>

The ... in this example shows that the block continues until the blank line.

Comments start with # and continue to the end of the line:

print "Tell me."     # This is a comment

Identifiers
Identifers are used to name variables, methods, functions or modules. They must start with a non-numeric character, may contain letters, numbers, and underscore (_). Identifiers are case sensitive.

B = 4
b = 2
if b != B:
	print 'small b is not equal to large B'

Reserved words (native to Python):

and		elif		global		or
assert		else		if		pass
break		except		import		print
class		exec		in		raise
continue	finally		is		return
def		for		lambda		try
del		from		not		while

Identifers with leading __ (double underscore) often have special meanings. Names of variables or functions with leading and trailing __ are used for built-in symbols:

__name__      the name of the function
__doc__       the doc string
__init__()    what we do on startup

Types

  • Numeric
    Numeric types are: integer, long integer, floating-point, and complex.
    >>> x = 4
    >>> int (x)
    4
    >>> long(x)
    4L
    >>> float(x)
    4.0
    >>> complex (4, .2)
    (4+0.2j)
    >>> 

  • String literals
    Enclosing strings in pairs of quotes (', " ,"""). Two strings together without an operator joins the adjacent strings:
    >>> print "Hi" "there"
    Hithere
    >>>

    Backslash (\) escapes special characters except in raw strings:

    >>> print r'\n\\'     # not backslash escaped
    \n\\

    Raw strings are often used for regular expressions, because they have quite a few backslashes in them:

    '\\[foo\\]'
    r'\[foo\]'           # these are the same

    The single quote (') and double quote (") are equivalent:

    "Don't enclose strings with ' in 's"
    'Without escaping the \''

  • [ ] Lists
    Integer indexed arrays start at 0:
    >>> months = ["January", "February"]
    >>> print months[0]
    January
    >>> months.append ("March")
    >>> print months
    ['January', 'February', 'March']

    Colon (:) is the slicing operator. It lets you work with a portion of the list. The second argument to the slice is non-inclusive ( 1:2 is the second and up to -- but not including -- the third item in the list):

    >>> print months[1:2]
    ['February']

    Plus (+) is the concatenation operator:

    >>> print months+months
    ['January', 'February', 'March', 'January', 'February', 'March']
    

    Lists can contain any kind of Python object and can be nested:

    >>> months.append (months)
    >>> print months
    ['January', 'February', 'March', ['January', 'February', 'March' ]]
    >>> months.append(1)
    ['January', 'February', 'March', ['January', 'February', 'March' ], 1]

  • () Tuples

    Tuples are the same as lists, but you can't modify them after you create them. They are usually used as keys into dictionaries.

  • {} Dictionaries

    Dictionaries are associative arrays or hashes, indexed by a key. A key can be any python object, but it is usually a tuple:

    >>> mydict = {"height" : "average",
    ... "skill" : "intermediate",
    ... "salary" : 1000 }
    >>> print mydict
    {'height': 'average', 'skill': 'intermediate', 'salary': 1000}
    >>> print mydict["skill"]
    intermediate
    >>> mydict[0] = 'Foo'
    >>> mydict [(5, 6)] = 'Coordinate 5, 6'

    You can use different sorts of Python objects as keys, such as strings and tuples. Lists and dictionaries cannot be used as keys.

Conditionals

>>> q = 4
>>> h = 5
>>> if q < h :
...    print "first test passed"  # indentation needed
... else:
...    print "first test failed"
... 
first test passed

Boolean keywords are: "or," "and," "not"

Operators are:

 == >= 

File Handling

  • Read a file
    >>> fh = open("helloworld.py")
    >>> for line in fp.readlines()   # read a line (readline method applied to fh)
    ...    print line,         # print line, adding newline at end 
    ... 
    #!/usr/bin/python
    
    print "Hello World"
    >>> fh.close()

  • Write a file
    $ python
    Python 1.5.2 (#1, May 28 1999, 14:49:17)  [GCC 2.7.2.3] on linux2
    Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    >>> fh = open("out.txt", "w")
    >>> fh.write ("we're writing...\n")
    >>> fh.close()
    >>>                      # I typed ^D to exit
    $ cat out.txt
    we're writing...
    $ 

Loops
For is used to iterate over the members of a sequence. It can work with any sequence type (lists, tuples, dictionaries):

>>> for x in range(1,5):
... print x
... 
1
2
3
4

Range creates a sequence described by ([start,] end [,step]), where the start and step are optional. Start is assumed to be 0 and step is assumed to be 1.



Back to top


Functions

Functions are named using the def keyword:

>>> def myfunc(a,b):
...     sum = a + b
...     return sum
...             
>>> myfunc (5,6)      
11

When you create functions, you can give them default parameters:

>>> def myfunc(a=4,b=6):
...     sum = a + b
...     return sum
... 
>>> myfunc()              # we use both defaults
10

You can give functions keyword parameters, so the order of parameters doesn't matter:

>>> myfunc(b=4)           # a defaults to 4, we override the value of b
8



Back to top


Classes

Classes contain collections of methods. Each method refers to the object as the first argument (self) as follows. (See Evelyn's previous column, Python 101: Testing your code , for a complete discussion.)

class PenguinPen:
    def __init__(self):
        self.penguinCount = 0

    def add (self, number = 1):
        """ Add one or more penguins to the pen
        The default number of penguins to add is 1 """
        self.penguinCount = self.penguinCount + number

    def remove (self, number = 1):
        """ Remove one or more  penguins from the pen """
        self.penguinCount = self.penguinCount - number

    def population (self):
        """ How many penguins in the pen? """
        return self.penguinCount



Back to top


Exceptions

When an error occurs, an exception is thrown, and a traceback is displayed. I created a file called except.py and it contains:

#!/usr/bin/python
print a

If I run it, it returns:

sylvia:/tmp$ python except.py 
Traceback (innermost last):
  File "except.py", line 2, in ?
    print a
NameError: a

If you catch the exception, you can handle it:

>>> try: fh=open("new.txt", "r")
... except IOError, e:
...   print e
... 
[Errno 2] No such file or directory: 'new.txt'

You can signal your own exception with the raise statement:

>>> raise MyException

You can also use an exception to quit the interpreter:

>>> raise SystemExit



Back to top


Modules

A module is collection of methods in a file ending in .py. The name of the file determines the name of the module in most cases:

I created a file called mymodule.py containing:

def one(a):
   print "in one"
   
def two (c):
   print "in two"

To use a module, you import it. dir() lists the contents of a module:

>>> import mymodule
>>> dir(mymodule)
['__builtins__', '__doc__', '__file__', '__name__', 'one', 'two']
>>> one
>>> mymodule.one(2)
in one



Resources

  • Download Python at the Python.org Web site, where you'll find binaries, source, and RPM distributions.

  • See Python.org's list of modules.

  • See Python.org's documentation and mailing lists.

  • Join the Community of Python.

  • Learn more about JPython.

  • Programming Python Mark Lutz; O'Reilly, 1996. Although it is slightly out of date now, it is the most complete Python programming book available now. The tutorial in Appendix E is highly recommended.

  • Learning Python Mark Lutz and David Ascher; O'Reilly, 1999. This is a very readable and complete introduction to Python, and the book that I recommend to new programmers who are interested in learning Python and programming at the same time.

  • Internet Programming with Python Aaron Watters, Guido van Rossum, and Jim Ahlstrom. The Python guru book, written by three of the most senior members of the Python community. This book emphasizes Internet programming, including CGI scripting and generating HTML documents. Slightly out of date.

  • "Python 101: Testing your code" (developerWorks, December 1999) illustrates the use of PythonUnit for unit testing your code.


About the author

Evelyn Mitchell has over a decade of experience doing various technical and programming work with computers. Taking geeking to the next level, she's now working on technical and programming work with humans, in her new position as CEO of tummy.com, ltd. She can be reached at efm@tummy.com.




Rate this page


Please take a moment to complete this form to help us better serve you.



YesNoDon't know
 


 


12345
Not
useful
Extremely
useful
 


Back to top