Skip to content
Snippets Groups Projects
Commit d3acac93 authored by Máté Zoltán Farkas's avatar Máté Zoltán Farkas
Browse files

python tutorial material ready

parent 3819f134
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:897fcfcd tags:
# Python Tutorial
-----------------------
Welcome to this warm-up tutorial! Let's take a look at some highlights of Python!
Please execute the whole notebook now by clicking on Cell->Execute All in the menubar. In the following, cells starting with TODOs and ending with a ```?``` are tasks to be solved individually.
Let's start with the usual **hello world** program:
%% Cell type:code id:c8562e26 tags:
``` python
print("Hello World!")
```
%% Output
Hello World!
%% Cell type:markdown id:48a13786 tags:
You can print multiple items in a row:
%% Cell type:code id:bea4da9f tags:
``` python
print("1 + 12 =", 13)
```
%% Output
1 + 12 = 13
%% Cell type:markdown id:5a70d15c tags:
## Comments
You can also comment your code with ```#``` for a **single line** or with ```"""comment"""``` for **multiple lines**:
%% Cell type:code id:6b5d414b tags:
``` python
# This is a comment and will be ignored upon execution
```
%% Cell type:code id:d69d90e9 tags:
``` python
print("What's that thing that spells the same backwards as forwards?")
"""
I am a comment too!
See, this line is ignored as well!
"""
print("A palindrome...?")
```
%% Output
What's that thing that spells the same backwards as forwards?
A palindrome...?
%% Cell type:markdown id:c4c8535a tags:
## Variables and Data-Types
Python is a **dynamically-typed** language, i.e. you don't have to define your variable types:
%% Cell type:code id:f7179786 tags:
``` python
a = 13 # This is an integer
b = "This is a string" # This is a string
c = True # A boolean
d = 14.5 # This is a double-precision floating-point variable (called a 'double' in C-speak)
e = [1, 3, 15, 34] # This is a list, an array of objects
f = ("Emmental", "Brie", "Gouda", "Danish Blue") # This is a tuple, an immutable array
```
%% Cell type:code id:d0586d1b tags:
``` python
# You can use squared brackets to access elements in an array or tuple
# TODO: What's the second element in array e?
print("The second element in a is:", None,"(should be 3)")?
```
%% Output
File "/tmp/ipykernel_51154/998780084.py", line 3
Input In [6]
print("The second element in a is:", None,"(should be 3)")?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:0019db03 tags:
## Elementary Arithmetics
You can use the usual **operators** +, -, *, / for elementary arithmetics:
%% Cell type:code id:86b8e68c tags:
``` python
# TODO: Use the variables a and d defined above to calculate 13 x 14.5!
print("13 x 14.5 =", "?")?
```
%% Output
File "/tmp/ipykernel_51154/2320046825.py", line 2
Input In [12]
print("13 x 14.5 =", "?")?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:32b1985e tags:
You can use the **double star** \*\*-operator to raise number to the **n-th power**:
%% Cell type:code id:8c45add3 tags:
``` python
print(1**2, 2**2, 3**2, 4**2, 32**2)
```
%% Output
1 4 9 16 1024
%% Cell type:code id:29eac6ed tags:
``` python
# TODO: Booleans work as numbers as well. What happens if you add a and c?
print("13 + True =", "?")?
```
%% Output
File "/tmp/ipykernel_51154/2665876267.py", line 2
Input In [14]
print("13 + True =", "?")?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:f6d98d65 tags:
## Comparison Opeartors
You can use <, >, ==, <=, >= to **compare numbers** (**and objects**), the **keywords** ```and```, ```or``` to compare statements (booleans) and the keyword ```not``` to negate them.
%% Cell type:code id:b0a7cbe1 tags:
``` python
# TODO: What's the output of ("a bigger than d" AND "c is True")?
print((a==14) and not (c<d))?
```
%% Output
File "/tmp/ipykernel_51154/816995051.py", line 2
Input In [15]
print((a==14) and not (c<d))?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:cbba9080 tags:
## Control Flow Tools
For pre-test loops you can use ```while```. Beware that in Python indented blocks of code belongs to the same parent line (similarly to ```{...}``` in C); mixing indentations yields an ```IndentationError```.
For pre-test loops you can use ```while```. Beware that in Python indented blocks of code belong to the same parent line (similarly to ```{...}``` in C); mixing indentations raises an ```IndentationError```.
%% Cell type:code id:bc0a1aa7 tags:
%% Cell type:code id:5f42b63f tags:
``` python
# TODO: fix the while loop below:
i = 0
while i<4:
print(i)
i = i + 1
```
%% Output
File "/tmp/ipykernel_51154/3109148489.py", line 5
Input In [16]
i = i + 1
^
IndentationError: unexpected indent
%% Cell type:markdown id:f5d33ba2 tags:
%% Cell type:markdown id:118d8935 tags:
Using ```for``` and the iterable ```range(n)``` a for-like loop can be created:
%% Cell type:code id:d26a4b8a tags:
%% Cell type:code id:7740d793 tags:
``` python
# TODO: Write a for loop adding up all the numbers from 0 to 100 and print the result.
sum = 0
for i in range(5):
print("")
print(sum)?
```
%% Output
File "/tmp/ipykernel_51154/756008327.py", line 5
Input In [17]
print(sum)?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:b3730030 tags:
%% Cell type:markdown id:fd2059e5 tags:
For **conditional branching**, the usual keywords ```if``` and ```else``` are defined. Loops can be stopped with ```break``` and skipped with ```continue```.
%% Cell type:code id:9a89a44c tags:
%% Cell type:code id:0c47c5d6 tags:
``` python
# TODO: With i%2, you can get the modulus of i divided by two.
# TODO: Write a small program checking whether i is an even or odd number for every i in [0, 10).
# TODO: Use 'continue' to skip 0!
n = 1
for i in range(n):
if True:
print(i, "is an odd/even number")
else:
print("else block")?
```
%% Output
File "/tmp/ipykernel_51154/2853117672.py", line 9
Input In [18]
print("else block")?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:2b795be3 tags:
%% Cell type:markdown id:f51fc582 tags:
## Functions
For repeating code, functions can be defined with the ```def``` keyword and their outputs can be returned using ```return```. These funtions can be also called recursively.
%% Cell type:code id:1768ca2b tags:
%% Cell type:code id:d5f33c84 tags:
``` python
def get_greeting(name):
return "Hello " + name +"!"
print(get_greeting("John Cleese"))
print(get_greeting("Graham Chapman"))
print(get_greeting("Eric Idle"))
```
%% Output
Hello John Cleese!
Hello Graham Chapman!
Hello Eric Idle!
%% Cell type:code id:e123d01c tags:
%% Cell type:code id:04034c0e tags:
``` python
# TODO: Implement the factorial operation
def factorial(n):
print(n)
return 0
factorial(10)?
```
%% Output
File "/tmp/ipykernel_51154/1882212969.py", line 5
Input In [20]
factorial(10)?
^
SyntaxError: invalid syntax
%% Cell type:markdown id:179e54d9 tags:
%% Cell type:markdown id:49898002 tags:
## Classes
Classes are high-level objects for storing and managing primitives. They are initialized with ```class class_name:``` after which the constructor ```__init__(self, args)``` is automatically called. Data in classes are stored using the ```self``` keyword, which are publicly accessible by default.
Classes are high-level objects for storing and managing primitives. They are initialized with ```class class_name:``` after which the constructor ```__init__(self, args)``` is automatically called. Data in classes are stored using the ```self``` keyword and are publicly accessible by default.
%% Cell type:code id:d399a53d tags:
%% Cell type:code id:dd4ae61f tags:
``` python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print("name:", self.name, ";", "age:", self.age)
alice = Person("Alice", 34)
alice.print_info()
alice.age = 18
alice.print_info()
```
%% Output
name: Alice ; age: 34
name: Alice ; age: 18
%% Cell type:markdown id:cd09aaa1 tags:
%% Cell type:markdown id:0d914e99 tags:
## Class Inheritance
A class can inherit the properties of the parent class. These properties can be freely overriden:
A class can inherit the properties of its parent class. These properties can be freely overriden:
%% Cell type:code id:60a46ff6 tags:
%% Cell type:code id:caf893b1 tags:
``` python
class Student(Person):
def print_info(self):
"""
Beware that name is inherited from 'Person'
Beware that the attribute name has been inherited from 'Person'
"""
print(self.name, "is a student!")
bob = Student("Bob", 20)
bob.print_info()
```
%% Output
Bob is a student!
%% Cell type:markdown id:39f231b0 tags:
## Numpy Basics
Numpy is an performant, easy-to-use scientific library for numeric calculations. You will often encouter cases where numpy can perform calculations several orders of magnitues faster due its C-backend and ability to process data in a vectorized (not individuallistic) form.
%% Cell type:code id:dfaeae8a tags:
``` python
import numpy as np # numpy is usually imported this way
```
%% Cell type:markdown id:935518b0 tags:
### Numpy One Dimensional Array Operations
Numpy operates on arrays element-wise meaning elementary operations are performed in an intuitive vectorized form.
%% Cell type:code id:2aff9b94 tags:
``` python
zero_array = np.zeros(10) # creates an an array of 10 zeros
one_array = np.ones(10) # creates an array of... guess what!
two_array = np.ones(10)*2 # this one is a bit more tricky
three_array = one_array + two_array # arrays are added element-wise
print(three_array)
# You can also create numpy arrays from python lists:
np_array_from_python_list = np.array([11, 22, 33, 44, 55, 66, 77])
print(np_array_from_python_list, type(np_array_from_python_list))
```
%% Output
[3. 3. 3. 3. 3. 3. 3. 3. 3. 3.]
[11 22 33 44 55 66 77] <class 'numpy.ndarray'>
%% Cell type:markdown id:e6057042 tags:
For this to work however the arrays must be of the same shape, otherwise a ```ValueError``` will be raised. In order to avoid this error, you can always access the shape of an array using the ```array.shape``` syntax:
%% Cell type:code id:1141c56f tags:
``` python
array1 = np.arange(10) # [0, 1, 2, ..., 9]
print("Shape of array1", array1.shape) # shape: (10,)
array2 = np.array([10]*5) # [10, 10, 10, 10, 10 ]
print("Shape of array2", array2.shape) # shape (5,)
print(np_array1/np_array2) # Voilà ValueError due to conflicting shapes
```
%% Output
Shape of array1 (10,)
Shape of array2 (5,)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [25], in <cell line: 5>()
3 array2 = np.array([10]*5) # [10, 10, 10, 10, 10 ]
4 print("Shape of array2", array2.shape) # shape (5,)
----> 5 print(np_array1/np_array2)
NameError: name 'np_array1' is not defined
%% Cell type:markdown id:d236a438 tags:
### Numpy Arrays of Multiple Dimensions
Numpy supports the creation of n-dimensional arrays (arrays, matrices, tensors). Let's say you wish to generate 5 normally distributed samples of size 1000 with means 0, 10, 20, 30 and 40 and standard deviation 1. For this, you can first generate 5\*1000 samples around 0, put them into a marix of shape (5, 1000) and shift each distribution to their respective means.
%% Cell type:code id:47d6ecce tags:
``` python
ndists = 5
sample_size = 1000
dataset = np.random.normal(0, 1, ndists*sample_size) # Dataset generation
print("Shape of the original dataset:", dataset.shape) # Printing the dataset shape
dataset_reshaped = dataset.reshape(ndists, sample_size) # Reshaping it to (5, 1000)
print("Shape of the reshaped dataset:", dataset_reshaped.shape) # Printing the new shape
```
%% Output
Shape of the original dataset: (5000,)
Shape of the reshaped dataset: (5, 1000)
%% Cell type:markdown id:8bffbc39 tags:
Now we can define our shift vector, extend it with a new "dimension" (called axis, i.e. bring it into the shape (5, 1)), such that all elements at the second index "see" a scalar.
%% Cell type:code id:f2ea360c tags:
``` python
shift_vector = np.arange(5)*10 # np.arange(n) creates an array of integers from 0 to n-1
shift_vector = shift_vector[:, np.newaxis] # np.newaxis takes care of the new axis creation
print("Shift vector shape:", shift_vector.shape) # observe that reshape has not been called
```
%% Output
Shift vector shape: (5, 1)
%% Cell type:markdown id:64fdffa1 tags:
Now our gaussians can be shifted to their right places!
%% Cell type:code id:f0177d95 tags:
``` python
dataset_shifted = shift_vector + dataset_reshaped # shape (5, 1) + shape (5, 1000) = shape (5, 1000)
import matplotlib.pyplot as plt # import the plotting library to showcase the results
for hist in dataset_shifted: # Iterate over every distribution
plt.hist(hist)
```
%% Output
%% Cell type:code id:439f4bf4 tags:
``` python
# ... or you check the documentation and solve the problem directly by invoking:
dataset_shifted = np.random.normal(loc=np.arange(5)*10, scale=np.ones(5), size=(1000, 5)).T
for hist in dataset_shifted:
plt.hist(hist)
# Always check the docs before inventing something "new"!
```
%% Output
%% Cell type:markdown id:7a826bff tags:
### Numpy Miscellaneous:
Below you can find a non-exhaustive list of built-in numpy functions for quick data analysis:
%% Cell type:code id:973bd72b tags:
``` python
print("Basic array operations:")
print("Sum", np.sum(np.arange(101))) # Sum of all numbers from 0 to 100
print("Mean", np.mean(dataset_shifted, axis=1)) # Mean of the generated gaussians from above...
print("Std", dataset_shifted.std(axis=1)) # ...and their respective standard deviations with a different syntax
print("Flattened array:", dataset_shifted.flatten()) # .flatten() makes an array 1D
```
%% Output
Basic array operations:
Sum 5050
Mean [ 0.08110435 9.98545632 20.02933072 30.02389687 39.97474169]
Std [0.99851965 0.97608616 1.0021044 0.98741231 1.00744611]
Flattened array: [-0.44605952 -0.22217352 -0.25286257 ... 41.29848664 39.92391046
39.72392673]
......
%% Cell type:markdown id:269d507c tags:
# Tensorflow Tutorial
---------------------------------
%% Cell type:code id:fb7e3964 tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment