Download 165.61 Kb.
Size165.61 Kb.
  1   2   3
Python Primer
Patrice Koehl

Modified by Xin Liu in Apr., 2011

Department of Computer Sciences, University of California, Davis.

This primer is mostly a compilation of information found in books / web resources that I highly recommend:

  • ; this is a reference manual, and not a tutorial, but provides invaluable information about the language: do not hesitate to consult it!

  • ; a Beginner’s guide with many links to resources for writing and running Python programs

  • Michael Dawson, “Python programming for the absolute beginner”, 3rd edition, Thomson Course Technology, ISBN: 978-1435455009; this is the class textbook; a great resource book on Python


  1. Why Python?

“Python” is an interpreted computer language developed in the 1980s and first released in 1991. Its design philosophy emphasizes programmer productivity and code readability.

It is important to understand that there is always more than one way to solve a problem. In programming, Python focuses on getting the job done. One Python program may be faster than another, or more concise, or easier to understand, but if both do the same things, there won’t be a judgment that defines which one is “better”. This also means that you do not need to know every detail about the language to do what you want with it.
Python has strength that makes it an ideal language to learn and use:

  • It is completely free, and available on all operating systems

  • It is very easy to learn

  • Python was designed to be easy for humans to write, rather than easy for computers to understand. Python syntax is more like English than many other programming languages

  • Python “talks” texts. It works with words and sentences, instead of characters. Files are series of lines, instead of individual bytes.

  • Python is very portable. Python programs can be run on any computers, as long as Python is installed on it.

  • Python is a “high-level” language: you do not have to worry about the computer’s operation (such as allocation and de-allocation of memory, …).

It is only fair to mention that these strengths can also translate into weaknesses:

  • Python takes care for you of all “low-level” operations: this may not always lead to efficient code

  • Python is interpreted, and loses the efficiency of compiled languages.

  • Python users then to write programs for small, specific jobs. These programs are usually for the programmer’s eye only, and as such are often incomprehensible to everyone but the original programmer. In that respect, I can only emphasize the need for clarity, as well as for useful comments in your source files!

  • Python was designed to be easy for humans. As a consequence, it is relatively lenient on the style you use. This can lead to bad programming habits. As an analogy, think of what would happen to your English writing style if nobody had ever cared about how you write as long as they understand what you have written. To avoid this, the key is to develop first a method to solve your problem that is independent of Python (or any other language), and then to adapt this method to Python.

  1. What is Python used for?

Python has been successfully implemented in many software applications as a scripting language.

Python is a very useful programming language for web applications.
Python is used widely for game development, for 3D animation packages, in the information security industry,…

  1. How do I get Python?

Python has been ported to many platforms, and will certainly run on the standard operating systems such as UNIX, Linux, Solaris, FreeBSD, all flavors of Windows, and Apple MacOS.

Python 2 versus Python 3
In December 2008, the Python consortium released a completely new version of Python, Python 3.0, that is not backward compatible: this means that programs written with Python 1 or Python 2 may not run under Python 3.0. At this stage, we move to Python 3.1.3. If you have Python 2 code, a tool, 2to3, will help you convert most of Python 2.x code to Python 3.x code by handling most of the incompatibilities.
Where to get Python:

  • You can get the source to the latest stable release of Python from Remember that you want Python 3.

  • Binary distributions for some ports are available at the same address

  • You can get binary packages of Python for Linux, Solaris, Mac OS and Windows from ActiveState at (free for download)

Installing Python on Linux/UNIX
Python is freely available, and usually comes packaged with most Linux/UNIX distribution. Type python from a shell prompt to check this. If you see something that starts with the text Python, then you already have python. If you don’t, check the install media (CD or DVD from which you installed Linux): the Python package should be available on it. Otherwise, get the binaries from the site mentioned above.
Installing Python on Mac Os
Again, Python comes packaged with the different flavors of Mac OS X, and you probably have nothing to do! Check it using python from a terminal. If you do not have it, I would advise getting it from ActiveState.
Installing Python on Windows
Installing ActivePython is quite straightforward. Download ActivePython’s Python installer for Windows from the activestate web site (again, it is free for download). Choose the appropriate version for the operating system you have (32 bit, or 64 bit). I would strongly advise using the MSI installer, in which case you will need Windows Installer 2.0+ (which you probably already use). It should work under Vista, but I have not tried it.

  1. Getting an IDE for Python

IDEs (integrated Development Environment) are great tools for learning a computer language and use it efficiently. There are many IDEs available for Python: see for a list of such IDEs.
I strongly recommend IDLE that is available for nearly all platforms. See ; it should come by default when you install Python on Windows; you have to install it however on Linux and MacOS platforms. For the latter, please check: .

  1. Using Python

You have two main ways to use Python:

  • Use it directly through a Control Window: again, I strongly advise using the IDLE interface

  • Write the Python program (module) using a text editor, and then execute this program through the python interpreter. Again, this can be done using IDLE; alternatively, you can use standard text editors for this task (see below)

Editing a Python program
Python source code is just plain test and should be written with a plain text editor, rather than a word processor. If you are using Windows, you can use Notepad, despite its annoying tendency to rename file extension to .txt. You may also use Word, as long as you save the file as text, with line breaks.
I would really recommend getting a good programmer’s editor. For Windows and Mac, I can recommend jEdit ( ): it is free (open source), runs under Windows, Mac OS X, Unix and Linux. It is easy to use, highly customizable, with many useful plugins. Another option for Mac user is TextWrangler ( ).
Naming a Python program
Traditionally, UNIX programs take no extension, while Windows files take a three-letter extension to indicate their type (.exe for an executable, .doc for a document –usually Word file-, .xls for a spreadsheet, …); the standard extension for Python program is py.
Obviously, the choice of the name in front of the extension is entirely yours!

Using Python in an IDE
If you are mainly using your computer in a graphical environment like Windows or X, you may not be familiar with using the command line interface, or “shell”. The “shell” is the program that gets input from you through the keyboard. The “shell prompt” or just “prompt” refers to the text that prompts you to enter a command. The standard prompt in IDLE is:
i.e. 3 chevrons.
In this primer, I will use a prompt that looks like:
I will show the text that you would type in bold and the text the computer generates in italic:
>>> print (“Hello world!”)

Hello World!

  1. Your first Python program

Traditionally, the first program anyone writes in a new language is called “Hello World!”, where you make the program prints that statement. Python allows us to do so using the print statement. The simplest form of the print statement takes a single argument and writes it to the standard output, i.e. the command window you have open. So your program consists of the single statement:

print( “Hello World!”)

You can execute this command directly in the IDLE main window, or you can incorporate it into a Python module, The file contains:


print(‘Hello World!\n’)


The different elements of a Python script:

  • Documenting the program: any line (except the first) starting with a sharp (#) is treated as a command line and ignored. This allows you to provide comments on what your program is doing: this is extremely useful, so use it! More generally, a line in a Python script may contain some Python code, and be followed by a comment. This means that we can document the program “inline”.

  • Keywords: Instructions that Python recognizes and understands. The word print in the program above is one example. There are two types of keywords:

    • functions (such as the print keyword); these are the verbs of the programming language and they tell python what to do.

    • Control keywords, such as if and else.

The number of Python keywords is small:

and del from not while

as elif global or with

assert else if pass yield

break except import print class

exec in raise continue finally

is return def for lambda

It is a good idea to respect keywords, and not use them as names in your programs!

  • Modules: Pythons come with a large list of modules that increases its functionality; these modules add keywords to the small list provided above, but are only available when the module has been specifically called. For example, adding:

use numpy

adds the modules of numerical functions “numpy” that are now accessible to the programmer.

  • Statements: Statements are the sentences of the program. Python is lenient however, and does not need a full stop to end a statement. The indentation levels of consecutive lines are used to generate INDENT and DEDENT, which in turn are used to determine the grouping of statements.

  • White space: White space is the name given to tabs, spaces, and new lines. Python is quite strict about where you put white space in your program. For example, we have seen that we use indentation to help show the block structure of statements.

  • Escape sequences: Python provides a mechanism called “escape sequences” to output special characters/actions: the sequence \n in the program above tells Python to start a new line. Here is a list of the more common escape sequences (also called “metacharacters”):

Escape Sequence





Start a new line


Carriage return


Single quote


Double quote




Back up one character (‘backspace’)


Alarm (rings the system bell)

Simple exercises:

  1. Write a program, that prints the sentence “This is my second program”:

    1. As a single line

    2. With a single word on each line.

  1. Find an online manual for Python

  1. Which of the following statements are likely to cause problems:

    1. print (“This is a valid statement\n”)

    2. print (“This is a valid statement”\n)

    3. print (“This is a ”valid” statement”)

    4. printx (“This is a valid statement\n”)

Chapter 1: Scalar Variables and Data Types

  1. Python as a calculator

The Python 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 on your regular calculator; parentheses can be used for grouping. For example:

>>> 1+3


>>> # This is a comment

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


>>> (60-5*6)/3


>>> 7//3 # Integer division returns the floor:


>>> 7//-3


Remember that, by default, Python only has a limited set of keywords. For example, it only knows how to do the basic mathematical operations (+,-,/,x). If you want a more scientific calculator, you need to first import the math functions included in the module “math”:

From math import *

  1. Python Variables

A variable is a name reference to a memory location. Variables provide an easy handle to keep track of data stored in memory. Most often, we do not know the exact value of what is in a particular memory location; rather we know the type of data that is stored there.

Python has three main types of variables:

  • Scalar variables hold the basic building blocks of data: numbers, and characters.

  • Array variables hold lists referenced by numbers (indices)

  • Dictionary variables hold lists references by labels.

The name of a variable can be practically any combination of characters and of arbitrary length. Note that the type of a variable cannot usually not be guessed from its name: I strongly advise you to choose a name for a variable that makes this type explicit. For example you can use names like X, X_list, X_dic to define a scalar, a list, and a dictionary, respectively.

There are a few rules regarding variable names that you need to be aware of:

  • The first character of the name of a variable cannot be a digit

  • Spaces are one type of characters that are not allowed: use underscore instead.

  • Variables are case sensitive: this means that abc refers to a different location in memory than ABC.

Creating a variable is as simple as making up a variable name and assigning a value to it.
Assigning a value to a variable is easy: all you have to do is write an equation, with the variable name on the left, an = sign, and the value on the left. The = sign is called the assignment operator:

>>>Width=4 # Note that the value of an assignment is not written



>>>print (Area)


>>>x=y=z=0 # Python allows multiple assignments: x, y and z are

set to 0

>>>DNA=’aattgcg’ # assign a string variable

>>>Name_list=[‘John’,’David’] # set up a list of names

  1. Special variable

Python has one special variable, _, that points to the place in memory that stores the more recent result:

>>> 4+5


>>>print( _)


This special variable “_” should be considered as “read-only”, i.e. I strongly advise against assigning a value to it!!

  1. Scalar variables

Python has two types of scalar values: numbers and strings. Both types ca be assigned to a scalar variable.

    1. Numbers

Numbers are specified in any of the common integer or floating point format:

>>>x = 1 # Integer

>>>y = 5.14 # Floating point

>>>z = 3.25E-7 # Scientific notation

Numbers can also be represented using binary or hexadecimal notations, but we will not need that.

Table of the most common number operators in Python:














Integer divide






Absolute value of x


x converted to integer


x converted to float


Assign add


Assign subtract


Assign multiply


Assign divide

Python allows us to use all standard arithmetic operators on numbers, plus a few others. The mathematical operations are performed in the standard order of precedence: power comes first, then multiplication has a higher precedence than addition and subtraction: 2+3*4 is equal to 14, and not 20. If we want the multiplication to be performed on 2+3, we need to include parenthesis: (2+3)*4. These are exactly the rules used by Python.

Some of the operators listed in the table above are unusual, and require more explanation:
The modulo operator:




In the example given above, the variable k holds the remainder of the division of 52 by 3, i.e. 1.

Operating and assigning at once:
Operations that fetch a value from memory, modify it and store it back in memory are very common: Python has introduced a special syntax for those. Generally:
i = i b;
can be written as:
i = b;
Let us see an example:


a = 5*4

print( “5 times four is”, a, end=’\n’)

a =a+4

print (“Plus three is “,a)


print (“Divided by three is “,a)

In this example, “a” takes successively the values 20, 24 and 8.

This works for +=, -=, *=, /=, **= and %=.

    1. Strings

A string is a group of characters attached together, enclosed by quotation marks. For now, we will only consider double quotes.

Just like with numbers, many operations can be performed on strings: the most common ones are listed in the table below.

String operator



Concatenates strings a and b


Repeats string a i times


Returns a string containing all characters of a between position i and j, with step k; if k is negative, starts from the right


Returns a string that is the reverse of a


Split string a into a list, using sep to decide where to cut


Returns a string equal to a, but that has been stripped of any “white” characters at the beginning and end of a (space, tab, CR,…)


Returns a string equal to a, but with all letters uppercase


Returns a string equal to a, but with all letters lowercase


Returns a string equal to a, but with the first word capitalized


Counts the number of instances of the substring ‘sub’ in the string a


Returns a string equal to a, but with n instances of substring sub1 replaced with substring sub2; if n is not given, all instances are returned

Concatenating strings:
The + operator, when placed between two strings, creates a single string that concatenates the two original strings. In the following example:





The variable C contains the string “ATTGCGGCCT”. Note that the concatenation operator can be attached to an assignment:

Adds a “G” at the end of the string contained in C.
Repeating a string
The operator “*” repeats a string a given number of times:

>>> text=”No! “


>>> print (newtext)

No! No! No! No! No!

Indexing and slicing strings
Characters within a string can be accessed both front and backwards. Frontways, a string starts at position 0 and the character desired is found via an offset value:

Download 165.61 Kb.

Share with your friends:
  1   2   3

The database is protected by copyright © 2020
send message

    Main page