lists - science club
TRANSCRIPT
First Python examples
print “hello”
> 42
> hello
x = 42print x
x = input()print x
< “salut”> salut
try also * / x = 41+1print x
# This is a comment
3 * “Cha”
Official Python page: http://www.python.org/Documentation: http://www.python.org/doc/Tkinter tutorial: http://www.python.org/doc/lifepreserver/
Flow control
if/elif/elsefor/elsewhile/elsebreak; continue
def return
globaldelexecimport <name>from <name> import <item>
If/elif/else
n = input("Weivill Geld hues de? ")if n < 6: print "Bleiw doheem"elif n< 10:
print “Science Club"else: print "Science Club oder Kino"
n = 3if n < 16: print "Smaller than 16"
Smaller than 16
ex. Password
Comperator operators
operator function
< less than<= less than or equal to> greater than>= greater than or equal to== equal!= not equal<> another way to say not equal
# exampleif x == 2:
print “x is 2”else:
print “x not 2”
For/else
text = “hello folks”for x in text:
print x
for x in range(1:10):print “>”+str(x)+”<”
list = [“one”,”two”,”tree”]for x in list:
print x
For/else
text = “hello folks”for x in text:
print x
even=[2,4,6,8,10]for x in even:
if x==3:print "found"break # do not use else clause
else:print "3 is not in the list"
# This could also be done with:if even.count(3) > 0:
print “found”else
print “3 is not in the list”
even=[2,4,6]for x in even:
print xelse:
print "done"
ex. Enter number: 51 3 5
Exec (execute code)
exec(“print 'hello'”)
i = 4s=”print 'hello”+str(i)+” ' ”exec(s)
hello
hello4
import mathfrom math import cosfrom math import *
math.cos(1)cos(1)cos(1)
Only cos All from math
Import (use library)
def doubleAll(what):print what*3
doubleAll(3)doubleAll(“cha”)
Functions
Create a reusable function
Explain python what thefunction should do
A 'Tab' at the start if the line tells python that this line still belongs to the function
def shallIBuy(costs):print “Chocolate costs ”+str(costs)+”.”if costs > 5:
print “I don't have enough money to buy”else:
print “I'll buy the chocolate”shallIBuy(3)shallIBuy(8)
Functions may be usedmore than once!
Numbers: 1,2,3Strings: "hello folks" 'hello'Lists [2,3,4] [2,3,[3,4]] ['one','two','tree']Dictionaries {'prenom':'Andre', 'nom':'Stemper'}Tuples: (1,2,3) (1,2)files: text=open('test.txt','r').read()
Types
text=”blah” type(text) type(text) is str type(text) is list
new string<type 'str'>truefalse
Numbers
3*4 12
print "3 * 4 is", 3 * 4
Operation Symbol ExampleExponentiation ** 5 ** 2 == 25Multiplication * 2 * 3 == 6Division / 14 / 3 == 4Remainder % 14 % 3 == 2Addition + 1 + 2 == 3Subtraction 4 3 == 1
3 * 4 is 12
ex. write programthat outputs a sequence like this:.....#.....#.....#.....#
Numbers
1/2 == 0 ; 1.0/2.0 == 0.5 !!!
(1+2j)/(1+1j) == (1.5+0.5j)
1. parentheses ()2. exponents **3. multiplication *, division / and remainder %4. addition + and subtraction
Complex numbers
a=1.5+0.5ja.real a.imag
a.real == 1.5 a.imag == 0.5
Mathematiques
from math import *sin(pi/2)cos(pi)
1.01.0
import math math.sin(pi/2)math.cos(pi)
dir(math)
1.01.0
returns list of functions
Strings
“Hello folks!”'Hello folks!''''Hello folks'''
3 * “Cha”
“Hello ” + “Folks” + “!”
i = 4print “The number is” + str(i) The number is 4
String Operators
text = “hello folks”text[0] text[1]text[2:6] text[1]len(text)len(text[1:3])text.replace(“folks”,”people”)text.split()text.upper()
dir(text)
Hello fs112Hello people['Hello', 'people']HELLO PEOPLE
List of functions
ex. Anagram
Lists
list=[1,2,”hello”]list[0] list[1]list[2] list[1:3]list[1]len(list)
12Hello[2, ”Hello”]“Hello”3
list=[1,[2,3],4]list[0] list[1]list[2] list[1][1]
1[2,3]43
Lists
list=[1,2,”hello”]dir(list)list.append(“go”)list.remove(“hello”)del list[1]list.extend( [1,4])list.append([3,6])list.count(1) # number of 1's in listlist.reverse()list.sort()list.__doc__list.count.__doc__
list of functions[1,2,”hello”,”go”][1,2,”go”][1,”go”][1,”go”,1,4][1,”go”,1,4,[3,6]]2 [[3,6],4,1,”go”,1]
Documentationex. Talker
import randomr=random.random()
Dictionaries
d={“prename”:”Andre”, 20:”Stroumpf”}dir(d)d[“prename”]d[20]d[“test”]=”works”
del d[“hello”]
d.keys()d.values()len(d)
list of functionsAndreStroumpf
{“test”:”works”, “prename”:”Andre”, 20:”Stroumpf”}{“prename”:”Andre”, 20:”Stroumpf”}
KeysValues
Dictionaries
lista = [“a”,”b”,”c”]listb = [“AAA”,”BBB”,”CCC”]d = dict(zip(lista,listb))
d[“b”]
{“a”:”AAA”,“b”:”BBB”,“c”:”CCC”}
“BBB”
ex. Phonebook
Files
f = file(“test.txt”,”w”)f.write(“hello”)f.close()
open file for writingwrite “hello” to fileclose the file
f = file(“test.txt”,”r”)s= f.read()print sf.close()
open file for readingread from filewrite to screenclose the file
s= f.readlines()f.writelines([“hello”,”world”])dir(f) ex. autotext
ButtonRadiobuttonCheckbuttonMenubuttonMenu
Tkinter OverviewChoices:
LabelMessageEntryListboxText
Textentry / Display
ToplevelFrameCanvas
Windows / Frames:
#!/usr/bin/pythonfrom Tkinter import *def hit():
print "hit"
win=Tk()b=Button(win,text="text",command=hit)b.pack()win.mainloop()
Tkinter Button
Button(text="Button,command=sys.exit) # exits program on click
b = Button(self, fg = "red", bg = "blue")fred["fg"] = "green"fred.config(fg = "yellow", bg = "red”)
Tkinter Options
Options:bg Backgroundcolorbd Border widthheight Heightwidth Widthunderline Underline fonttextvariable Variable that holds the displayed textrelief RAISED, FLAT, SUNKEN, ...
Tree methods to set Widget options:
ex. Button changes color if pressed
#!/usr/bin/pythonfrom Tkinter import *win=Tk()l = Label(win, text="Hello, world!")l.pack()win.mainloop()
Tkinter Label
ex. Label changes text if Button has been pressed
from Tkinter import *win=Tk()var1=StringVar()c1=Checkbutton(text="Checkbutton",variable=var1, \ onvalue="Selected",offvalue="Not selected")c1.pack()Label(win, textvar=var1).pack()win.mainloop()
Tkinter Checkbutton
More than one button may beselected at the same time.
from Tkinter import *win=Tk()var1=StringVar()c1=Radiobutton(text="Radio1button",variable=var1,value=1)c2=Radiobutton(text="Radio1button",variable=var1,value=2)c1.pack()c2.pack()Label(win, textvar=var1).pack()win.mainloop()
Tkinter Radiobutton
Only one button may beselected at the same time.
from Tkinter import *def hit():
print “hit”
win=Tk()win.bind('<q>',hit)win.mainloop()
Tkinter Bind Key
If the key <q> is pressed, the function “hit()” is called.This can also be used to bind special keys like <Enter> or even mouse movement to an function.
<Enter> Enter widget<Leave> Leave widget<Button1> Mouse button 1 (try 13)<DoubleButton1> Double click on button 1<B1Motion> Button1 pressed and
mouse move
<Return> The <Enter> key<Key> (replace key with the KEY)<KeyRelease> Key has been released
from Tkinter import *def move(event):
print "Mouse X="+str(event.x)+" Y="+str(event.y)win=Tk()win.bind('<Motion>',move)win.mainloop()
Tkinter Bind Mouse
<Enter> Enter widget<Leave> Leave widget<Button1> Mouse button 1 (try 13)<DoubleButton1> Double click on button 1<B1Motion> Button1 pressed and
mouse move
<Return> The <Enter> key<Key> (replace key with the KEY)<KeyRelease> Key has been released
from Tkinter import *win = Tk(); can = Canvas(win, bg='white', height=200, width=200) can.pack()ball = can.create_oval(100, 100, 150, 150, width=2, fill='red')line = can.create_line(20, 25, 110, 110, width=2, fill="blue", dash=(4, 8))rect = can.create_rectangle(50, 25, 150, 75, fill="green")win.mainloop()
Tkinter Canvas
can.coords(ball, 10, 10, 30, 30) # Change coordinates of widget
from Tkinter import *# win = Tk(); # Create new windowwin.title("Pong") # Name it "Pong"win.mainloop() # redraw window, watch for keys...
The window
pongframe.py
from Tkinter import *# gwidth = 800; gheight = 400 # Size of the playgroundballsize = 20; # Ball size# x1, y1 = 0,0 win = Tk(); win.title("Pong")can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')win.mainloop()
The window
Canvas options:bg Background colorbd Border widthheight Heightwidth Width
Oval options:bg Background colorfill Fill coloroutline Color of the linewidth width of the line
...def move(): global x1
x1 = x1 + 1can.coords(oval1, x1, 0, x1+30, 30)win.after(50, move)
x1=0; y1=0win = Tk()can = Canvas(win, bg='white', height=400, width=800) can.pack()
oval1 = can.create_oval(x1, y1 ,x1+30,y1+30, width=2, \ fill='white')move()win.mainloop()
Test: Moving the circle
Start position of the circleStart position of the circle
Create the circle at positon 0Create the circle at positon 0Animate the circle
Define a function
Add 1 to x at every step
Next step in 50 ms
Change position of oval (leave size)
Animate !!!
#!/usr/bin/pythonfrom Tkinter import *def move(): global x1, y1
x1 = x1 + 1y1 = y1 + 1can.coords(oval1, x1, y1, x1+30, y1+30)win.after(50, move)
x1=0; y1=0win = Tk()can = Canvas(win, bg='white', height=400, width=800) can.pack()
oval1 = can.create_oval(x1, y1, x+30, y1+30, width=2, \fill='red')
move()win.mainloop()
Test: Moving in two dimensions
Start position of the circleStart position of the circle
Initialize y
Create at position (x, y)
Add 1 to y at every step
Change position of oval (leave size)
Change speed?Change direction?
#!/usr/bin/pythonfrom Tkinter import *def move(): global x1, y1, dx, dy
x1 = x1 + dxy1 = y1 + dycan.coords(oval1, x1, y1, x1+30, y1+30)win.after(50, move)
x1=0; y1=0dx=10; dy = 12win = Tk()can = Canvas(win, bg='white', height=400, width=800) can.pack()oval1 = can.create_oval(x1, y1, x1+30, y1+30, width=2, fill='red')move()win.mainloop()
Test: Changing speed / direction
Speed in both directions
Add dx instead of “1”
#!/usr/bin/pythonfrom Tkinter import *def move(): global x1, y1, dx, dy
x1 = x1 + dxy1 = y1 + dyif x1 >770:
dx = dx if y1 >370:
dy = dy if x1 <0:
dx = dx if y1 <0:
dy = dy can.coords(oval1, x1, y1, x1+30, y1+30)win.after(50, move)
Test: Bounce at boundry
770 = width of field – width of the ball This way the ball stays in the field.
370 = height of field – height of the ball
Rest of the program has not been changed ...
30 = width of the ball
30 =height of the ball
from Tkinter import *# def move(): global x1, y1, dx, dy, gwidth, gheight, ballsize x1, y1 = x1 +dx, (y1+dy) if y1 > (gheightballsize): y1, dy = gheightballsize, dy if y1 < 0: y1, dy= 0, dy if x1 > (gwidthballsize):
x1,dx = gwidthballsize, dx if x1 < 0:
x1,dx = 0 , dxcan.coords(oval1, x1, y1, x1+ballsize, y1+ballsize)
win.after(50, move) dx, dy = 15, 15 # Directions of the ballgwidth = 800; gheight = 400 # Size of the playgroundballsize = 20; # Ball sizex1, y1 = 0,0 win = Tk(); win.title("Pong")can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')move() # draw next sequence win.mainloop()
All together: Moving the ball
pongnomidline.py
# change ball position
# calculate the next ball position
# call the function move in 50 milliseconds again
...oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
move() # draw next sequence win.mainloop()
Adding the midline
pongnorackets.py
Line options:fill Fill coloroutline Color of the linewidth width of the linedash dashing of the line
...# dx, dy = 15, 15 # Start directions of the ballgwidth = 800; gheight = 400 # Size of the playgroundballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket size# x1, y1 = rfb, (gheightballsize)/2rpos=lpos=(gheightrs)/2win = Tk(); # Create new windowwin.title("Pong") # Name it "Pong"can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)# Create the ball oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')# Create mid lineline = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")move() # draw next sequence win.mainloop()
Adding the rackets1/2
pongnocontrol.py
def move(): global x1, y1, dx, dy, gwidth, gheight, ballsize, rfb global rpos, lpos, rs x1, y1 = x1 +dx, (y1+dy) if y1 > (gheightballsize): y1, dy = gheightballsize, dy if y1 < 0: y1, dy= 0, dy if x1 > (gwidthballsize):
x1,dx = gwidthballsize, dx if x1 < 0:
x1,dx = 0 , dx can.coords(oval1, x1, y1, x1+ballsize, y1+ballsize) # Change the positon of the two rackets can.coords(rracket, gwidthrfb, rpos, gwidthrfb, rpos+rs) can.coords(lracket, rfb, lpos, rfb, lpos+rs) win.after(50, move)
Adding the rackets 2/2
pongnocontrol.py
...dx, dy = 15, 15 # Start directions of the ballgwidth = 800; gheight = 400 # Size of the playgroundballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket sizerspeed = 20 # Speed of the racket # x1, y1 = rfb, (gheightballsize)/2rpos=lpos=(gheightrs)/2win = Tk(); win.title("Pong")can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
# Use the following keys to move the racketwin.bind('q', lup)win.bind('p', ldown)win.bind('<B1Motion>', rmove)
move() # draw next sequence win.mainloop() # redraw window, watch for keys...
Adding Control1/3
pongnostart.py
# def lup(event): global lpos, rspeed if lpos > rspeed:
lpos=lposrspeed def ldown(event): global lpos, gheight, rspeed, rs if lpos < (gheightrsrspeed):
lpos=lpos+rspeed
def rmove(event): global rpos, gheight, rs ypos = event.y if ypos > 0 and ypos < (gheightrs): # if in range
rpos = ypos#
Adding Control2/3
pongnostart.py
def move(): global x1, y1, dx, dy, gwidth, gheight, ballsize, rfb global rpos, lpos, rs x1, y1 = x1 +dx, (y1+dy) if y1 > (gheightballsize): y1, dy = gheightballsize, dy if y1 < 0: y1, dy= 0, dy
# if the ball passed the right border of the field give it to the left player if x1 > (gwidthballsize): x1, y1 = rfb, (gheight/2) # if the ball passed the left border give it to the right player if x1 < 0:
x1, y1 = gwidthrfb, (gheight/2) # test if the ball hits the left racket let it bounce back if x1 <= rfb:
if y1>lpos and y1 < (lpos+rs): x1, dx = rfb+5, dx
# test if the ball hits the right racket let it bounce back if x1 >= (gwidthrfbballsize): if y1 >= rpos and y1 <= (rpos+rs): x1, dx = (gwidthrfbballsize5), dx ...
Adding Control 3/3
pongnostart.py
def move(): global x1, y1, dx, dy, playing, gwidth, gheight, ballsize, rfb global nextplayer, rpos, lpos, rs # position the ball on the playground if playing > 0: x1, y1 = x1 +dx, (y1+dy) else: # follow racket if nextplayer==0: # if the next player is the right player give him the ball x1,y1,dx = rfb+10, lpos+(rsballsize)/2, abs(dx)
else: # otherwise give the left player the ball x1,y1,dx = gwidthrfb10, rpos+(rsballsize)/2,abs(dx) if y1 > (gheightballsize): y1, dy = gheightballsize, dy if y1 < 0: y1, dy= 0, dy if x1 > (gwidthballsize): x1, y1 = rfb, (gheight/2) # give right player the ball
nextplayer = 0playing = 0 # stop the game
if x1 < 0:x1, y1 = gwidthrfb, (gheight/2) # give left player the ballnextplayer = 1playing = 0 # stop the game
...
Adding Start 1/3
pongnoscore.py
...x1, y1 = rfb, (gheightballsize)/2rpos=lpos=(gheightrs)/2nextplayer = 0 # next player: 0=right, 1=leftplaying = 0 # Do not play when starting the programwin = Tk(); win.title("Pong")can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
win.bind('q', lup)win.bind('p', ldown)win.bind('<B1Motion>', rmove)win.bind('<space>', startit) # start game by hitting space
move() # draw next sequence win.mainloop() # redraw window, watch for keys...
Adding Start 2/3
pongnoscore.py
def move(): global x1, y1, dx, dy, playing, gwidth, gheight, ballsize, rfb global lplayer, rplayer, nextplayer, counter, rpos, lpos, rs if playing > 0: x1, y1 = x1 +dx, (y1+dy) else: if nextplayer==0: x1,y1,dx = rfb+10, lpos+(rsballsize)/2, abs(dx)
else: x1,y1,dx = gwidthrfb10, rpos+(rsballsize)/2,abs(dx) if y1 > (gheightballsize): y1, dy = gheightballsize, dy if y1 < 0: y1, dy= 0, dy
...
Pong 1/3
pong.py
... # give the left player a point if x1 > (gwidthballsize):
lplayer=lplayer+1 # increment score for left player x1, y1 = rfb, (gheight/2) # give right player the ball
nextplayer = 0playing = 0 # stop the game
if x1 < 0:rplayer=rplayer+1 # increment score for right player
x1, y1 = gwidthrfb, (gheight/2) # give left player the ballnextplayer = 1playing = 0 # stop the game
if x1 <= rfb: if y1>lpos and y1 < (lpos+rs):
x1, dx = rfb+5, dx if x1 >= (gwidthrfbballsize): if y1 >= rpos and y1 <= (rpos+rs): x1, dx = (gwidthrfbballsize5), dx # draw ball position can.coords(oval1, x1, y1, x1+ballsize, y1+ballsize) # draw current score score = str(lplayer) + ":" + str(rplayer) can.itemconfigure(counter, text=score)...
Pong2/3
pong.py
...# dx, dy = 15, 15 # Start directions of the ballgwidth = 800; gheight = 400 # Size of the playgroundballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket sizerspeed = 20 # Speed of the racket lplayer=rplayer=0 # Start with no points# x1, y1 = rfb, (gheightballsize)/2rpos=lpos=(gheightrs)/2nextplayer = 0 # next player: 0=right, 1=leftplaying = 0 win = Tk(); win.title("Pong")can = Canvas(win, bg='black',height=gheight, width=gwidth) can.pack(side=LEFT)oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")# Create the score textfont=('courier', 20)counter=can.create_text(gwidth/2, 20, text='0:0', font=font, fill="white")win.bind('q', lup)win.bind('p', ldown)...
Pong 3/3
pong.py