View
2
Download
0
Category
Preview:
Citation preview
Discovering
Python
Michael Weigend
Universität Münster
Holzkamp-Gesamtschule Witten
Vilnius 2017
Outline
Presentation 1 “Introduction to Python”
Application domains, basic features, functions, data structures, OOP, logical correctness
(assertions)
Hands On Exercise 1
Basic Python programming
Coffee Break
Presentation 2 “Python on the Raspberry Pi”
Hands On Exercise 2
Part 1: LEDs, temperature sensors, camera module
Part 2: Projects with the SenseHAT
Advanced tasks: GUI programming with tkinter
Final discussion
Material
1) Handout with suggestions what to do
2) Example programs to try out and to modify
Application Domains
Created With Python
Creator: Stani Michiels
A Minimalist Version
20 Lines of Code
Visualization of the Mandelbrot Set from tkinter import *
RADIUS = 2.0
ZOOM = 50.0
class Mandelbrot:
def __init__(self):
self.window = Tk()
self.image = PhotoImage(width=200, height=200)
self.image_label = Label(master=self.window,
image=self.image)
self.image_label.pack()
self.draw()
self.window.mainloop()
def draw(self):
interval = [x/ZOOM for x in range(-100, 100)]
mandelbrot = [(x, y) for x in interval
for y in interval
if self.test(x, y)]
for x, y in mandelbrot:
self.image.put("#0000ff", (int(ZOOM*x+100), int(ZOOM*y+100)))
def test (self, x, y):
c = x + 1j * y # j is the imaginary number i
z = 0
for i in range(20):
if abs (z)< RADIUS:
z = z*z - c
else: return False # not in the Mandelbrot set
return True # element of the Mandelbrot set
m = Mandelbrot()
Application Domains
• creative projects Disney VR Studio, Industrial Light & Magic
• science American Space Telescope Institute, Deutsche Gesellschaft für Luft- und Raumfahrt
• web services Google, BSCW, Dropbox
• security sensible systems governments, airlines, banking
• Education universities (MIT), schools
Advantages of Python
• simple (minimalist)
• consistent
• short programs
• platform independent
• open source
• many programming paradigms
Computer Programs
are Written for Humans
Donald Knuth (1984):
„I believe that the time is ripe for
significantly better documentation of
programs, and that we can best
achieve this by considering
programs to be works of
literature.”
Knuth, D. E.: Literate Programming. In:
The Computer Journal 27/2, 1984, S.
97-111.
Dynamic Typing
int a;
double[3] s;
a = 3;
s = [1.1, 2, 3]
a = 3
s = [1.1, 2, 3]
Python Java
Name
Type
Object
int
float Ducktyping
Name
Type Object
Intuitive Models
Python Java
int a;
a = 3;
a = 3
Verbosity: Minimal Code
if ( a > b )
{
a = b;
b = c;
}
if a > b:
a = b
b = c
no semicolons
indentation for defining blocks of code
Python Java
Associated Boolean Values
None () {} [] 0 False
s = [1, 3, 5]
while s:
print s[0]
del s[0]
1
3
5
“Empty “ objects
Using Common Mathematical Notation
if((14 < age) && (age < 60))
{
System.out.println("Welcome!")
}
if 14 < age < 60:
print ("Welcome!")
Python Java
(Implicit) Tuples
a, b = 12, 14
a, b = b, a
Simple swapping
Compact assignments
Functions
Live Presentation 1
• position parameters
• keyword parameters
• docstring
• default values and multiple number of parameters
def area (…)
Type
Hierarchy
Operations for Collections
>>> numbers = [2, 3, 56, 12]
>>> 1 in numbers
False
>>> "e" in "Delft"
True
in
>>> for c in "Delft" : print (c)
D
e
l
f
t
>>> for i in numbers:
print (i)
2
3
56
12
Iteration
Operations for Sequences
concatenation
indexing and slicing
>>> w = "Delft"
>>> 'Tiles from ' + w
'Tiles from Delft'
>>> 2*w
'DelftDelft'
>>> w[0]
'D'
>>> w[0:2]
'De'
>>>
>>> w[2:]
'lft'
>>> numbers = [2, 3, 56, 12]
>>> 2*numbers
[2, 3, 56, 12, 2, 3, 56, 12]
>>> numbers = [2, 3, 56, 12]
>>> numbers[0]
2
List mutable sequence
list items may be all kinds of objects
[1, 2, 3]
[1, "a", [1, 2], len]
[]
[[], [], []]
List Comprehension
[n*n for n in [1, 2, 3]]
Which items are in this list?
List Comprehension
[n*n for n in [1, 2, 3]]
[1, 4, 9]
Set Builder Notation
s = {2*x for x in {1, 2, 3, 4, 5} if x**2 > 3}
Modeling with Lists
Stack last in – first out
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
Modeling with Dictionaries
Mapping key value
>>> tel = {'jack': 4098, 'tom': 4139}
>>> tel['guido'] = 4127
>>> tel
{‘tom': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['tom']
>>> tel
{'guido': 4127, 'jack': 4098}
create a dictionary
find a value using a key
delete an item
add an item
Object Oriented Programming
Everything is an object!
>>> a=1
>>> type(a)
<class 'int'>
>>> id(a)
9786792
>>> a + 2
3
>>> a.__add__(2)
3
Object Oriented Programming
Live Presentation 2
• Class definition
• Class attributes, object attributes
• Methods
• Polymorphism (overloading)
Modeling Volume
0.05 mL
1.0 L
How to find a bug?
Complex program
Simple
condition
Simple
condition
Simple
condition
Quicksort
def qsort (sequence):
s = sequence[:] # s is a copy of sequence
if s == []:
result = s # end of recursion
else:
x = s[0] # take first element
del s[0]
s1 = [] # split remaining list
s2 = []
for i in s:
if i <= x:
s1.append(i)
else:
s2.append(i)
result = qsort(s1) + [x] + qsort(s2) # recursive calls
return result
Quicksort checking postconditions
def qsort (sequence):
s = sequence[:] # s is a copy of sequence
if s == []:
result = s # end of recursion
else:
x = s[0] # take first element
del s[0]
s1 = [] # split remaining list
s2 = []
for i in s:
if i <= x:
s1.append(i)
else:
s2.append(i)
result = qsort(s1) + [x] + qsort(s2) # recursive calls
assert len(result) == len (sequence)
assert min(sequence) == min(sequence)
return result
Hands-on Exercise 1
Part 2
Python Projects in the
Classroom –
Raspberry Pi Projects
Agile Classroom Projects Extreme Programming (Kent Beck)
Invent a project metaphor
write stories
Start with an architectural spike solution
Implement stories in short iterations
User can choose a font
Stories
User can insert phrases ( “Dear friend!”)
The Letter Fairy
A text editor that helps young children writing
letters in a foreign language.
Start with an Architectural Spike
from tkinter import *
class Editor:
def __init__ (self):
# widgets
self.window = Tk()
self.window.title("Text Editor 1")
self.text = Text(master=self.window)
self.text.pack()
# window
self.window.mainloop()
Editor()
9 lines of code
At the End of the First Iteration ----------------------------------------------------
# file name: editor3.pyw
# A simple text editor with menu for open and save
# Michael Weigend 2009
#----------------------------------------------------
from tkinter import *
class Editor:
def __init__ (self):
# Textfeld
self.window = Tk()
self.text= Text(master=self.window,
wrap=WORD, font=('Arial', 10))
self.text.pack()
# Menu Bar
self.menuBar=Menu(master=self.window)
self.window.config(menu=self.menuBar)
# file menu
self.fileMenu=Menu(self.menuBar)
self.fileMenu.add_command(label="Open",
command = self.load)
self.fileMenu.add_command(label="Save as",
command = self.save)
self.fileMenu.add_separator()
self.fileMenu.add_command(label='Quit',
command=self.quit)
self.menuBar.add_cascade(label="file",
menu=self.fileMenu)
self.window.mainloop()
# methods
def load (self):
self.file = filedialog.askopenfile()
self.text.delete(1.0, END) # delete all text in text area
if self.file:
self.text.insert(1.0, self.file.read()) # read text from file and insert it
def save (self):
self.file = filedialog.asksaveasfile()
if self.file:
self.file.write(self.text.get(1.0, END) )
self.file.close()
def quit(self):
if messagebox.askyesno('Finish',
'Do you really want to quit?'):
self.window.destroy()
Editor()
approx. 50 lines of code
Programming the Raspberry Pi
Computer = Black Box
41
Michael Weigend: Der Raspberry Pi im naturwissenschaftlichen Unterricht cc by-nc-sa 2014 42
Open The Black Box
Open the Blackbox
43
1. Processor
2. GPIO
3. USB
4. RJ45
5. AnalogAudio-/ Videoa
Output
6. HDMI
7. Micro-USB (power supply)
8. Mikro-SD card
9. Bluetooth and WLAN
10.CSI (camera)
Open the Blackbox
44
• Many operating systems
• play with administration
• software installation
• server configuration
Construct it Yourself
Michael Weigend: Der Raspberry Pi
in der Schule Düsseldorf 2016
45
LED-Matrix made of
1st quality junk
Clock with LCD display
Mobile Devices
46
Seeing with ultra sonic
Touchscreen
Astro Pi with Sense-HAT on th ISS
Kiosk and Dashboard
47
Mail From All Over The World
48
Project: Collecting and Processing
Temperature Data
analog
digital
Direct-to-Digital
Sensor
physical
phenomenon
Computer
data package
Information
temperature-
sensitive oscillator
DS1820
1-Wire-Bus
ID
temperature
(-55 to +125 °C)
temperature crc
Hardware Configuration
51
GPIO
Wiring Diagram
R=4,7kΩ …
52
Reading data with modprobe
sudo modprobe wire
sudo modprobe w1-gpio
sudo modprobe w1-therm
Temperature
information
ID of the sensor
28 = DS18B20
53
Temperature Data Logger os.system("modprobe wire")
os.system("modprobe w1-gpio")
os.system("modprobe w1-therm")
for d in os.listdir("/sys/bus/w1/devices"):
if d.startswith("10") or d.startswith("28"):
deviceFile = "/sys/bus/w1/devices/" + d + "/w1_slave"
def readTemp():
ok = False
while not ok:
f = open(deviceFile, "r")
firstLine, secondLine = f.readlines()
f.close()
if firstLine.find("YES") != -1:
ok = True
tempString = secondLine.split("=")[1]
return int(tempString)/1000
while True:
print(readTemp())
time.sleep(1)
Output: 22.937
22.312
22.312
54
Starting point for new ideas
Photo
: cc b
y 2
.0 A
ngelo
de S
antis
2013
, wik
imedia
com
mons
Story: Vertical temperature
profile of a lake
Photo
: cc b
y 2
.0 D
wig
ht B
urd
ette
2012,
wik
imedia
com
mons
Story: The dynamics of
temperature in a room
while airing.
55
Story: Recognizing fluids
(like water, ethanol,
proanone)by observing
temperature changes
56
Story: Observing the temperature
durimng a chemical reaction using
an array of temperature sensors.
(assignment paper Georgij
Loptev, 2014)
Starting point for new ideas
Mobile Devices
57
Story: Find the
coldest spot
Temperature Server
58
Story: Temperature in a
fermentation bottle is
observed and published.
HAT Technology
Recommended