Interpreter
To start the Python interpreter, type python:
|
A simple command:
|
To leave the interpreter, type Ctrl-D (on Linux) or Ctrl-Z (Windows) or:
|
or:
|
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:
|
we can run it with the command:
|
|
|
Statements end in newlines, not with semicolons (;), for example). So the following is a complete command:
|
Blocks are indicated by indentation following a statement ending in a colon (:) as in:
|
The … in this example shows that the block continues until the blank line.
Comments start with # and continue to the end of the line:
|
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.
|
Reserved words (native to Python):
|
Identifers with leading __ (double underscore) often have special meanings. Names of variables or functions with leading and trailing __ are used for built-in symbols:
|
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 sameThe 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] - () TuplesTuples are the same as lists, but you can’t modify them after you create them. They are usually used as keys into dictionaries.
- {} DictionariesDictionaries 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
|
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):
|
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.
|
|
Functions are named using the def keyword:
|
When you create functions, you can give them default parameters:
|
You can give functions keyword parameters, so the order of parameters doesn’t matter:
|
|
|
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.)
|
|
|
When an error occurs, an exception is thrown, and a traceback is displayed. I created a file called except.py and it contains:
|
If I run it, it returns:
|
If you catch the exception, you can handle it:
|
You can signal your own exception with the raise statement:
|
You can also use an exception to quit the interpreter:
|
|
|
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:
|
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
This text is stolen directly from here
The other Good introduction to Python can be found at this link