Python is a widely used programming language (source code is now available under the GNU General Public License – GPL) started by Guido van Rossum that supports multiple programming paradigms.

With a gentle learning curve, Python is readable, writeable, and endlessly powerful. Its simplicity lets you become productive quickly. This hand-on will show some basic characteristics of Python to help to enter yourself in this great language. At the end of the page you will find very useful links to advance on your own and some tips that could help you.  Good luck!

Installing Python

Before you start, you will need Python on your computer, but you may not need to download it. Nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers now come with Python already installed. First of all check that you don’t already have Python installed by entering python in a command line. If you see a response from a Python interpreter it will include a version number in its initial display. If you use the environment proposed in the previous hands-on you will see:

torres@vm:~$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.

If you need to install Python , you may as well download the most recent stable version of Python 2 or Python 3 from general download page. For advice on choosing between Python 2 and Python 3 see Python 2 or 3.


Line indentation

Python has no mandatory statement termination characters and blocks are specified by indentation (there are no braces to indicate blocks of code for class and function definitions or flow control). Statements that expect an indentation level end in a colon (:). The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Python will advise you if there is a unclear line indentation with the following warning:

IndentationError: unexpected indent

Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments.

Variables, operators and data types

Python is implicitly typed language (i.e. you don’t have to declare variables), case sensitive (i.e. Barcelona and BARCELONA are two different variables) and object-oriented (i.e. everything is an object). Help in Python is always available right in the interpreter. Type help() for interactive help, or help(object) for help about object. If you want to know how an object works, all you have to do is call help(<object>) Also useful are dir(), which shows you all the object’s methods:

>>> help (int)

Help on int object:
class int(object)

| int(x=0) -> int or long
| int(x, base=10) -> int or long

| Methods defined here:
| __abs__(…)
| x.__abs__() <==> abs(x)

(type q to exit)


The addition, subtraction, multiplication, and division operations work just like expected. In addition we can use the modulus operator (%). All the modulus operator does is to divide the left side by the right side and get the remainder. The floor division operator (//) just divides the number and rounds down. The double * is just an easy way to provide exponents to Python.

Values are assigned with the sign “=”, in fact, objects are bound to names (the equality testing is done using two equal signs “==”). It is possible use the += and -= operators on many datatypes, strings included. You can also use multiple variables and swaps variables in one line. It doesn’t violate variable typing because values aren’t actually being assigned, but new objects are bound to the old names.

>>> IntegerVar = 10
>>> IntegerVar += 10
>>> print IntegerVar
>>> StringVar = “Welcome”
>>> StringVar += ” to Barcelona”
>>> print StringVar
Welcome to Barcelona
>>> IntegerVar, StringVar = StringVar, IntegerVar
>>> print IntegerVar
Welcome to Barcelona
>>> print StringVar
>>> help (StringVar)
Help on int object:

class int(object)
| int(x=0) -> int or long
| int(x, base=10) -> int or long

The data structures available in Python are lists, tuples and dictionaries. Lists are like one-dimensional arrays and we can also have lists of other lists or tuples. There are number of methods for lists (methods follow the list name). Tuples are immutable one-dimensional array.

>>> sampleList = [1,2,3,4,5,6,7,8]
>>> print (sampleList[1])
>>> sampleTuple = (1,2,3,4,5,6,7,8)
>>> print (sampleTuple)
(1, 2, 3, 4, 5, 6, 7, 8)
>>> print sampleList
[1, 2, 3, 4, 5, 6, 7, 8]
>>> sampleList.append(9)
>>> print sampleList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sampleTuple.append(9)
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
AttributeError: ‘tuple’ object has no attribute ‘append’

Python dictionaries are associative arrays that has keys to obtain the elements of the dictionary. Dictionaries aren’t exactly based on an index, there is no particular order in dictionaries (we could add a key: value and, it will appear in random places). A big caution here is that you cannot create different values with the same key (Python will just overwrite the value of the duplicate keys).

>>> myDicc = {‘someItem’: 2, ‘otherItem’: 20}
>>> print(myDicc[‘otherItem’])

Python lists/dictionaries/tuples can be of any type, so you can mix them in. Variables can point to functions. The index of the first element is 0 and negative numbers count from the end towards the beginning ( -1 is the last element).

>> Example = [1, “BCN”, [“another”, “list”], {“and”,”a”,”tuple”}]
>>> print Example
[1, ‘BCN’, [‘another’, ‘list’], set([‘a’, ‘and’, ‘tuple’])]
>>> myfunction = len
>>> print myfunction (Example)
>>> print Example[-1]
set([‘a’, ‘and’, ‘tuple’])
>>> print Example[3]
set([‘a’, ‘and’, ‘tuple’])

IMPORTANT: If you paste this code directly into the python console it displays the error message “Syntax error: Invalid syntax”. This is due to the quotation mark, because word transforms the quotation mark “ (0x22 HEX Unicode) into a left double quotation mark “ (0x201C HEX Unicode), probably to make the text more beautiful. It’s not a big deal, but must be taken into account, as students cannot copy/paste the code directly.

Finally, Python strings can use either single or double quotation marks, and we can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ‘I enjoy Barcelona’.” ). Multiline strings are enclosed in triple double (or single) quotes  (“””). Another interesting feature is that Python supports Unicode out of the box, using the syntax u”This is a unicode string example”. To fill a string with values, we use the % operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and we can also use dictionary substitutions as we show in the following example:

>>> MultiString = “”” Example of
… a multiline
… string”””
>>> print MultiString
 Example of
a multiline
>>> print “Arrival: %s from %s” % ( “BA230”, “Barcelona”)
Arrival: BA230 from Barcelona
>>> print “Arrival: %(fly)s from %(city)s” % {“fly”:”BA230″, “city”:”Barcelona”}
Arrival: BA230 from Barcelona

Flow control statements

Flow control statements are if, for, and while Often partnered with the if statement are else if and else. However, Python's else if is shortened into elif. After every conditional we have a colon. Next, we could proceed to a new line with number of spaces to tell Python we only want this code to be run when the previous conditional is satisfied. 

>>> a = 20
>>> if a >= 22:
…     print(“Paris”)
… elif a >= 21:
…     print(“Londres”)
… else:
…     print(“Barcelona”)


Loops in Python are very versatile and simple.

>>> for a in range(1,4):
…        print (a)


>>> a = 1
>>> while a < 4:
…        print (a)
…        a+=1


You can stop the loop using the “break” statement.

In this example we use the range keyword (used to enumerate through members of a list and to obtain a list of numbers) to set the starting point and the point right after we would finish (this is precisely why the number 4 didn’t print). Python is quite fond of this idea of all the way up to a number, but not including it.



We can define a function by using the keyword def before your function name. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values).

>>> def someFunction():
…        print(“Barcelona”)

>>> someFunction()

>>> def fib(n):    # write Fibonacci series up to n
…         a, b = 0, 1
…         while b < n:
…             print b,
…             a, b = b, a+b

>>> fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Lambda Functions

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called “lambda”. This is not exactly the same as lambda in functional programming languages:
>>> fibonacci = (lambda x: 1 if x <= 2 else fibonacci(x-1) +  fibonacci(x-2)) >>> fibonacci(10)
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> for i in filter(lambda x: x % 3 == 0, foo):
print (i)



Python supports a limited form of multiple inheritance in classes.

>>> class Calculator(object):
…     #define class to simulate a calculator
…     def __init__ (self):
…         #start with zero
…         self.current = 0
…     def add(self, amount):
…         #add number to current
…         self.current += amount
…     def getCurrent(self):
…         return self.current

>>> myCalc = Calculator() # make myCalc into a Calculator object
>>> myCalc.add(2) #use myCalc’s new add method derived from the Calculator class
>>> print(myCalc.getCurrent()) 
>>> myCalc.add(2)
>>> print(myCalc.getCurrent())


In the previous example the first part defines a Class. def __init__ is the constructor function, the function that is called when a new instance of the class is created. The actual new instance is created in the line myCalc = Calculator(). The second part shows how to use this class in Python.



Python define a object type for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration

An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero.

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

>>> vec = [1, 2, 3]
>>> it = iter (vec)
>>> next (it)
>>> next (it)
>>> next (it)
>>> type (vec)

<class ‘list’>
>>> type (it)
<class ‘list_iterator’>


Exceptions in Python are handled with try-except blocks. See the following code for one example:

>>> def function():
…     try:
…         # Division by zero raises an exception
…         10 / 0
…     except ZeroDivisionError:
…         print “Invalid operation.”

>>> function()
Invalid operation.


External libraries are used with the import [libname] keyword. We can also use from [libname] import [funcname] for individual functions.

>>> from random import randint
>>> randomint = random.randint(1, 100)
>>> print randomint
>>> randomint = random.randint(1, 100)
>>> print randomint

In this example we are showing how first we are importing the whole library and then accessing and individual function of that library, and then how we can import just the individual function and use it directly without needing to write the library.

Read/Write files

Python uses the following sintax for read/write files:

>>> f = open(“test.txt”,”w”) #opens file with name of “test.txt”
>>> f.write(“Barcelona, “)
>>> f.write(“is the best city of the world.”)
>>> f.write(“With an excellent weather.”)
>>> f.close()
>>> f = open(“test.txt”,”r”) #opens file with name of “test.txt”
>>> print(
Barcelona, is the best city of the world.With an excellent weather.
>>> f.close


Exercice: Guess the number

To sum up, let’s create a little game using Python concepts learnt before.

Using the “random” library, generate a random number between 1 and 20, then ley the player guess the number introduced, displaying “Your guess is to low/high” if they fail. The game ends either when the number is guesses correctly, or after 5 attempts.

To read from the terminal, use the function raw_input as showed here:

# Name variable contains the input from terminal
name = raw_input(‘Hello! What is your name?\n’)

To run a python script, simply use the following terminal command, where <file path> is the path to the file containing your script (python scripts must have the .py extension):
$ python file_path ;

Useful references

Barcelona, 30/11/2013

Links  updated: 5/02/2014


2017-08-09T12:39:30+00:00 November 30th, 2013|