Python: Basics

I will be teaching the Python language, version 2.7 (more on that later).

The biggest take-away message from this lecture is:

Danger

In order to learn Python, you have to write Python code.

The converse is also true, so:

Danger

If you do not write Python code, you will not learn Python.

Please keep this in mind.


The Interpreter

The term Python refers to the Python language, while python refers to the Python interpreter.

In order to access the interpreter, type:

python

in a terminal window. You will get a prompt that looks like this:

Python 2.7.12+ (default, Sep  1 2016, 20:27:38)
[GCC 6.2.0 20160822] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Now you are free to type your Python code into the interpreter, and it will be executed immediately. Try it out with:

print "hello, world!"

To quit the interpreter, either type:

quit()

or press Control-d on a blank line.

Warning

There are two versions of the Python language out there:

  1. Python 2: this is the version we will be using. The current version of the Python 2 interpreter is 2.7.12.

    When we talk about Python, we refer to Python 2.

  2. Python 3: this is a new and improved version of the language.

    It is mostly compatible with Python 2: a lot of valid Python 2 code is also valid Python 3 code. Alas, there are also slight differences. I will not explain what these are.

    The current version of the Python 3 interpreter is 3.5.2.

We will stick to Python 2 in this course.

Warning

There are some minor differences between the languages allowed by the different versions of the Python interpreter.

For instance, list comprehensions have been available since Python 2, interpreter version 2.0, but generators (which work similarly) have only been introduced in version 2.4.


Modules

A module is a text file hosting a bunch of Python code.

If you want to execute Python code written in a text file, you have to:

  1. Make sure that the file has a .py extension, for instance example.py.

  2. Type:

    python example.py
    

Warning

The .py extension is mandatory! If you use any other extension, the interpreter will not recognize your text file as containing valid Python code.

Let’s say that you wrote a module util.py, which includes a function do_stuff(). In order to use that function from a different module, you have to import the module, as follows:

import util

util.do_stuff()

The do_stuff() function is prefixed with the name of the module. This way there is no name clash between functions (or other symbols) in different modules.

Note

The name of the module (as seen from inside Python) is util, not util.py!


Objects

An object represents a datum (for instance, a number, some text, a collection of things, etc.) as well as functions for operating on that datum.

Every object has:

  • a type, which specifies what the kind of data represented by the object.
  • a value, that is, the data itself.

In a way, the type is a form of meta-data (information about the data).

Python provides some elementary types:

Type Meaning Domain Mutable?
bool Condition True, False No
int Integer \(\{-2^{-63},\ldots,2^{63}-1\}\) No
long Integer \(\mathbb{N}\) No
float Rational \(\mathbb{Q}\) (more or less) No
str Text Text No
list Sequence Collections of things Yes
tuple Sequence Collections of things No
dict Map Maps between things Yes

Most of these should be pretty obvious. Later on, we will see how the more complex ones (list, tuple and dict) mean.


Variables

Variables are references to objects. You can view them as names for the objects that they refer to.

An object is assigned to a variable with the assignment operator =:

pi = 3.1415926536

Here the variable pi refers to the object 3.1415926536. Informally, we just decided to use the name pi to refer to the object 3.1415926536.

Warning

The name of the variable is arbitrary!

You can pick any name you like, as long as you follow some simple rules:

  • the only allowed characters are upper-case digits (A-Z), lower-case digits (a-z), numerical digits (0-9), and the underscore _.
  • the name can not begin with a number.

The type of a variable is given by the type of the object it refers to. In the previous example, the type of 3.1415926536 is float; as a consequence, the type of pi is also float.

Warning

The variable does not contain the object; it merely contains a reference to the object.

To print the value of a variable (or rather, of its associated object), use the print function:

var = "I am an example"
print var

To print the type of a variable (object), use the type function:

var = "I am an example"
print type(var)

Example. Just to wrap up, let’s create a new variable var:

var = 123

The name of var is var, its value is 123, and its type is int:

print var       # 123
print type(var) # int

Example. A variable can be assigned multiple times:

var = 1
print var       # 1
print type(var) # int

var = "MANLFKLGAENIFLGRKAATKEEAIRF"
print var       # "MANLFKLGAENIFLGRKAATKEEAIRF"
print type(var) # str

var = 3.1415926536
print var       # 3.1415926536
print type(var) # float

Note how the value and type of var changes after each assignment!

Example. Assignment also works between variables:

a = "I am an example"
print a

b = a
print b

Here the variable b is assigned the same object that is referenced by a, that is, "I am an example".


Functions and Methods

Python provides a variety of functions and methods, for instance print() (to print the value of an expression) and help() (to show the manual of a given type, function, method, class, or module).

  • A function takes zero or more objects as inputs (its arguments), performs some operation on them, and returns an object (its result).

    To invoke a function f(), write:

    result = f(arg1, .., argN)
    

    Here the variable result is assigned to the result of the function.

  • A method is exactly like a function, except that it is provided by a given type. For instance, strings provide a split() method, which can only be used in conjunction with strings; lists provide a join() method, which only works with lists. The other basic types (except for numbers) also provide their own methods.

    To invoke a method t.m(), write:

    result = obj_or_var_for_type_t.m(arg1, ..., argN)
    

Warning

Python functions and mathematical functions share some similarities: informally, both evaluate their arguments (inputs) to produce a result (output).

There are some important differences though:

  • Not all Python arguments require arguments. They may take none at all.
  • Python functions may not return any result. (In which case they always evaluate to None).
  • Mathematical functions can only operate on their arguments, while Python functions can access additional resources.
  • Mathematical functions can only modify the “external environment” through their result. Python functions can have side-effects.

For now, you can just use functions and methods already provided by Python; later on in the course we will write our own functions!


Documentation

In order to open the interactive manual of a type/object/variable, you can use the help() function. For instance:

help(1)

shows the manual of the int type; you can achieve the same result with:

help(int)

and:

x = 1
help(x)

To open the manual of a given function or method, you can use the same procedure, for instance:

# Opens the manual of the len() function
help(len)

# Opens the manual of the split() method of the str type
help(str.split)
# help("some text".split)

To quit the manual, press q.