The Python Tutorial

By Sue Bradley,2014-06-12 20:59
10 views 0
The Python Tutorial

    The Python Toturial

    1. Whetting Your Appetite

    If you do much work on computers, eventually you find that there‘s some task you‘d

    like to automate. For example, you may wish to perform a search-and-replace over a large

    number of text files, or rename and rearrange a bunch of photo files in a complicated way.

    Perhaps you‘d like to write a small custom database, or a specialized GUI application, or a

    simple game.

    If you‘re a professional software developer, you may have to work with several

    C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is too slow.

    Perhaps you‘re writing a test suite for such a library and find writing the testing code a

    tedious task. Or maybe you‘ve written a program that could use an extension language,

    and you don‘t want to design and implement a whole new language for your application.

    Python is just the language for you.

    You could write a Unix shell script or Windows batch files for some of these tasks, but

    shell scripts are best at moving around files and changing text data, not well-suited for

    GUI applications or games. You could write a C/C++/Java program, but it can take a lot of

    development time to get even a first-draft program. Python is simpler to use, available on

    Windows, Mac OS X, and Unix operating systems, and will help you get the job done

    more quickly.

    Python is simple to use, but it is a real programming language, offering much more

    structure and support for large programs than shell scripts or batch files can offer. On the

    other hand, Python also offers much more error checking than C, and, being a

    very-high-level language, it has high-level data types built in, such as flexible arrays and

    dictionaries. Because of its more general data types Python is applicable to a much larger

    problem domain than Awk or even Perl, yet many things are at least as easy in Python as

    in those languages.

    Python allows you to split your program into modules that can be reused in other

    Python programs. It comes with a large collection of standard modules that you can use

    as the basis of your programs or as examples to start learning to program in Python.

    Some of these modules provide things like file I/O, system calls, sockets, and even

    interfaces to graphical user interface toolkits like Tk.

    Python is an interpreted language, which can save you considerable time during

    program development because no compilation and linking is necessary. The interpreter

    can be used interactively, which makes it easy to experiment with features of the

    language, to write throw-away programs, or to test functions during bottom-up program

    development. It is also a handy desk calculator.

    Python enables programs to be written compactly and readably. Programs written in

    Python are typically much shorter than equivalent C, C++, or Java programs, for several


    ? the high-level data types allow you to express complex operations in a single


    ? statement grouping is done by indentation instead of beginning and ending brackets;

     1 / 102

    The Python Toturial ? no variable or argument declarations are necessary.

    Python is extensible: if you know how to program in C it is easy to add a new built-in

    function or module to the interpreter, either to perform critical operations at maximum

    speed, or to link Python programs to libraries that may only be available in binary form

    (such as a vendor-specific graphics library). Once you are really hooked, you can link the

    Python interpreter into an application written in C and use it as an extension or command

    language for that application.

    By the way, the language is named after the BBC show ―Monty Python‘s Flying

    Circus‖ and has nothing to do with reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged!

    Now that you are all excited about Python, you‘ll want to examine it in some more

    detail. Since the best way to learn a language is to use it, the tutorial invites you to play

    with the Python interpreter as you read.

    In the next chapter, the mechanics of using the interpreter are explained. This is

    rather mundane information, but essential for trying out the examples shown later.

    The rest of the tutorial introduces various features of the Python language and

    system through examples, beginning with simple expressions, statements and data types,

    through functions and modules, and finally touching upon advanced concepts like

    exceptions and user-defined classes.

    2. Using the Python Interpreter

    2.1. Invoking the Interpreter

    The Python interpreter is usually installed as /usr/local/bin/python on those machines

    where it is available; putting /usr/local/bin in your Unix shell‘s search path makes it possible to start it by typing the command


    to the shell. Since the choice of the directory where the interpreter lives is an

    installation option, other places are possible; check with your local Python guru or system

    administrator. (E.g., /usr/local/python is a popular alternative location.)

    On Windows machines, the Python installation is usually placed in C:\Python26,

    though you can change this when you‘re running the installer. To add this directory to your

    path, you can type the following command into the command prompt in a DOS box:

    set path=%path%;C:\python26

    Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the

    primary prompt causes the interpreter to exit with a zero exit status. If that doesn‘t work,

    you can exit the interpreter by typing the following command: quit().

    The interpreter‘s line-editing features usually aren‘t very sophisticated. On Unix,

    whoever installed the interpreter may have enabled support for the GNU readline library,

    which adds more elaborate interactive editing and history features. Perhaps the quickest

    check to see whether command line editing is supported is typing Control-P to the first

     2 / 102

    The Python Toturial

    Python prompt you get. If it beeps, you have command line editing; see Appendix

    Interactive Input Editing and History Substitution for an introduction to the keys. If nothing

    appears to happen, or if ^P is echoed, command line editing isn‘t available; you‘ll only be

    able to use backspace to remove characters from the current line.

    The interpreter operates somewhat like the Unix shell: when called with standard

    input connected to a tty device, it reads and executes commands interactively; when

    called with a file name argument or with a file as standard input, it reads and executes a

    script from that file.

    A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in command, analogous to the shell‘s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is

    usually advised to quote command in its entirety with single quotes.

    Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file for module as if you had spelled out its full name on the command line.

    Note that there is a difference between python file and python . In the latter case, input requests from the program, such as calls to input() and raw_input(), are satisfied from file. Since this file has already been read until the end by the parser before the

    program starts executing, the program will encounter end-of-file immediately. In the

    former case (which is usually what you want) they are satisfied from whatever file or

    device is connected to standard input of the Python interpreter.

    When a script file is used, it is sometimes useful to be able to run the script and enter

    interactive mode afterwards. This can be done by passing -i before the script. (This does not work if the script is read from standard input, for the same reason as explained in the

    previous paragraph.)

    2.1.1. Argument Passing

    When known to the interpreter, the script name and additional arguments thereafter

    are passed to the script in the variable sys.argv, which is a list of strings. Its length is at

    least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0]

    is set to the full name of the located module. Options found after -c command or -m

    module are not consumed by the Python interpreter‘s option processing but left in

    sys.argv for the command or module to handle.

    2.1.2. Interactive Mode

    When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter prints a welcome message stating its version

    number and a copyright notice before printing the first prompt:


     3 / 102

    The Python Toturial

    Python 2.6 (#1, Feb 28 2007, 00:02:06)

    Type "help", "copyright", "credits" or "license" for more information.


    Continuation lines are needed when entering a multi-line construct. As an example,

    take a look at this statement:

    >>> the_world_is_flat = 1

    >>> if the_world_is_flat:

    ... print "Be careful not to fall off!"


    Be careful not to fall off!

    2.2. The Interpreter and Its Environment

    2.2.1. Error Handling

    When an error occurs, the interpreter prints an error message and a stack trace. In

    interactive mode, it then returns to the primary prompt; when input came from a file, it exits

    with a nonzero exit status after printing the stack trace. (Exceptions handled by an except

    clause in a try statement are not errors in this context.) Some errors are unconditionally

    fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and

    some cases of running out of memory. All error messages are written to the standard error

    stream; normal output from executed commands is written to standard output.

    Typing the interrupt character (usually Control-C or DEL) to the primary or secondary

    prompt cancels the input and returns to the primary prompt. [1] Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement.

    2.2.2. Executable Python Scripts

    ? On BSD‘ish Unix systems, Python scripts can be made directly executable, like shell

    scripts, by putting the line

    #! /usr/bin/env python

    (assuming that the interpreter is on the user‘s PATH) at the beginning of the script and giving the file an executable mode. The #! must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ('\n'), not a

    Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a

    comment in Python.

    The script can be given an executable mode, or permission, using the chmod


    $ chmod +x

    On Windows systems, there is no notion of an ―executable mode‖. The Python

    installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.

     4 / 102

    The Python Toturial 2.2.3. Source Code Encoding

    It is possible to use encodings different than ASCII in Python source files. The best

    way to do it is to put one more special comment line right after the #! line to define the

    source file encoding:

    # -*- coding: encoding -*-

    With that declaration, all characters in the source file will be treated as having the

    encoding encoding, and it will be possible to directly write Unicode string literals in the

    selected encoding. The list of possible encodings can be found in the Python Library

    Reference, in the section on codecs.

    ? For example, to write Unicode literals including the Euro currency symbol, the

    ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value

    164. This script will print the value 8364 (the Unicode codepoint corresponding to the

    Euro symbol) and then exit:

    # -*- coding: iso-8859-15 -*-

    currency = u"?"

    print ord(currency)

    If your editor supports saving files as UTF-8 with a UTF-8 byte order mark (aka BOM),

    you can use that instead of an encoding declaration. IDLE supports this capability if

    Options/General/Default Source Encoding/UTF-8 is set. Notice that this signature is not understood in older Python releases (2.2 and earlier), and also not understood by the

    operating system for script files with #! lines (only used on Unix systems). ? By using UTF-8 (either through the signature or an encoding declaration), characters

    of most languages in the world can be used simultaneously in string literals and

    comments. Using non-ASCII characters in identifiers is not supported. To display all

    these characters properly, your editor must recognize that the file is UTF-8, and it

    must use a font that supports all the characters in the file.

    2.2.4. The Interactive Startup File

    When you use Python interactively, it is frequently handy to have some standard

    commands executed every time the interpreter is started. You can do this by setting an

    environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.

    This file is only read in interactive sessions, not when Python reads commands from

    a script, and not when /dev/tty is given as the explicit source of commands (which

    otherwise behaves like an interactive session). It is executed in the same namespace

    where interactive commands are executed, so that objects that it defines or imports can

    be used without qualification in the interactive session. You can also change the prompts

    sys.ps1 and sys.ps2 in this file.

    If you want to read an additional start-up file from the current directory, you can

    program this in the global start-up file using code like if os.path.isfile(''):

    execfile(''). If you want to use the startup file in a script, you must do this

    explicitly in the script:

     5 / 102

    The Python Toturial

    import os

    filename = os.environ.get('PYTHONSTARTUP')

    if filename and os.path.isfile(filename):


    3. An Informal Introduction to Python

    In the following examples, input and output are distinguished by the presence or

    absence of prompts (>>> and ...): to repeat the example, you must type everything after

    the prompt, when the prompt appears; lines that do not begin with a prompt are output

    from the interpreter. Note that a secondary prompt on a line by itself in an example means

    you must type a blank line; this is used to end a multi-line command.

    Many of the examples in this manual, even those entered at the interactive prompt,

    include comments. Comments in Python start with the hash character, #, and extend to

    the end of the physical line. A comment may appear at the start of a line or following

    whitespace or code, but not within a string literal. A hash character within a string literal is

    just a hash character. Since comments are to clarify code and are not interpreted by

    Python, they may be omitted when typing in examples.

    ? Some examples:

    # this is the first comment

    SPAM = 1 # and this is the second comment

     # ... and now a third!

    STRING = "# This is not a comment." 3.1. Using Python as a Calculator

    Let‘s try some simple Python commands. Start the interpreter and wait for the primary

    prompt, >>>. (It shouldn‘t take long.)

    3.1.1. Numbers

    The interpreter acts as a simple calculator: you can type an expression at it and it will

    write the value. Expression syntax is straightforward: the operators +, -, * and / work just

    like in most other languages (for example, Pascal or C); parentheses can be used for

    grouping. For example:

    >>> 2+2


    >>> # This is a comment

    ... 2+2


    >>> 2+2 # and a comment on the same line as code


    >>> (50-5*6)/4

     6 / 102

    The Python Toturial 5

    >>> # Integer division returns the floor:

    ... 7/3


    >>> 7/-3


    The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is

    displayed before the next interactive prompt:

    >>> width = 20

    >>> height = 5*9

    >>> width * height


    ? A value can be assigned to several variables simultaneously:

    >>> x = y = z = 0 # Zero x, y and z

    >>> x


    >>> y


    >>> z


    ? Variables must be ―defined‖ (assigned a value) before they can be used, or an error

    will occur:

    >>> # try to access an undefined variable

    ... n

    Traceback (most recent call last):

     File "", line 1, in NameError: name 'n' is not defined

    ? There is full support for floating point; operators with mixed type operands convert the

    integer operand to floating point:

    >>> 3 * 3.75 / 1.5


    >>> 7.0 / 2


    Complex numbers are also supported; imaginary numbers are written with a suffix of j

    or J. Complex numbers with a nonzero real component are written as (real+imagj), or can

    be created with the complex(real, imag) function. >>> 1j * 1J


    >>> 1j * complex(0,1)


    >>> 3+1j*3


    >>> (3+1j)*3


     7 / 102

    The Python Toturial

    >>> (1+2j)/(1+1j)


    Complex numbers are always represented as two floating point numbers, the real

    and imaginary part. To extract these parts from a complex number z, use z.real and


    >>> a=1.5+0.5j

    >>> a.real


    >>> a.imag


    The conversion functions to floating point and integer (float(), int() and long()) don‘t

    work for complex numbers there is no one correct way to convert a complex number to

    a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part.

    >>> a=3.0+4.0j

    >>> float(a)

    Traceback (most recent call last):

     File "", line 1, in ?

    TypeError: can't convert complex to float; use abs(z)

    >>> a.real


    >>> a.imag


    >>> abs(a) # sqrt(a.real**2 + a.imag**2)


    In interactive mode, the last printed expression is assigned to the variable _. This

    means that when you are using Python as a desk calculator, it is somewhat easier to

    continue calculations, for example:

    >>> tax = 12.5 / 100

    >>> price = 100.50

    >>> price * tax


    >>> price + _


    >>> round(_, 2)


    ? This variable should be treated as read-only by the user. Don‘t explicitly assign a

    value to it you would create an independent local variable with the same name

    masking the built-in variable with its magic behavior.

    3.1.2. Strings

    ? Besides numbers, Python can also manipulate strings, which can be expressed in

    several ways. They can be enclosed in single quotes or double quotes:

    >>> 'spam eggs'

    'spam eggs'

     8 / 102

    The Python Toturial

    >>> 'doesn\'t'


    >>> "doesn't"


    >>> '"Yes," he said.'

    '"Yes," he said.'

    >>> "\"Yes,\" he said."

    '"Yes," he said.'

    >>> '"Isn\'t," she said.'

    '"Isn\'t," she said.'

    ? String literals can span multiple lines in several ways. Continuation lines can be used,

    with a backslash as the last character on the line indicating that the next line is a

    logical continuation of the line:

    hello = "This is a rather long string containing\n\ several lines of text just as you would do in C.\n\

     Note that whitespace at the beginning of the line is\


print hello

    Note that newlines still need to be embedded in the string using \n; the newline

    following the trailing backslash is discarded. This example would print the following:

    This is a rather long string containing

    several lines of text just as you would do in C.

     Note that whitespace at the beginning of the line is significant.

    Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines

    do not need to be escaped when using triple-quotes, but they will be included in the string.

    print """

    Usage: thingy [OPTIONS]

     -h Display this usage message

     -H hostname Hostname to connect to """

    ? produces the following output:

    Usage: thingy [OPTIONS]

     -h Display this usage message

     -H hostname Hostname to connect to

    If we make the string literal a ―raw‖ string, \n sequences are not converted to newlines,

    but the backslash at the end of the line, and the newline character in the source, are both

    included in the string as data. Thus, the example:

    hello = r"This is a rather long string containing\n\ several lines of text much as you would do in C."

print hello

    ? would print:

    This is a rather long string containing\n\

     9 / 102

    The Python Toturial

    several lines of text much as you would do in C.

    The interpreter prints the result of string operations in the same way as they are typed

    for input: inside quotes, and with quotes and other funny characters escaped by

    backslashes, to show the precise value. The string is enclosed in double quotes if the

    string contains a single quote and no double quotes, else it‘s enclosed in single quotes.

    (The print statement, described later, can be used to write strings without quotes or


    Strings can be concatenated (glued together) with the + operator, and repeated with *:

    >>> word = 'Help' + 'A'

    >>> word


    >>> '<' + word*5 + '>'


    Two string literals next to each other are automatically concatenated; the first line

    above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:

    >>> 'str' 'ing' # <- This is ok


    >>> 'str'.strip() + 'ing' # <- This is ok


    >>> 'str'.strip() 'ing' # <- This is invalid

     File "", line 1, in ?

     'str'.strip() 'ing'


    SyntaxError: invalid syntax

    Strings can be subscripted (indexed); like in C, the first character of a string has

    subscript (index) 0. There is no separate character type; a character is simply a string of

    size one. Like in Icon, substrings can be specified with the slice notation: two indices

    separated by a colon.

    >>> word[4]


    >>> word[0:2]


    >>> word[2:4]


    ? Slice indices have useful defaults; an omitted first index defaults to zero, an omitted

    second index defaults to the size of the string being sliced.

    >>> word[:2] # The first two characters


    >>> word[2:] # Everything except the first two characters


    ? Unlike a C string, Python strings cannot be changed. Assigning to an indexed position

    in the string results in an error:

     10 / 102

Report this document

For any questions or suggestions please email