Introduction to the Python language

The lectures (more or less) follow the official Python 3.7 tutorial and the w3schools tutorial is also good.

  • 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 (see e.g. 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,
  • Extendable (e.g. with C, C++ code)
  • Great community, open source codebase
  • Leading programming languge in data science
  • Open source, free (as in free speach not as in free beer)

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 there.

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 program.

IDLE (Interactive Development & Learning Environment)

IDLE is part of the Python distribution. It has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. Run it by $ idle idle

Jupyter notebook

Jupyter is a browser based interface for python (and other languages as well). You can run jupyter from your own computer (if it is installed), but for the labs we will use jupyter.math.bme.hu. This is the same interface as you would start jupyter notebook from your own machine.

Jupyter itself is a browser-based interface, it runs a Python (or Sage, R or other) interpreter in the background (so called kernel ).

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 3.7
  • 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 elements 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", "öt hűtőházból kértünk színhúst", "ハンガリーからのご挨拶", "هنغاريا", "Венгрия", "헝가리", "הונגריה", "匈牙利", "ฮังการี",...

The type can be acquired with the type command.

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

Operations, expressions

Operations operate on objects, 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 result bool

Boolean operations on boolean objects:

  • a and b
  • a or b
  • not a
  • a != b (exclusive or, xor)

String operations:

  • a + b, concatenation
  • a in b, inclusion (results bool)
In [2]:
5 / 11
Out[2]:
0.45454545454545453
In [3]:
2 ** 251
Out[3]:
3618502788666131106986593281521497120414687020801267626233049500247285301248
In [4]:
12 ^ 7 # bitwise exclusive or: 1100 ^ 0111 = 1011
Out[4]:
11
In [5]:
a = 54
b = a - 50
a * b
Out[5]:
216
In [6]:
54 > 12
Out[6]:
True
In [7]:
b <= 0
Out[7]:
False
In [8]:
54 > 12 or b <= 0
Out[8]:
True
In [9]:
s = "puppy"
"up" in s
Out[9]:
True
In [10]:
s = "little " + s
s
Out[10]:
'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 are different names

Strings

There are tree ways of constructing a string literal.

In [ ]:
s = "puppy"
type(s)
In [ ]:
s = 'puppy'
type(s)
In [ ]:
s = """사랑 means
love
"""
type(s)
In [ ]:
s

You can see the "new line" control character denoted by an escape sequence \n. The print command prints it in a readable format.

In [ ]:
print(s)

The first two quotion types 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 [ ]:
print("A 'quotion' mark, " + 'and an other "quotion" mark.')

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

In [1]:
'there is this: \' and this: "'
Out[1]:
'there is this: \' and this: "'
In [2]:
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 the \n escape sequence.

Some other escape sequences: \\\\, \\', \\", \n (new line), \t (tab)

In [3]:
print("\home\name")
\home
ame
In [4]:
print(r"\home\name")    # raw text, no escape sequences
\home\name

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() function. If you want to see more values in one cell, you have to use print().

In [5]:
5 + 8
5 + 7
Out[5]:
12
In [6]:
a = 5
print(a)
a = 15
print(a * 2)
a
5
30
Out[6]:
15
In [11]:
string = "hon"
"Pyt" + string
Out[11]:
'Python'
In [12]:
print("Once upon a time there was a %s who liked to bark." % "puppy")
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 [13]:
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 [14]:
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"

With the option end= you can determin how to close the string. The default end is \n. If you want to continue a line, use end=' ' or end=''. Empty print() begins a new line.

In [15]:
print(1, 3.14, "cat", end=' ')  # a space
print("some", end='')           # an empty character
print("thing", end=' ')         # a space
print()                         # a new line (if there is no end='...' argument)
print("EOT")
1 3.14 cat something 
EOT

Input

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

In [7]:
input()
12
Out[7]:
'12'

This is an annoyingly polite piece of code:

In [16]:
name = input("Your name, please! ")
print("Hi %s,\nnice to meet you!" % name)
Your name, please! Joel
Hi Joel,
nice to meet you!
In [17]:
input() > 10
12
-------------------------------------------------------------------------
TypeError                               Traceback (most recent call last)
<ipython-input-17-90907fbeb455> in <module>
----> 1 input() > 10

TypeError: '>' not supported between instances of 'str' and 'int'
In [18]:
int(input()) > 10    # converts the input strint to integer
12
Out[18]:
True
In [8]:
type(input())
12
Out[8]:
str

Control flows

Conditional

In [19]:
x = float(input())
if x < 0:
    print("negative")
elif x == 0:
    print("zero")
elif x == 1:
    print("one")
else:
    print("too many")
0.5
too 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 indentation) is executed. If the first condition is not satisfied, then the first elif which evaluates to True is executed. If neither of those is True, then the else branch is considered (if there is such a branch).

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

While loop

In [20]:
n = 1000
a = 1
while a ** 3 <= n:
    print(a ** 3, end=' ')  # results separated by spaces
    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. One can embed control flows into each other.

Here is a code for the famous Collatz or $3x+1$-conjecture:

In [22]:
a = int(input())
while a != 1:
    print(a, end=' ')  # write the numbers in the same line
    if a % 2 == 0:
        a = a // 2
    else:
        a = a * 3 + 1
print(a)
71
71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1

We need to go deeper!

In [9]:
a = int(input())
if a > 0:
    while a != 1:
        print(a, end=' ')
        if a % 2 == 0:
            a = a // 2
        else:
            a = a * 3 + 1
    print(a)
else:
    print("Give a positive integer, please!")
-2
Give a positive integer, please!

The above code checks for positive integer input. Change the code with repeatedly reading the numbers, and stop running if the input is zero. You can use the break command within loops, which unconditionally and immediately escapes the given block and continues as if the loop would have ended.

In [10]:
while True:
    a = int(input())
    if a > 0:
        while a != 1:
            print(a, end=' ')
            if a % 2 == 0:
                a = a // 2
            else:
                a = a * 3 + 1
        print(a)
    elif a == 0:
        break
    else:
        print("Please, enter a nonnegative integer! 0 stops running.")
13
13 40 20 10 5 16 8 4 2 1
17
17 52 26 13 40 20 10 5 16 8 4 2 1
0

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