Session 2 Introduction to Python programming¶

Outline¶

  1. About Python
  2. How to install Python and Editors
  3. Python basics
  4. Classes
  5. Packages

About Python¶

Python is a high-level and interpreted programming language with a focus on readability. Python was released in 1991 by Guido van Rossum.

Python is used for¶

  • System scripting - repeating tasks or automate tasks
  • Mathematics and Simulations
  • Web development - Implementation of the server side
  • Data visualization

Why Python¶

  • Python runs on most operating system, like Windows, Mac, and Linux) - Sharing of code
  • Python has simple syntax based on mathematics and English language
  • Python program can be shorter, since fewer lines of code are needed

What is different¶

  • Python uses indentation, using white space, to define scope; such as the scope of loops, functions and classes.
  • Python has a really nice package manager and it is easy to install libraries

How to install Python and Editors¶

Python¶

  • Linux: sudo dnf install python3 or sudo apt-get install python3
  • MacOS: Install Python via HomeBrew
  • Windows: Install the executable from Python.org
  • Docker: Using the official Python Docker image

Package manager¶

  • pip - pip3 install numpy
  • anaconda - conda install -c anaconda numpy

Editor¶

  • Visual Studio Code -- Allows C++ and Python programming in the same editor
  • Jupyter -- Runs in the browser and code can be run step by step and images are shown on the fly.
  • and many more editors are available.

Basics¶

The first example for all programming languages, is the so-called "Hello world!" program. In that case the string "Hello world!" is printed. Let us have a look into the Python code:

In [1]:
 print("Hello, World!") 
Hello, World!

Here, we executed the hello world code using Jupyter notebooks. Another option is to run a file with the code

In [2]:
%%writefile helloworld.py
print("Hello, World!") 
Overwriting helloworld.py
In [3]:
%%bash
python3 helloworld.py
Hello, World!

Indentation¶

Most programming languages use parentheses, like curly ${}$ ones, to specify the scope and indentation is used only for readability. In Python there are no parentheses and indentation is very important.

In [4]:
if 5 > 2:
    print("Five is greater than two!")
Five is greater than two!

Here, we use the if statement for conditional statements. Only if the condition 5 > 2 is evaluated as true all the indented code is executed.

Variables¶

In Python we do not have types, like int, double, or string as in other languages. An the type of the variable is determined by the assignment.

In [5]:
# Integer
x = 5
# Floating point value
y = 5.5
# String
name = "Medical physics"

For in-code documentation the hashtag # is used and this lien of code is not executed. Python also supports multi line comments

In [6]:
"""
"the meaning of life, 
the universe, and everything
"""
x=42

Casting¶

The programmer can specify the variable type, by casting the right-hand side to the desired type.

In [7]:
x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0 

Getting the type of a variable

In [8]:
print(type(x))
<class 'str'>
In [9]:
print(type(z))
<class 'float'>

Strings¶

We can define a string using 'hello' (single quotation) or "hello" (double quotation).

In [10]:
string = "Medical Physics"
print(string[0:7])
Medical
In [11]:
for s in string[8:len(string)]:
    print(s)
P
h
y
s
i
c
s

Operator¶

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical operators

Arithmetic Operators (+, -, *, /, %, **, and //)¶

In [12]:
5 + 5
Out[12]:
10
In [13]:
2**8
Out[13]:
256
In [14]:
10 % 4
Out[14]:
2
In [15]:
9 // 4 #Floor division
Out[15]:
2

Assignment Operators (=, +=, -=. *=, /=. %=, //, and **=)¶

In [16]:
x=4
x += 4
x
Out[16]:
8
In [17]:
x /= 8
x
Out[17]:
1.0

Comparison Operators (==. !=, >, <. >=, and <=)¶

In [18]:
2 == 2
Out[18]:
True
In [19]:
4 != 5
Out[19]:
True
In [20]:
9 >= 34
Out[20]:
False

Logical Operator (and, or, not)¶

In [21]:
x = 1
In [22]:
x < 5 and x < 10
Out[22]:
True
In [23]:
x < 0 or x < 5
Out[23]:
True
In [24]:
not x < -1
Out[24]:
True

Lists¶

Lists are used to store multiple items in a single variable

In [25]:
list = ["Medical",'Physics']
In [26]:
list[0]
Out[26]:
'Medical'
In [27]:
list[1]
Out[27]:
'Physics'
In [28]:
len(list)
Out[28]:
2
In [29]:
# Lists can have mixed data types
list = ["Medical",'Physics','MDEP',7098]
In [30]:
list[0] = ""
print(list)
['', 'Physics', 'MDEP', 7098]
In [31]:
list.insert(3,"Patrick")
print(list)
['', 'Physics', 'MDEP', 'Patrick', 7098]
In [32]:
list.remove("Patrick")
print(list)
['', 'Physics', 'MDEP', 7098]
In [33]:
list.pop(0)
print(list)
['Physics', 'MDEP', 7098]
In [34]:
list = [100, 50, 65, 82, 23]
list.sort()
print(list)
[23, 50, 65, 82, 100]
In [35]:
def compare(n):
    return -n
list.sort(key = compare)
print(list)
[100, 82, 65, 50, 23]

For loops¶

For loops can be used to access a list element by element or loop over an range.

In [36]:
for l in list:
    print(l)
100
82
65
50
23
In [37]:
for i in range(0,4):
    print(i**2)
0
1
4
9

Functions¶

In [38]:
def pow(i):
    return i**2

print(pow(2))
4
In [39]:
def names(*name):
    for n in name:
        print(n)
        
names("Raphael", "Donatello", "Michaelangelo", "Leonardo")
Raphael
Donatello
Michaelangelo
Leonardo

Math module¶

Python provides the module import math with additional mathematical functions

In [40]:
import math
math.pi
Out[40]:
3.141592653589793
In [41]:
math.sqrt(2)
Out[41]:
1.4142135623730951

A complete list with all functions and methods is available here.

Classes¶

Python is an object oriented programming language. An object can contain variables and functions.

  • The __init__ method is called each time, we generate a new object
  • The keyword self is used to access the internal class variables and functions
In [42]:
class Person:
    def __init__(self, name,age):
        self.name = name
        self.age = age
        
    def birthday(self):
        self.age +=1
        
student = Person("Mike",20)
print(student.name)
print(student.age)
student.birthday()
print(student.age)
Mike
20
21

Packages¶

  • Matplotlib - Visualization with Python
  • Numpy - Arrays and numerical computing tools
  • SciPy - algorithms for optimization, integration, interpolation, eigenvalue problems, algebraic equations, differential equations, statistics
  • VTK - Image processing, 3D graphics, volume rendering and visualization
  • mshio - Converting between various mesh formarts
  • TensorFlow or Keras - Machine learning and deep learning