Introduction to the Python language

The lectures (more or less) follow the official Python 3.7 or 3.8 tutorial and the w3schools tutorial is also good (you may try several examples, and may check your knowledge with online tests).

  • Python is a general purpose, high level programming 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
  • Good math projects (sage)
  • 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

In Linux: $ python3 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): $ python3 hello.py This runs all the commands in the .py file, the output (if any) is printed on the console.

In Windows: C:\Users\YourName> py or maybe instead of py you may write python(.exe). C:\Users\YourName> py Desktop\hello.py

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

In Windows you may right click on a .py file, or search IDLE from start menu.

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 ). It saves the files with .ipynb ending (interactive python notebook). Never send your homework in this format!

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.8
  • 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, 2.3e4
  • bool (boolean): True, False
  • str (string): "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 function.

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
  • 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 = 14
b = a - 10
a * b
Out[5]:
56
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]:
54 > 12 and b <= 0
Out[9]:
False
In [10]:
s = "puppy"
"up" in s
Out[10]:
True
In [11]:
s = "little " + s
s
Out[11]:
'little puppy'

Variables

  • A name (of an object) 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, Val1 and VAL1 are different names
  • convention: a variable name has no capital letters, and multiword names use underscore: time, number_of_participants. Use explanatory names!

Strings

There are tree ways of constructing a string literal.

In [12]:
s = "puppy"
type(s)
Out[12]:
str
In [13]:
s = 'puppy'
type(s)
Out[13]:
str
In [14]:
s = """사랑 means
love
"""
type(s)
Out[14]:
str
In [15]:
s
Out[15]:
'사랑 means\nlove\n'

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

In [16]:
print(s)
사랑 means
love

The first two quotion types are equivalent and 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 [17]:
print("A 'quotion' mark, " + 'and an other "quotion" mark.')
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 [18]:
'quotation marks are \' and "'
Out[18]:
'quotation marks are \' and "'
In [19]:
print('quotation marks are \' and "')
quotation marks are ' and "

In the third type you can use line breaks, in the others you have to use the \n escape sequence. In Python we use \ for escape sequences: \\\\, \\', \\", \n (new line), \t (tab)

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

Comments

Inline comments with #, multiline comments with the """-strings. Any string which is not assigned to a variable is a comment!

In [22]:
1 + 1  # my first Python command
Out[22]:
2
In [23]:
"""The next code 
is really
very simple:"""
1 + 2
Out[23]:
3

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 [24]:
5 + 8
5 + 7
Out[24]:
12
In [25]:
a = 5
print(a)
a = 15
print(a * 2)
a
5
30
Out[25]:
15
In [26]:
string = "hon"
"Pyt" + string
Out[26]:
'Python'
In [27]:
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 [28]:
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 [29]:
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.
In [30]:
"Hi %s! You have %d points." % ("Tom", 100)
Out[30]:
'Hi Tom! You have 100 points.'

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 [31]:
print(1, 3.14, "cat", end=' ') # a space
print("some", end='')          # an empty character
print("thing", end=' ')        # a space
print()                        # new line (if there's 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 [32]:
input()
asdfélkjrt 3456
Out[32]:
'asdfélkjrt 3456'

This is an annoyingly polite piece of code:

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

TypeError: '>' not supported between instances of 'str' and 'int'
In [35]:
int(input()) > 10    # converts the input strint to integer
12
Out[35]:
True
In [36]:
type(input())        # the input gets always a string
12
Out[36]:
str

Control flows

Indentation

Python uses indentation (a few spaces at the beginning of a line) to indicate a block of code. In a block every indentation have to have the same nuber of spaces. General convention: indent with 4 spaces. Editors do it automaticaly.

Conditional

In [37]:
x = float(input())
if x < 0:
    print("negative")
elif x == 0:
    print("zero")
elif x == 1:
    print("one")
else:
    print("positive, but not one")
    
if x >= 10:
    print("it has at least two digits")
123
positive, but not one
it has at least two digits

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 [38]:
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 $3n+1$-conjecture:

In [41]:
n = int(input())
while n != 1:
    print(n, end=' ')  # write the numbers in the same line
    if n % 2 == 0:
        n = n // 2
    else:
        n = n * 3 + 1
print(n)
17
17 52 26 13 40 20 10 5 16 8 4 2 1

We need to go deeper!

In [ ]:
n = int(input())
if n > 0:
    while n != 1:
        print(n, end=' ')
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    print(n)
else:
    print("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 [ ]:
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.")

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