Commit 7cb62627 authored by christian.foerster's avatar christian.foerster
Browse files

minor changes

parent 73d053b5
......@@ -440,7 +440,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tupel"
"### Tuple"
]
},
{
......@@ -945,36 +945,19 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# you can even pass functions as function arguments\n",
"def add_ten(func,a,b):\n",
" '''\n",
" my function\n",
" '''\n",
" return func(a,b)+10\n",
"\n",
"print(add_ten(sum_2,0,1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"sys.getrecursionlimit()\n",
"#sys.setrecursionlimit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 2,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.54 ms ± 69.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n",
"1.02 ms ± 23.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n",
"842 µs ± 22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"# recursion works like this (std limit 3000)\n",
"def factorial_slow(n):\n",
......@@ -982,7 +965,7 @@
" if n==1:\n",
" return n\n",
" else:\n",
" return n*factorial(n-1)\n",
" return n*factorial_slow(n-1)\n",
"\n",
"# lets compare the execution time of recursion to a while loop\n",
"def factorial_fast(m):\n",
......@@ -1013,6 +996,22 @@
"# for is faster than while\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# you can even pass functions as function arguments\n",
"def add_ten(func,a,b):\n",
" '''\n",
" my function\n",
" '''\n",
" return func(a,b)+10\n",
"\n",
"print(add_ten(sum_2,0,1))"
]
},
{
"cell_type": "code",
"execution_count": null,
......@@ -1800,7 +1799,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
"version": "3.7.4"
}
},
"nbformat": 4,
......
%% Cell type:markdown id: tags:
# A short Introdcution to Python
## Things you might be wondering:
- What is an Anaconda and what does it have to do with Python
- Anaconda program to manage virtual environments
- can be set up in a virtual environment
- Python 2 vs Python 3?
- unsupported vs. supported
- Where does Python fit in?
- for educational purposes (https://www.researchgate.net/publication/328175547_MatLab_vs_Python_vs_R)
- more generally speaking (https://pyzo.org/python_vs_matlab.html) (R is mainly for data wrangling)
- development -> if you want to develop open source software, that many people can use, you need a open source language!
- Is Python fast?
- not really
- it can comparable to c++/c/fortran (numpy, cython, numba)
- Why is Python so popular?
- easy to learn/use
- code readabiltiy
- open source
- huge commuinuty
- general purpose language
## Some nice-to-know's
* indexing starts at 0
* the syntax i controlled mainly by tabs (4 spaces), that mean less brackets and better readability
* so you should adapt your texteditor (e.g.: notepad++) to replace a tab with 4 spaces
* commet with hashtag, multiline comments/docstrings like so """my comment or docstring"""
%% Cell type:markdown id: tags:
## Variables and Conversions
%% Cell type:code id: tags:
``` python
# Integer
a=25
# Float
b=5.6
# String
c="6.7"
#Boolean
d=True
# Variable conversion work as follows. (int() always rounds down)
print(float(a),float(c),int(b),str(b),sep="\n")
print("Some string")
a
```
%% Cell type:markdown id: tags:
**Mind the difference between \/ and \/\/**
%% Cell type:markdown id: tags:
**String formatting**
For quick and simple formatting
%% Cell type:code id: tags:
``` python
# Float and int formatting in strings
print("Ich bin %.2f alt." %29.324232) # % für hier muss noch was rein, .2 für 2 Kommastellen, f für float
print("Ich bin %i alt."%29) # ...
# concat strings
print("Ich bin "+str(29)+" alt.")
# copy pasting folder paths (use the r"" -> raw string mode)
print(r"C:\adg\ggj")
```
%% Cell type:markdown id: tags:
For complexer formatting
%% Cell type:code id: tags:
``` python
# straight forward without index the format arguments
print('{}, {}, {}'.format('a', 'b', 'c'))
# indexing the format arguments
print('first-{0},second-{1},third-{2}'.format('a', 'b', 'c'))
print('{2}, {1}, {0}'.format('a', 'b', 'c',"d"))
print('{2}, {1}, {0}'.format(*'abcd')) # * unpacks the string into a tuple
print('{0}+++{1}---{0}'.format('first', 'second'))
# using keyword arguments and indexing in one step
print("{x}-{x}={z[0]}".format(x=4,z=[0,7]))
```
%% Cell type:code id: tags:
``` python
# interesting string methods
print("dd".replace("d","e"))
print("edf.ggg".split("."))
print("55".isdigit())
# ...
```
%% Cell type:code id: tags:
``` python
# multiline string
"""
this is one
...
"""
# and this
'''
also
one
'''
```
%%%% Output: execute_result
'\nalso \none\n'
%% Cell type:code id: tags:
``` python
# keep in mind
''==""
```
%%%% Output: execute_result
True
%% Cell type:markdown id: tags:
## Basic Math Hints
%% Cell type:code id: tags:
``` python
#Attention!
print("That's a: ", type(6/3))
print("And that's a ",type(6//3))
```
%% Cell type:code id: tags:
``` python
8^5 # what the hell (https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do)
```
%% Cell type:code id: tags:
``` python
print(0^0,1^1,1^0,0^1, sep="\n")
```
%% Cell type:code id: tags:
``` python
8**5 # to the power of
```
%% Cell type:code id: tags:
``` python
-7 // 2 # integer division rounding down!
```
%% Cell type:code id: tags:
``` python
13 % 4 # modulo (divison remainder)
```
%% Cell type:code id: tags:
``` python
x = 3
x += 3 # same as x = x + 3
x *= 2 # same as x = x * 2
x /= 4 # same as x = x / 4
x
```
%% Cell type:markdown id: tags:
## Basic Data Structures
- list() -> ordered, mutable structure (indexing via number)
- dict() -> unordered structure (indexing via keyword)
- tuple() -> ordered, immutable structure (indexing via number)
- sets() -> unordered,immutable representation with unique values only (does not support indexing)
### Lists
%% Cell type:code id: tags:
``` python
# initiate an empty list
mylist=[] # or list()
print(mylist)
# adding values to a list one at a time
mylist.append(2)
mylist.append(4)
print(mylist)
# joining lists, adding mutiple values at once
mylist.extend([22,14])
mylist=mylist+[25,43]
mylist+=[235,143]
print(mylist)
```
%% Cell type:markdown id: tags:
Indexing, slicing, reversing lists
%% Cell type:code id: tags:
``` python
Numbers=[1,2,3,4,5,6,7,8,9,10]
# slice
print(Numbers[2:5])
print(Numbers[:5])
# index
print(Numbers[0]) # gibt den letzten Wert aus
# reverse
print(Numbers[::-1])
```
%% Cell type:code id: tags:
``` python
# sort
Numbers.sort()
print(Numbers)
```
%% Cell type:markdown id: tags:
What can we store in a list?
%% Cell type:code id: tags:
``` python
# lists, dictionary and tuple are very versatile and can store all possible data structures and other things
newlist=[2,3.2,[3],True]
# print the type of the stored values
print(type(newlist[0]),type(newlist[1]),type(newlist[2]),sep="\n")
```
%% Cell type:code id: tags:
``` python
# string to list
list("abcdefghijklmnopqrstuvwxyz")
```
%% Cell type:markdown id: tags:
Attention: pointer or new list?!
%% Cell type:code id: tags:
``` python
a=[4,5,6]
b=a
b[0]=99
b.append(5)
```
%% Cell type:code id: tags:
``` python
a
```
%% Cell type:code id: tags:
``` python
id(a)==id(b)
```
%% Cell type:code id: tags:
``` python
c=a.copy()# copy list (also a[:])
c[2]=9999
```
%% Cell type:code id: tags:
``` python
a
```
%% Cell type:code id: tags:
``` python
id(a)==id(c)
```
%% Cell type:markdown id: tags:
### Tupel
### Tuple
%% Cell type:code id: tags:
``` python
# tuple are intitated with tuple() or ()
x = (1, 2, 3)
len(x)
```
%% Cell type:code id: tags:
``` python
# indexing, slicing and reversing is the same as in lists
y = (4, 5, 6)
print(y[:2])
print(y[-1])
y[::-1]
```
%% Cell type:code id: tags:
``` python
listOfTuples = [x, y]
listOfTuples
```
%% Cell type:markdown id: tags:
**Unpacking of lists and tuples**
%% Cell type:code id: tags:
``` python
(age, income) = "32,120000".split(',')
print(age)
print(income)
print(income.replace("0","9"))
```
%% Cell type:markdown id: tags:
### Dictionaries
%% Cell type:code id: tags:
``` python
# initiate a dictionary {} or dict()
lastnames = {}
# fill the dictionary
lastnames["Jakob"] = "Benisch"
lastnames["Stefanie"] = "Wiek"
lastnames["Winnie"] = "Puh"
lastnames["Christian"] = "Koch"
lastnames["blaa"]=[1,2,3,43,12,21,3,43]
print(lastnames)
# indexing
print(lastnames["Christian"])
```
%% Cell type:code id: tags:
``` python
# indexing with error catch
print(lastnames.get("Bruno"))
```
%% Cell type:code id: tags:
``` python
# accessing data of a dict
print(lastnames.items())
print(lastnames.keys())
print(lastnames.values())
```
%% Cell type:code id: tags:
``` python
# Some problematic as in lists pointers and new dictionary
a={"a":3}
b=a.copy()
b["a"]=99
a
```
%% Cell type:markdown id: tags:
### Sets
%% Cell type:code id: tags:
``` python
a={1,2,3,4,3,4,5}
print("a: {}".format(a))
b=set([2,4,2,2,6,4,23])
print("b: {}".format(b))
print("In a but not in b: {}".format(a.difference(b)))
```
%% Cell type:markdown id: tags:
**A quick Comparison**
%% Cell type:code id: tags:
``` python
# list
[1,2,3,4,5,3]
# tuple
(3,2,4)
# dict
{"myname":40}
# set
{1,2,3}
```
%% Cell type:code id: tags:
``` python
# For all of these we can use the in statement to check whether a number is in a given list.
3 in [3,4]
3 in {3:"for dictionaries the key will be checked"}
3 in (3,4)
3 in {3,4}
```
%% Cell type:markdown id: tags:
## Learning by doing!
In order to not fall asleep when looking at python syntax, let's have a little break and do some exercises.
### Exercise Round 1
- What's the remainder of $2^{99}$ divided by $57$?
- If you were to write a little database, that gets one file for every day containing data for that day.
And you want to store the file locations in a basic python data structure. Which one would you use and why?
- If you want to check two large python lists for commen values, how would you do it?
%% Cell type:markdown id: tags:
## Loops
%% Cell type:code id: tags:
``` python
# summing up the values of a list
summe=0
for num in [1,2,3,4]:
# everything that is endeted is within the loop
summe+=num
print(num)
print("Summe: "+str(summe))
```
%% Cell type:code id: tags:
``` python
for number in [1,2,3,4,[],"ffffdd"]:
print(number)
```
%% Cell type:code id: tags:
``` python
# while loop example
start=1
end=6
while start<end:
print(start)
start+=1
```
%% Cell type:code id: tags:
``` python
# be careful with while loop
# this one would run endlessly
#while True:
# a=1
```
%% Cell type:code id: tags:
``` python
# nested loop matrix (m,n) filled with ones, technically speaking its a list not a matrix...
m=4
n=10
matrix=[]
for i_m in range(m):
matrix.append([])
for i_n in range(n):
matrix[i_m].append("{},{}".format(i_m,i_n))
matrix
```
%% Cell type:markdown id: tags:
## Control Statements
%% Cell type:code id: tags:
``` python
a=2
if a==3:
print("a is 3!")
elif a==1:
print("a is 1!")
else:
print("a is not 3, nor 1!")
```
%% Cell type:code id: tags:
``` python
# try rerunning that script
if type(age)==str:
print("Told you its a string!")
# converts to an integer
age=int(age)
else:
print("Guess I was wrong. It's a %s" %str(type(age)))
#converts to a string
age=str(age)
```
%% Cell type:markdown id: tags:
## Nifty One-Liners
%% Cell type:code id: tags:
``` python
# control statement one - liner
3 if 3==3 else "bollox"
```
%% Cell type:code id: tags:
``` python
# fancy list comprehension -> even or uneven?
[(True,i) if i%2==0 else (False,i) for i in range(29)]
```
%% Cell type:code id: tags:
``` python
# dictionary comprehension
{key: value for key, value in zip(["a","b","c"],[1,2,3])}
```
%% Cell type:markdown id: tags:
### Exercise Round 2
Lets write a little program which can be used to analyse files and can count the occurance of patterns in each line!
__Pattern Analyser__
Input:
- A string! (later a file)
Output:
- Number of occurances in each line!
%% Cell type:markdown id: tags:
## Standard Functions
%% Cell type:code id: tags:
``` python
help(abs)
```
%% Cell type:code id: tags:
``` python
min([1,2])
```
%% Cell type:code id: tags:
``` python
max([1,2])
```
%% Cell type:code id: tags:
``` python
sorted([8,1,2])
```
%% Cell type:code id: tags:
``` python
len([1,2])
```
%% Cell type:code id: tags:
``` python
range(99)
```
%% Cell type:code id: tags:
``` python
zip([2,3,4],[55,77,66])
```
%% Cell type:code id: tags:
``` python
enumerate([3,4,5])
```
%% Cell type:code id: tags:
``` python
sum([3,4,67])
```
%% Cell type:code id: tags:
``` python
all([True,True]) and not any([False, False])
```
%% Cell type:markdown id: tags:
## Writing your own Functions
%% Cell type:code id: tags:
``` python
# function to add two arguments
def sum_1(a,b):
return a+b
# funtion with provided default values for arguments
def sum_2(a,b=6,c=9,d=98):
'''
this is my docstring
'''
c=a+b+c
return c
# this function does add the two input arguments but does not return them
def sum_3(a,b):
c=a+b
return 3,4,5
# playing around with the defined functions
print(sum_1(2,3))
print(sum_2(2,c=-44))
print(sum_3(2,3))
```
%% Cell type:code id: tags:
``` python
# you can even pass functions as function arguments
def add_ten(func,a,b):
'''
my function
'''
return func(a,b)+10
print(add_ten(sum_2,0,1))
```
%% Cell type:code id: tags:
``` python
import sys
sys.getrecursionlimit()
#sys.setrecursionlimit()
```
%% Cell type:code id: tags:
``` python
# recursion works like this (std limit 3000)
def factorial_slow(n):
if n==1:
return n
else:
return n*factorial(n-1)
return n*factorial_slow(n-1)
# lets compare the execution time of recursion to a while loop
def factorial_fast(m):
res=1
while m>1:
res*=m
m-=1
return res
def factorial_fastest(number):
if number == 1 or number == 0:
return 1
result = 1 # variable to hold the result
for x in range(1, number + 1, 1):
result *= x
return result
# performance check
%timeit factorial_slow(2000)
%timeit factorial_fast(2000)
%timeit factorial_fastest(2000)
# for is faster than while
```
%%%% Output: stream
1.54 ms ± 69.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.02 ms ± 23.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
842 µs ± 22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%% Cell type:code id: tags:
``` python
# you can even pass functions as function arguments
def add_ten(func,a,b):
'''
my function
'''
return func(a,b)+10
print(add_ten(sum_2,0,1))
```
%% Cell type:code id: tags:
``` python
# decorators
def pretty_print(func):
def wrap(arg):
symbols="-"*len(arg)
print(symbols)
res=func(arg)
print(symbols)
return res
return wrap
@pretty_print
def printer(string=3):
print(string)
printer(" o -|- ofdsgafdgfdsagdsgsa ")
```
%% Cell type:code id: tags:
``` python
# special function argumentes
def arbitiary_number_of_arguments(*args):
print(*args)
print(args)
return "-".join([str(a) for a in args])
arbitiary_number_of_arguments(2,3,4,5,6)
```
%% Cell type:code id: tags:
``` python
# special function keyargumentes
def arbitiary_number_of_keyword_arguments(**kwargs):
print(kwargs)
arbitiary_number_of_keyword_arguments(ab=2,cd=4,ef=5,gh="ee")
```
%% Cell type:code id: tags:
``` python
# args before kwargs!!
def both(*args,**kwargs):
return args,kwargs
both(3,4,2,4,5,wa=2,ab=44)
```
%% Cell type:markdown id: tags:
## Generators
%% Cell type:code id: tags:
``` python
# define a generator with the yield statement
def squared_range(n):
for i in range(n):
yield i**2
```
%% Cell type:code id: tags:
``` python
# using a generator in a loop
for val in squared_range(8):
print(val)
```
%% Cell type:code id: tags:
``` python
gen=squared_range(8)
```
%% Cell type:code id: tags:
``` python
# use with the next statement
next(gen)
```
%% Cell type:markdown id: tags:
## Local vs Global Variables
Variables can have a local or a global scope. For instance variables used in a function are only known within that function -> local.
%% Cell type:code id: tags:
``` python
# defining a global variable
i_glob=2
# a function defined to change the value of i_glob
def changeVariable():
i_glob = 33
return
```
%% Cell type:code id: tags:
``` python
# which number will be printed????
changeVariable()
#print(i_glob)
```
%% Cell type:code id: tags:
``` python
i_glob=2
# changing global variables from within a function
def changeVariable():
global i_glob
i_glob = 222
return
changeVariable()
#print(i_glob)
```
%% Cell type:code id: tags:
``` python
# other ways to access local and global variables
def test():
a = 9
b = 99
c = 999
print(locals())
test()
```
%% Cell type:code id: tags:
``` python
globals()
```
%% Cell type:code id: tags:
``` python
print(a_local)
```
%% Cell type:code id: tags:
``` python
def update_globals_with_locals():
a_local="how convenient"
globals().update(locals())
return
update_globals_with_locals()
print(a_local)
```
%% Cell type:markdown id: tags:
## Import Packages
Like in moste programming languages many packages exist... To install packages you can use *pip* (Package Installer Python). If you have anaconda installed you can also use *conda*.
Open a terminal/console and install packages like so:
**pip install _packagename_** or **conda install _packagename_**
Once the desired package is installed you can import it.
%% Cell type:code id: tags:
``` python
# import the package numpy
import numpy
# import the package numpy to a variable called np
import numpy as np
# import the function "array" from the package numpy
from numpy import array
# import all functions from the package numpy
from numpy import *
```
%% Cell type:markdown id: tags:
Depending on how you import packages the access to it's functions is slightly different.
%% Cell type:code id: tags:
``` python
# create a list
Liste=[1,2,3]
# import numpy
import numpy
# convert list to numpy array
Array=numpy.array(Liste)
```
%% Cell type:code id: tags:
``` python
# import numpy to variable np
import numpy as np
# convert list to numpy array
Array=np.array(Liste)
```
%% Cell type:code id: tags:
``` python
# import only the array funtion from the package numpy
from numpy import array
# convert list to numpy array
Array=array(Liste)
```
%% Cell type:markdown id: tags:
## Working with Files (low level)
**opening modes:**
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)
%% Cell type:code id: tags:
``` python
# read a file line by line
myFile=open("data/data_file.txt","r")
for line in myFile:
print(line)
myFile.close()
```
%% Cell type:code id: tags:
``` python
# keepting the data
file_list=[]
file=open("data/data_file.txt","r")
for line in file:
file_list.append(line)
file.close()
```
%% Cell type:code id: tags:
``` python
# another way (the cleanest, as the file is closed automatically)
with open("data/data_file.txt") as f:
read_data = f.read()
read_data
```
%% Cell type:code id: tags:
``` python
# writing new file plus creating it (line by line writing)
file=open("data/data_file_new.txt","w+")
for line in file_list:
file.write(line)
file.close()
```
%% Cell type:markdown id: tags:
### Exercise Round 3
Adapt our previous analyser to read a file and analyse it!
__Pattern Analyser__
Input:
- A file
Output:
- A dict containg the line numbers as keys and occurances in that line as value!
Lines without occurances should not be in the dictionary.
%% Cell type:markdown id: tags:
## Object Oriented Programming
%% Cell type:markdown id: tags:
## 4 Pillars of OOP
- Inheritance (a way to reuse your code)
- Abstraction (showing only essential features hiding details)
- Encapsulation (bind data variables and functions together in a class)
- Polymorphism (create functions with same name and different arguments, redefine functions)
%% Cell type:code id: tags:
``` python
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Child class (inherits from Dog() class)
class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child class (inherits from Dog() class)
class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
```
%% Cell type:code id: tags:
``` python
# Child classes inherit attributes and
# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description())
# Child classes have specific attributes
# and behaviors as well
print(jim.run("slowly"))
# Is jim an instance of Dog()?
print(isinstance(jim, Dog))
# Is julie an instance of Dog()?
julie = Dog("Julie", 100)
print(isinstance(julie, Dog))
# Is johnny walker an instance of Bulldog()
johnnywalker = RussellTerrier("Johnny Walker", 4)
print(isinstance(johnnywalker, Bulldog))
# Is julie and instance of jim?
print(isinstance(julie, RussellTerrier))
```
%% Cell type:markdown id: tags:
## Special Methods, hidden Variables, ...
Fancy things we can do!
%% Cell type:code id: tags:
``` python
class Bank_Account():
bank = "Some Bank"
'''my documentation'''
# this function is being run, when the class is initialized.
# (So when an object is created)
def __init__(self, account_balance):
self.balance = account_balance
return
# this is a method - a function belonging to a class
def withdraw(self, amount):
'''more documentation'''
self.balance -= amount
return
# this is a method - a function belonging to a class
def deposit(self, amount):
self.balance += amount
return
# this is a protected method
def _protected(self):
print("easy to access...")
# this is a hidden method
def __hidden(self):
print("can't make python methods more private than this...")
# this is a so called magix method, just like __init__
def __add__(self, other):
balanceSum = self.balance + other.balance
print("Their future shared account holds {}.".format(balanceSum))
return self.balance + other.balance
# the representation of the instance
def __repr__(self):
return "This is an instance of the class {}.".format(self.__class__.__name__)
```
%% Cell type:code id: tags:
``` python
# create objects (objects are instnances of a class)
Jana=Bank_Account(33)
Steffen=Bank_Account(644)
Jana.withdraw(10)
Jana+Steffen
```
%% Cell type:markdown id: tags:
If you want to know more about OOP check out: https://www.oodesign.com/
## Error Handling
%% Cell type:code id: tags:
``` python
# cause an error
"e"+3
```
%% Cell type:code id: tags:
``` python
# catch the error
try:
"e"+3
except:
print("Caught it!")
```
%% Cell type:code id: tags:
``` python
# better would be to catch a certain error
# so that if something unexpected happens you will know what it is
try:
"e"+3
except :
print(3)
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Beispiele
So jetzt zeigen ich einfach mal ein paar Beispiele und die kannst du ja mal nachvollziehen. Danach bekommst du ein paar Übungsaufgaben.
%% Cell type:code id: tags:
``` python
class Notepad():
def __init__(self):
self.notes = {}
self.selectedNote=None
return
def _noteNameCheck(self,noteName):
if noteName is None and self.selectedNote is None:
raise ValueError("Please provide a noteName.")
elif noteName is None:
noteName = self.selectedNote
return noteName
def addNote(self, noteName):
self.selectedNote=noteName
self.notes[noteName] = {}
return self.notes
def deleteNote(self, noteName=None):
noteName = self._noteNameCheck(noteName)
del self.notes[noteName]
self.selectedNote = None
return self.notes
def addEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName)
self.notes[noteName][entry]="unmarked"
return self.notes
def deleteEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName)
del self.notes[noteName][entry]
return self.notes
def markEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName)
self.notes[noteName][entry]="marked"
return self.notes
NotepadInstance = Notepad()
NotepadInstance.addNote("Shopping")
NotepadInstance.addEntry("coffee")
NotepadInstance.addEntry("milk")
NotepadInstance.addEntry("break")
NotepadInstance.addEntry("chocolate")
NotepadInstance.markEntry("chocolate")
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# create your own error message
class WhatHaveYouDoneNowError(Exception):
pass
raise WhatHaveYouDoneNowError("This error occurs when you do things that fall under the category:'You have done what???????'")
```
%% Cell type:code id: tags:
``` python
# list containing numbers from 1 to 10
Numbers=list(range(11))[1:]
# create a new list containing only even numbers
Even=[]
for num in Numbers:
if num%2==0:
Even.append(num)
print(Even)
# the short version with list comprehension
# mind the syntax, reads almost like a sentences
Even=[num for num in Numbers if num%2==0]
print(Even)
```
%% Cell type:code id: tags:
``` python
# webscraping for a wg easy
# popular package for sending HTTP requests
import requests
# regular expressions
import re
# get source of webpage
r = requests.get("https://www.wgzimmer.ch/en/wgzimmer/search/mate/ch/zurich-stadt.html?wc_language=en")
webpage_content = r.text
# filtet to find links to flats
re.findall('''<a href="/en/wgzimmer/search/mate/ch/zurich-stadt/(.+).html">''',webpage_content)
```
%% Cell type:code id: tags:
``` python
# we'll create function that gets rid of repeating entries in lists
Liste=[1]*10+[2,2]+[3]*4
print(Liste)
def Uniquify_long(L):
unique=[]
for i in L:
if i not in unique:
unique.append(i)
return unique
print("Result of the long syntax: "+str(Uniquify_long(Liste)))
# or with list comprehension
def Uniquify_medium(L):
unique=[]
[unique.append(i) for i in L if i not in unique]
return unique
print("Result of the medium syntax: "+str(Uniquify_medium(Liste)))
# and the shortest
def Uniquify_short(L):
return [num for pos,num in enumerate(L) if num not in L[:pos]]
print("Result of the short syntax: "+str(Uniquify_short(Liste)))
# thats the most efficient and easiest way
print(set(Liste))
```
%% Cell type:code id: tags:
``` python
# boolean expressions
print(1 is not 3)
print(True or False)
print(True==1)
print(False and False == False)
print((False and False) == False)
```
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment