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
defchangeVariable():
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
defchangeVariable():
globali_glob
i_glob=222
return
changeVariable()
#print(i_glob)
```
%% Cell type:code id: tags:
``` python
# other ways to access local and global variables
deftest():
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
defupdate_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
importnumpy
# import the package numpy to a variable called np
importnumpyasnp
# import the function "array" from the package numpy
fromnumpyimportarray
# import all functions from the package numpy
fromnumpyimport*
```
%% 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
importnumpy
# convert list to numpy array
Array=numpy.array(Liste)
```
%% Cell type:code id: tags:
``` python
# import numpy to variable np
importnumpyasnp
# convert list to numpy array
Array=np.array(Liste)
```
%% Cell type:code id: tags:
``` python
# import only the array funtion from the package numpy
fromnumpyimportarray
# 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")
forlineinmyFile:
print(line)
myFile.close()
```
%% Cell type:code id: tags:
``` python
# keepting the data
file_list=[]
file=open("data/data_file.txt","r")
forlineinfile:
file_list.append(line)
file.close()
```
%% Cell type:code id: tags:
``` python
# another way (the cleanest, as the file is closed automatically)
withopen("data/data_file.txt")asf:
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+")
forlineinfile_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
classDog:
# Class attribute
species='mammal'
# Initializer / Instance attributes
def__init__(self,name,age):
self.name=name
self.age=age
# instance method
defdescription(self):
return"{} is {} years old".format(self.name,self.age)
# instance method
defspeak(self,sound):
return"{} says {}".format(self.name,sound)
# Child class (inherits from Dog() class)
classRussellTerrier(Dog):
defrun(self,speed):
return"{} runs {}".format(self.name,speed)
# Child class (inherits from Dog() class)
classBulldog(Dog):
defrun(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
classBank_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
defwithdraw(self,amount):
'''more documentation'''
self.balance-=amount
return
# this is a method - a function belonging to a class
defdeposit(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__
"**2. Plot the data to get a better feel for it. (Scattermatrix would be a good idea)**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3. Now plot the data _grouped_ by target_name.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**4. Create a multidimensional linear model that tries to guess the petal width depending on petal_length, sepal_width, sepal_length and check how well it fits!**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**5. Create Numpy array from the setosa sepal and petal values only!**"