Introduction to the Python language

The lectures (more or less) the official Python tutorials.

  • Python is a general purpose, high level programmng languge.
  • One of its principles is readability through a very clean syntax.
  • It was created in 1991 by Guido Van Rossum.
  • Its name was inspired by Monthy Python, not the reptile.

Why Python?

Popularity

Pros

  • Easy-to-learn, steep learning curve, interactive, good for beginners (Raspberry Pi)
  • Well readable code, simple commands for high level functionality
  • Runs on almost every platforms, portable code
  • Object Oriented (OOP)
  • Good for web applications (Google, Yahoo, IBM, NASA, Disney, Dropbox, ...)
  • Quick to write, concise code, suitable for great projects, too
  • Great community, open source codebase
  • Leading programming languge in data science
  • Open source, free (as in free beer and free speech

Cons

  • Slow
  • Not ideal for mobile apps
  • Not suitable for graphical (3D) computing

Run

  • python is a so called interpreted language
  • The code cannot run on its own, you need an other program to interpret it: an interpreter
  • The interpreter is a binary executable (it was not written in binary code, rather it was compiled to a binary code)
  • The python code is (more or less) OS independent, but the interpreter is not.

There are several ways to run a python code.

Command line

For example, interactively:
$ python
This opens a prompt, you can type commands here.

One can run a given set of python commands from a file (a python script, .py extension): $ python hello.py This runs all the commands in the .py file, the output (if any) is printed on the console.

The interpreter is the python(.exe) executable here.

Jupyter (IPython) notebook

Jupyter is a browser based interface, which is in close resemblance to the Sage notebooks from last semester.

You can start your own web server, on leibniz: $ ipython notebook --port=##### --no-browser --ip=127.0.0.1 Where ##### is a port number ranging from 9000 to 20000. Then you can look your notebooks on the address localhost:##### in your web-browser.

This starts a program which handles the interface in yout browser and this program starts other interpreters (kernels), depending on your usage. But ipython is an interpreter itself.

In newer versions ipython notebook is replaces with jupyter notebook (it's easier from your own computer). Jupyter can run multiple kernels, not even with the same programming language, for example Python, Sage and there are several others.

Spyder

Spyder is a graphical development environment for python, it is installed on leibniz, but you can install it on your own machine, for any operating system.

This is not an interpreter, rather a graphical insterface to comfortably write and run your code, it has to use and interpreter though.

At home

I advise to use Anaconda. It is available on all of the major desktop OSs (Linux, Mac, Windows)

  • choose your OS
  • choose version 2.7 (we use this because this is installed on leibniz, but there are newer versions)
  • Mind the 32/64 bits

Anaconda contains command line (python, ipython), notebook (jupyter) and graphical (Spyder) environments, not to mention a lots of useful libraries, tools and packages.

Basic objects

The objects are the building blocks of the language. Every object has a type. Let's start with the following types:

  • int (integer): 2354, -12
  • float (floating point): 1.0, -23.567, 2.3E4
  • bool (boolean): True, False
  • str (string): "puppy", "once upon a time there was a puppy"

The type can be acquired with the type command.

In [12]:
type(5.0)
Out[12]:
float

Operations, expressions

Operations operate on object, resulting an expression, the result can have a different (but well specified) type.

Integer and float operations:

  • a + b addition
  • a - b subtraction
  • a * b multiplication
  • a / b division (in Python2.7 int/int = int, but from Python3 int/int = float)
  • a // b integer division
  • a % b remainder, modulo
  • a ** b power (unlike Sage a ^ b !)
  • a == b, a < b, a > b, a <= b, a >= b, a != b, a <> b result bool

Boolean operations on boolean objects:

  • a and b
  • a or b
  • not a

String operations:

  • a + b, concatenation
  • a in b, inclusion (results bool)

Example

In [13]:
5 + 11
Out[13]:
16
In [14]:
2 ** 251
Out[14]:
3618502788666131106986593281521497120414687020801267626233049500247285301248L
In [15]:
a = 54
b = a - 50
a * b
Out[15]:
216
In [16]:
54 > 12
Out[16]:
True
In [17]:
b < 0
Out[17]:
False
In [18]:
54 > 12 or b < 0
Out[18]:
True
In [19]:
s = "puppy"
"x" in s
Out[19]:
False
In [20]:
s = "little " + s
s
Out[20]:
'little puppy'

Variables

  • A variable name can start either with underscore or letter: [_a-zA-Z]
  • it can be folowed by any number of letters, or numbers, or underscores: [_a-zA-Z0-9]
  • in theory, a name can be arbitrarily long
  • name cannot be reserver word (later)
  • Case sensitive: val1 and Val1 differ

Strings

There are tree ways of constructing a string literal.

In [21]:
s = "puppy"
type(s)
Out[21]:
str
In [22]:
s = 'puppy'
type(s)
Out[22]:
str
In [23]:
s = """Once upon a time
there was a puppy.
Elment a vásárba fél pénzzel!
"""
type(s)
Out[23]:
str
In [24]:
s
Out[24]:
'Once upon a time\nthere was a puppy.\nElment a v\xc3\xa1s\xc3\xa1rba f\xc3\xa9l p\xc3\xa9nzzel!\n'

You can see the control characters (\n is new line) and UTF-8 byte codes (á=c3a1, \x is followed by a hexa code). The print command prints it in a readable format.

In [25]:
print s
Once upon a time
there was a puppy.
Elment a vásárba fél pénzzel!

The first two quotions are for using quotion marks in a string. You can use a quotion mark if it is not the one used to mark string literal. Example:

In [26]:
print "One 'quotion' mark, " + 'two "quotion" marks'
One 'quotion' mark, two "quotion" marks

If you want to use the same quotion mark as the string mark, then use escape characters:

In [27]:
'there is this: \' and this: "'
Out[27]:
'there is this: \' and this: "'
In [28]:
print 'there is this: \' and this: "'
there is this: ' and this: "

In the third type you can use line breaks, in the others you have to use escape character for newlines (\n).

Other special (escape) characters: \\\\, \\', \\", \n (new line), \t (tab)

Printing

In Jupyter notebooks, the last result is printed after every cell, but if you run a python program you have to use the print command. If you want to see more values in one cell, you have to use print, too.

In [29]:
5 + 8
5 + 7
Out[29]:
12
In [30]:
a = 5
print a
a = 15
print a * 2
a
5
30
Out[30]:
15
In [31]:
string = "puppy"
"I had a " + string
Out[31]:
'I had a puppy'
In [32]:
print "Once upon a time there was a %s who liked to bark." % string
Once upon a time there was a puppy who liked to bark.

If a string contains %s and % after it, then the latter is substitued in the place of %s. You can do more substitutions:

In [33]:
print "%s upon a time there was a %s who liked to %s." % ("Once", "puppy", "bark")
Once upon a time there was a puppy who liked to bark.

You can substitute other types not just strings:

In [34]:
print """The %d is a decimal integer, 
the %f is a float number.""" % (23, 1.0/3)
The 23 is a decimal integer, 
the 0.333333 is a float number.
% type example result
%s string "Once upon a time there was a %s" % "puppy" "Once upon a time there was a puppy"
%d integer "%d upon a time there was a puppy" % 1 "1 upon a time there was a puppy"
%f float "Once upon a time there were %f puppies" % math.pi "Once upon a time there were 3.141593 puppies"
mixed "There were %d %s and they had to share %f fl.oz. milk" % (3, 'puppies', math.pi) "There were 3 puppies and they had to share 3.141593 fl.oz. milk"

You can print more thing in one line, just use a comma separated list, print will use a space separator.

If you want to continue a line, end the print command with a comma.

Empty print begins a new line.

In [35]:
print 1, 3.14, "puppy"
print "cat",
print "camel",
print
print "EOT"
1 3.14 puppy
cat camel
EOT

Input

Since we know how to output things, we learn how to read input.

In [36]:
raw_input()
five
Out[36]:
'five'

This is an annoyingly polite piece of code:

In [37]:
a = 5
name = raw_input("Your name, please! ")
print "Hi %s\nnice to meet you!" % name
Your name, please! Gabor
Hi Gabor
nice to meet you!
In [38]:
input() > 10
8
Out[38]:
False
In [39]:
input() ** 10
2
Out[39]:
1024

The difference between raw_input and input:

In [40]:
a = raw_input()
a + " cats"
5
Out[40]:
'5 cats'
In [41]:
b = input()
b + " cats"
5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-d2ed710d9bb4> in <module>()
      1 b = input()
----> 2 b + " cats"

TypeError: unsupported operand type(s) for +: 'int' and 'str'

raw_input always returns a string, input interprets the input:

In [42]:
type(input())
3.14
Out[42]:
float

It is worth mentioning that input itself is a security risk:

python
>>> intput()
exit()

Control flows

Conditional

In [43]:
x = input()
if x < 0:
    print "this is negative"
    print 5
elif x == 0:
    print "this is zero"
elif x == 1:
    print "this is one"
else:
    print "this is many"
5
this is many

You can have more than one elif branches but neither elif nor else is mandatory.

If the first condition is met (expression evaluates to True) then the first block (marked with an ident) is executed. If not then the first elif which evaluates to True. If neither of those, then the else branch (if there is such a branch).

The ident is mandatory, that marks the block, one ident is usually 4 spaces deep.

While loop

In [44]:
n = 1000
a = 1
while a ** 3 <= n:
    print a ** 3,  # comma continues the line
    a = a + 1
print "end"
1 8 27 64 125 216 343 512 729 1000 end

The while block is executed as while as the condition is evaluated to True.

The former example increases the variable a as long as its cube is not greater than 1000.

One can embed control flows into each other.

The famous Collatz or $3x+1$-conjecture:

In [45]:
a = input()
while a != 1:
    print a,  # comma continues the line
    if a % 2 == 0:
        a = a / 2
    else:
        a = a * 3 + 1
20
20 10 5 16 8 4 2

We need to go deeper!

In [46]:
a = input()
if type(a) == int:
    while a != 1:
        print a,  # comma continues the line
        if a % 2 == 0:
            a = a / 2
        else:
            a = a * 3 + 1
else:
    print "Integer, please"
3.14
Integer, please

The above code checks for integer input. Better to prepare for the worst. What if somebody gives a negative input?

In [49]:
a = input()
if type(a) == int:
    if a < 0:
        a = -1 * a
    while a != 1:
        print a,  # comma continues the line
        if a % 2 == 0:
            a = a / 2
        else:
            a = a * 3 + 1
else:
    print "Integer, please"
-20
20 10 5 16 8 4 2

Finaly, we have to exclude 0, because the conjecture doesn't work for that:

In [50]:
a = input()
if type(a) == int and a != 0:
    if a < 0:
        a = -1 * a
    while a != 1:
        print a,  # comma continues the line
        if a % 2 == 0:
            a = a / 2
        else:
            a = a * 3 + 1
else:
    print "Non zero integer, please"
0
Non zero integer, please

Break

You can use break within loops, this command unconditionally and immediately escapes the given block and continues as if the loop would have ended.

In [51]:
n = input("Give a whole square under 10000! ")
a = 0
while a ** 2 < 10000:
    if a ** 2 == n:
        break
    a = a + 1
if a ** 2 < 10000:
    print "its square root is %d" % a
else:
    print "You lied! :("
Give a whole square under 10000! 100
its square root is 10

In case of nested loops, break escapes the innermost loop.