python workshop ch4hs dec 2012 see website: ecs.vuw.ac.nz/main/pythonforschools
TRANSCRIPT
Python Workshop
CH4HS Dec 2012
see website: ecs.vuw.ac.nz/Main/PythonForSchools
© Peter Andreae
People
Tutors:
• Peter Andreae, VUW
• Robert Sheehan, U Auckland
• Heidi Newton, VUW (prev Canty)
• Tim Bell U Canterbury
• Edward Dalley U Canterbury
Teachers:Sarah Hailes, Daniel Greenwood, Chris Dillon, Paul Curry, Irena Krchnavy, Alistair West, Giuseppe Cugilari, Trish McKay, Rowena Bullock, Alison Chester, Tim Curran, Steve Rodkiss, Karen Clark, Paul Akula
2
© Peter Andreae
Where are you?
No programming experience at all (not even scratch)
Have done some Scratch/Alice, but no text languages
Have done a little bit of programming in another text-based language
Have done quite a bit of programmingbut not in Python
3
© Peter Andreae
The Programming Standards:• Level 1
• Variables and values• Conditionals (if..else), loops (while… for…)• Input and output
• What's added at level 2?• Program decomposed into modules (functions)• Functions with parameters (rules out Scratch)• Lists/Arrays/Sequences
• What's added at level 3?• Simple GUI: event-based input • Simple object oriented: defining a class of objects• Staged development• Must be a text based language• Design and implementation integrated
© Peter Andreae
Text-based vs Drag&Drop
Text-based Languages ( eg Python, Java, ….)
vs
Drag and Drop Languages (eg Scratch, Alice)
• Just the same
• Text-based is harder for learners because• There is much more to remember (no menu of options)• More detail to get right (or wrong)
© Peter Andreae
Python vs other textual languages:• Plus
• simple syntax rules (fewer details to get wrong)• untyped variables and parameters (less syntax to get wrong)• interpreter (allows testing and experimenting)• lots of libraries (including turtle)
• Minus• untyped variables and parameters (computer can't help
debug as much)• interpreter (computer doesn't help debug as much)• some inconsistencies, especially with lists.• non-standard structures as well as common ones.
© Peter Andreae
Python syntax.
(If you’ve used other text-based languages:)
• Don't have to specify types of variables
• Indentation is meaningful - specifies nesting
• Very little required punctuation• if, while, for, def use a :• " … " or ' … ' or ' ' ' ….. ' ' ' for strings
• [ ] for lists
• ( ) for function arguments/parameters and for "tuples"
• { } for dictionaries (mappings)
© Peter Andreae
Invitation: input/output,
print(“Hi”)
name = input(“What’s your name: ")
print(“Hello ", name)
print(“You’re invited to my party on Friday“)
• print(string , ...) action that does something
• input(promptString ) action that also returns a value
• variable = value store a value in a variable
• using the variable use the value that was stored
• sequence of actions
9
© Peter Andreae
Let’s do it:• Start up the Wing-101 IDE
• Type the program in main window
• Click the “bug” button to run the program.
10
© Peter Andreae
To Do• Temperature converter (F -> C)
• ask for temperature in fahrenheit and store in variable• compute and print out temperature in celcius
• You will need to calculate values• +, -, *, / work as normal
• You need to be able to convert strings into numbers• float(string ) number (with fractional part) • int(val ) number (with no fractional part)
© Peter Andreae
Guess my name: if / conditionals
guess = input(“Can you guess my name? ")
if guess == "pam" :
print("Yes, you got it right!")
print("How did you guess?")
else :
print("no, I’m not ", guess, "My name is pam")
• if condition : actionselse : other actions
• indentation is important• == tests if two values are the same
• To Do – try it out. Modify to guess my height
12
© Peter Andreae
Guess the word: while / iteration• (This is a silly program, but it illustrates some python)
print(“Lets play Guess the Word, ok?”)
word = input(“What is your guess: ")
while word != "pancake" :
print("no, ", word, " is not the right answer")
word = input("guess again: ")
print("Yes, you guessed the magic word!")
• while condition : Loop repeatedly, testing each time actions
• != test for inequality
• To Do: modify to guess the number. Say if their guess is too low or too high
13
© Peter Andreae
Multiplication: from random import *
base = 5other = randomint(1,10)ans = input("what is " + str(base)+ " x " + str(other) + " : ")ans = int(ans)if ans == base * other : print(" yes, that’s right! ")else : print ("no, that’s not the right answer “) print (base, " X ", other, " is “, (base * other) )
• random numbers, need to import “library”• adding strings, converting numbers to strings• doing arithmetic
To Do: change it to test addition or subtraction
14
© Peter Andreae
Multiplication: repeating n times
from random import *
base = 5for i in range(10) :
other = randomint(1,10)ans = int(input("what is " + str(base)+ " x " + str(other) + " : "))if ans == base * other : print(" yes, that’s right! ")else : print ("no, that’s not the right answer “) print (base, " x ", other, " is “, (base * other) )
print(" Good bye “)
• For loop for repeating fixed number of times• range(num) range(from, to) list of numbers
To Do: change it to test addition or subtraction
15
© Peter Andreae
To Do• Times table printer
• asks for number and prints out 1 x up to 10 x
choose number for table: 81 x 8 = 82 x 8 = 163 x 8 = 244 x 8 = 325 x 8 = 406 x 8 = 487 x 8 = 568 x 8 = 649 x 8 = 7210 x 8 = 80
© Peter Andreae
Turtle Graphics• Lets you write programs with simple graphical
patterns with minimal maths
• Can also do standard 2D graphics, but requires coordinates – some students find it tricky
Turtle graphics programsimport turtle
make a screen to move around on
make a Turtle (or more than one!)
tell the turtle to move around and draw stuff.
17
© Peter Andreae
Turtle Graphicsimport turtle
window = turtle.Screen()pet = turtle.Turtle()pet.pencolor(“red”)pet.forward(50)pet.left(120)pet.forward(50)pet.left(120)pet.forward(50)pet.left(120)
• Making new objects• calling functions on objects, and passing arguments
To Do Make a turtle that draws a house.
Draw star shape; draw letter shapes
18
import turtle
window = turtle.Screen()
sam = turtle.Turtle()
sam.pencolor(“blue”)
for i in range(3) :
sam.forward(50)
sam.left(120)
© Peter Andreae
Defining functions• Breaking a program up into modules
• easier to manage• easier to understand• easier to reuse.
• Each module is a function• has a name• has parameters – specifying the information it needs
def draw_triangle (turtle, size) :for i in range(3) :
turtle.forward(size)turtle.left(120)
• when you call the function, you provide values for each parameter
draw_triangle(sam, 80)
19
© Peter Andreae
To Do• Define functions for drawing stars and moons
• Write a program that uses those functions to draw a sky.
20
© Peter Andreae
Lists• Lists are a collection of items in order
• can act on individual elements, indexed by position (0,1,2….) • Like arrays, but better• can be extended or shortened• can be acted on as a whole
• eg, can be stored in variable, passed to function, printed out, …
• Written with square brackets, comma separated, • eg names = ["peter", "james", "justine"]
ages = [ ]
• Access using index inside [ ]: print(names[ 2 ] )
names[ i ] = “jim"
• Append to end:• names.append("jillian")
© Peter Andreae
Using a listdef main () :
allowed = ["peter", "james", "justine"]
name = input(“Please enter name ")
for i in range(len(allowed)) :
if name == allowed[i] :print("Yes, you may enter")
else :print(“Sorry, you are not allowed”)
main()
22
© Peter Andreae
Using a listdef main2 () :
allowed = ["peter", "james", "justine"]name = input(“Please enter name ") for n in allowed :
if name == n :print("Yes, you may enter")
else :print(“Sorry, you are not allowed”)
def main3 () :allowed = ["peter", "james", "justine"]name = input(“Please enter name ") if name in allowed :
print("Yes, you may enter")else :
print(“Sorry, you are not allowed”)
• New for loop construct• New condition construct
23
© Peter Andreae
Input the allowed listdef readAllowedNames () : names = [ ] print("Please enter the allowed names. End with 'done'") while True : name = input("Name:") if name == "done" : break; names.append(name) return names
def main () : allowed = readAllowedNames() while True : name = input("Please enter name ") if name in allowed : print("Yes, you may enter") else : print("Sorry, you are not allowed")
main()
24
© Peter Andreae
To Do:• stats:
• read a line of numbers into a list then find min, max, average• list all the numbers less than the average.
• wordList• read a list of words from user• print out shortest and longest word ( len(“word”) 4 )• any word starting with a vowel ( “word”[0] “w” )
• scrabble arranger:• read a list of letters• repeatedly :
• ask user for index of a letter to move to the left• swap the letter with its neighbour• print out the list