Sie sind auf Seite 1von 30

Python

Hélène Martin
Puget Sound CSTA
December 11th, 2010

Special thanks to Marty Stepp for some formatting and content


Hélène Martin

Bachelor’s in CS from UW
Career and Technical Ed through South Seattle
Teach at comprehensive public high school
Five periods of computer science
- 2x Exploring Computer Science
- 2x AP Computer Science
- 1x AP Computer Science (Experienced)

http://garfieldcs.com
Why Teach Python?

Light-weight syntax
Multi-paradigm (procedural, OO, functional)
Lots of great libraries
- turtle graphics
- pygame
- scipy
- myro (workshop last spring)

Interpreted
Permissive
Used increasingly in college courses, web applications
Why Not Teach Python?

Permissive
Dynamically typed (values have types, but not
variables)
Too many ways to skin a single cat!
Not used much in corporate world
- Though YouTube, Google, Yahoo!, NASA make some use of it
- Primarily for internal tools (think Perl)
Creative Computing

Semester-long high school course


Only pre-requisite is algebra 1
Topic progression:
- Basic syntax with turtle graphics (iteration, variables,
conditionals)
- Functions (abstraction)
- Compound data: strings and lists
- Programming robots
- Object-oriented basics
- Games with pyGame
Getting Python

Free at http://python.org
Generally pre-installed on OS X or Linux
Includes IDLE, a basic IDE
Interacting With IDLE

Programs saved with .py extensions


Commands interpreted straight in shell
Students can get confused about the two!!
Procedural Turtle Graphics

Long tradition started by Logo


Drawing shapes gives instant feedback
Students get used to syntax, algorithms

Note: students often save


files as turtle.py - remind
them not to do that!
Available functions

http://docs.python.org/library/turtle.html
- forward() | fd() - write()
- backward() | bk() | back() - showturtle() | st()
- right() | rt() - hideturtle() | ht()
- left() | lt() - shape()
- goto() | setpos() | setposition() - register_shape() | addshape()
- stamp()
- speed()
- pendown() | pd() | down()
- penup() | pu() | up()
- pensize() | width()
- color()
- begin_fill()
- end_fill()
- clear()
Geometry exercises

Reasoning about repetition


Breaking down a problem into steps
http://neoparaiso.com/logo/ejercicios-de-
geometria.html
Iteration

Definite loop
for loop structure
1 for i in range(<times>):
2 <statements>
3 <statements>
4 print("Hi") # not repeated

Indefinite loop
while loop strcture
1 while(<condition>):
2 <statements>
3 <statements>
4 print("Hi") # not repeated
White Space

Indentation indicates blocks


Super offensive at first glance, but one gets over it
- it’s NOT like shell scripting!

Colon indicates containers, everything indented


under is governed by that container

Indentation matters
1 for i in range(3):
2 print("Hello") # repeated
3 print(25) # repeated
4 print("Hi") # not repeated
Functions

Definition
The def keyword is used for defining functions
1 def hello(<param1>, <param2>...):
2 print("Hello, world!")
3
4 hello()
5 hello()

Calling
- Students often forget to use parentheses when calling
Print Function

Simple! (no System.out.yuck)


Can be called with parameters of different types
Concatenation shows ugliness of dynamic types

Print can display different types


1 print("Hello, world!")
2 print()
3 print(25)
4 print("You have " + str(dollars) + " dollars")
Python Operations

Arithmetic:
- ** (exponent)
- * (multiplication) / (division) % (modulus)
- + (addition) - (subtraction)

Boolean
- == != < <= > >=
- not
- and or

Common Types
- int, float, bool, str
Conditionals

Conditional structure
1 if(<condition>):
2 <statements>
3 elif(<condition>):
4 <statements>
5 else:
6 <statements>
User input

User input
1 >>> name = raw_input("Your name?")
2 Your name? Bonnie
3
4 >>> name
5 'Bonnie'
6

User input - numbers


1 >>> age = int(raw_input("Your age?"))
2 Your age? 15
3
4 >>> age
5 15
6
External Libraries

Import modules to get access to more functions

Using random numbers


1 from random import *
2
3 die1 = randint(1, 6)
4 die2 = randint(1, 6)
Your turn

Write a guessing game


I'm thinking of a number between 1 and 100.
Your guess? 50
Too big!
Your guess? 25
Too small!
Your guess? 37
Too big!
Your guess? 30
Too small!
Your guess? 34
Too big!
Your guess? 32
Too small!
Your guess? 33
You got it in 7 guesses
Strings

Characters have indexes:


index 0 1 2 3 4 5 6 7
or -8 -7 -6 -5 -4 -3 -2 -1
character P . D i d d y

Accessing string character(s)


1 >>> name = "P. Diddy"
2 >>> name[0]
3 'P'
4 >>> name[7]
5 'y'
>>> name[-1]
6 'y'
7 >>> name[3:6]
8 'Did'
9 >>> name[3:]
10 'Diddy'
11 >>> name[:-2]
12 'P. Did'
Iterating over strings

Can access length using len() function


Can use for loop to examine each character

Looping over a string


1 >>> for c in "PSCSTA":
2 print c
3
4
5 P
6 S
7 CS
8 T
9 A
10
String methods
str.capitalize()
str.endswith(suffix)
str.find(sub)
str.isdigit()
str.join(iterable)
str.lower()
str.replace(old, new)
str.split([sep])
str.startswith(prefix)
str.strip()
str.title()
str.upper()

http://docs.python.org/library/stdtypes.html#string-methods
Lists

Lists
1 >>> nums = [2, 4, 6, 8]
2 >>> for num in nums:
3 print num
4 2
5 4
6 6
7 8
8 >>> nums.reverse()
9 >>> nums
10 [8, 6, 4, 2]
11 >>> nums.append(10)
12 >>> nums
13 [8, 6, 4, 2, 10]
14 >>> nums.sort()
15 >>> nums
16
17 [2, 4, 6, 8, 10]
18 >>> nums[len(nums) - 2]
19 8
Your turn

Write a pig latin program


Phrase to translate? What a lovely day it is
hatWAY AAY ovelyLAY ayDAY tIAY sIAY

Simple: move the first letter to the back and add


AY. Capitalize the last three letters
More complex: if the word starts with a vowel,
just add ay. Move first consonant cluster.
- “trash” -> “ashTRAY”
- “ashtray” -> “ashtrayAY”
- Write a boolean function is_vowel
File reading

File reading
1 >>> f = open("my_file")
2
3 >>> for line in f:
4 ...
5

Longest line in a file

1 def longest_line(f):
2 maxline = ""
3 for line in f:
4 if len(line) > len(maxline):
5 maxline = line
6 return maxline
7
File projects
Dictionaries

Longest line in a file


1 >>> birth_years = {"Bob":1983, "Mary":1955, "Joe":2000}
2 >>> birth_years["Bob"]
3 1983
4 >>> birth_years.keys()
5 ['Bob', 'Mary', 'Joe']
6 >>> birth_years.values()
7 [1983, 1955, 2000]
8 >>> birth_years.has_key("Andy")
9 False

Write a program to count the frequency of words in the Washington state


programming framework.

>>> import operator


>>> sorted(words.iteritems(), key=operator.itemgetter(1))
Classes

point.py

1 from math import *


2
3 class Point:
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8 def distance(self, other):
9 dx = self.x - other.x
10 dy = self.y - other.y
11 return sqrt(dx * dx + dy * dy)
12
13 def __str__(self):
14 return "(" + str(self.x) + ", " + str(self.y) + ")"

• No encapsulation
• Explicit use of self
• __what?!__
Python Resources

http://python.org/
http://diveintopython.org
http://openbookproject.net//thinkCSpy/
Scribblers

Das könnte Ihnen auch gefallen