U of T CS4HS 2011: Python Workshop Dan Zingaro July 13-14, 2011 - - PowerPoint PPT Presentation

u of t cs4hs 2011 python workshop
SMART_READER_LITE
LIVE PREVIEW

U of T CS4HS 2011: Python Workshop Dan Zingaro July 13-14, 2011 - - PowerPoint PPT Presentation

U of T CS4HS 2011: Python Workshop Dan Zingaro July 13-14, 2011 Python History Late 1970s: programming language called ABC High-level, intended for teaching Only five data types Programs are supposedly one-quarter the size of the


slide-1
SLIDE 1

U of T CS4HS 2011: Python Workshop

Dan Zingaro July 13-14, 2011

slide-2
SLIDE 2

Python History

◮ Late 1970s: programming language called ABC

◮ High-level, intended for teaching ◮ Only five data types ◮ Programs are supposedly one-quarter the size of the equivalent

BASIC or Pascal program

◮ Not a successful project ◮ More ABC information:

http://homepages.cwi.nl/~steven/abc/

slide-3
SLIDE 3

Python History...

◮ 1983: Guido van Rossum joined the ABC team ◮ Late 1980s: Guido started working on a new project, in which

a scripting language would be helpful

◮ Based it on ABC, removed warts (e.g. ABC wasn’t extensible) ◮ Python, after Monty Python ◮ Guido: Benevolent Dictator for Life (BDFL)... but he’s

retiring!

◮ http://www.artima.com/intv/ (search for Guido)

slide-4
SLIDE 4

Why Python for Education?

◮ Readable, uniform code structure ◮ No compilation step — Python is interpreted ◮ Supports and integrates imperative and OOP features ◮ Batteries included: Python’s standard library comes with tools

for a variety of problem domains, and thousands of additional modules are available for download

◮ Writing games, creating GUIs, web scripting, accessing

databases, etc.

slide-5
SLIDE 5

Dynamic Typing

◮ Biggest conceptual change compared to C, Pascal, Java etc. ◮ Variables do not have types. Objects have types

>>> a = 5 >>> type (a) <type ’int’> >>> a = ’hello’ >>> type (a) <type ’str’> >>> a = [4, 1, 6] >>> type (a) <type ’list’>

slide-6
SLIDE 6

Functions and Ifs

defining functions and using if statements is similar to what you expect (. . . except for the indentation!):

def bigger (a, b): print ’Hi’ if a > b: return a else: return b

slide-7
SLIDE 7

While Loops

There’s a standard while loop (but for loops are different; we’ll talk about that later)

i = 8 while i > 0: print i i = i - 1

slide-8
SLIDE 8

Built-in Types

◮ We’ll look at the core five object types that are built-in to

Python

◮ Numbers ◮ Strings ◮ Lists ◮ Dictionaries ◮ Files

◮ They’re extremely powerful — we do many assignments with

these alone!

slide-9
SLIDE 9

Built-in Types: Numbers

◮ Create numbers by using numeric literals ◮ If you include no fractional component, it’s an integer;

  • therwise it’s a float

◮ We have all of the standard mathematical operators, and even

** for exponent

◮ Make integers as small or large as you like — they can’t go

  • ut of bounds
slide-10
SLIDE 10

Exercise: Numbers

Exercise 1 on handout

slide-11
SLIDE 11

Built-in Types: Strings

◮ A string is a sequence of characters ◮ To indicate that something is a string, we place single- or

double-quotes around it

◮ We can use + to concatenate strings ◮ This is an example of overloading: + is used to add numbers

too; it knows what to do based on context

◮ What happens if we try to use + with a string and a number?

◮ Error: + doesn’t know what to do! ◮ e.g. is ’3’ + 4 supposed to be the string ’34’ or the number

7?

◮ Design philosophy: Python tries never to guess what you mean

slide-12
SLIDE 12

Strings...

◮ The * operator is overloaded, too

◮ Applied to a string and an integer i, it duplicates the string i

times

◮ If i ≤ 0, the result is the empty string

◮ Can also use relational operators such as < or > to lexically

compare strings

slide-13
SLIDE 13

Looping Through Strings

for char in s: <do something with char>

◮ We’ll see this pattern again and again for each Python type ◮ It’s like Php’s foreach or Java’s for-with-the-colon ◮ Let’s write a function that counts the number of vowels in a

string

◮ The in operator can be used for set membership

slide-14
SLIDE 14

Possible Solution: How Many Vowels? (num vowels.py)

def num_vowels(s): ’’’Return the number of vowels in string s. The letter "y" is not treated as a vowel.’’’ count = 0 for char in s: if char in "aAeEiIoOuU": count += 1 return count

slide-15
SLIDE 15

String Methods

◮ Like in Java, strings are objects and have tons of methods ◮ Use dot-notation (i.e. object.method) to access methods ◮ Use dir (str) to get a list of them, and

help (str.methodname) for help on any method

◮ Useful ones: find, lower, count, replace... ◮ Like Java again, strings are immutable — all we can do is

create new strings

slide-16
SLIDE 16

Indexing and Slicing Strings

◮ Assume s is a string ◮ Then, s[i] for i ≥ 0 extracts character i from the left (0 is

the leftmost character)

◮ We can also use a negative index i to extract a character

beginning from the right (-1 is the rightmost character)

◮ Slice notation: s[i:j] extracts characters beginning at

s[i] and ending at the character one to the left of s[j]

◮ If we leave out the first index, Python defaults to using index 0

to begin the slice

◮ Similarly, if we leave out the second index, Python defaults to

using index len(s) to end the slice

slide-17
SLIDE 17

Exercise: Strings

Exercises 2 and 3 on handout

slide-18
SLIDE 18

Built-in Types: Lists

Lists are the closest thing we have to arrays. . . . but they’re not that close! Strings Lists Sequences of? Characters Any object types Immutable? Yes No Can be heterogeneous? No Yes Can index and slice? Yes Yes Can use for-loop? Yes Yes Created like? ’hi’ [4, 1, 6]

slide-19
SLIDE 19

List Methods

◮ As with strings, there are lots of methods; use dir (list) or

help (list.method) for help

◮ append is used to add an object to the end of a list ◮ extend is used to append the objects of another list ◮ insert (index, object) inserts object before index ◮ sort() sorts a list ◮ remove (value) removes the first occurrence of value from

the list

slide-20
SLIDE 20

Exercise: Length of Strings

◮ Write a function that takes a list of strings, and prints out the

length of each string in the list

◮ e.g. if the list is [’abc’, ’q’, ’’], the output would be as

follows

3 1

slide-21
SLIDE 21

Exercise: Lists

Exercise 4 on handout

slide-22
SLIDE 22

Built-in Types: Dictionaries

Dictionaries are like Php associative arrays, or Java maps.

Lists Dictionaries Stores? Sequences of objects Key-value pairs Immutable? No No Can be heterogeneous? Yes Yes Can index and slice? Yes No Can use for-loop? Yes Yes Created like? [4, 1] {’a’:1, ’b’:2}

slide-23
SLIDE 23

Dictionaries vs. Lists

◮ Compared to using “parallel lists”, dictionaries make an

explicit connection between a key and a value

◮ But unlike lists, dictionaries do not guarantee any ordering of

the elements

◮ If you use for k in d, for a dictionary d, you get the keys

back in arbitrary order bird_dict = { ’peregrine falcon’:1, ’harrier falcon’:5, ’red-tailed hawk’: 2, ’osprey’ : 11}

slide-24
SLIDE 24

Adding to Dictionaries

◮ Dictionary keys must be of immutable types (no lists!), but

values can be anything

◮ We can use d[k] = v to add key k with value v to dictionary

d

◮ We can use the update method to dump another dictionary’s

key-value pairs into our dictionary

◮ We can use d[k] to obtain the value associated with key k of

dictionary d

◮ If k does not exist, we get an error

◮ The get method is similar, except it returns None instead of

giving an error when the key does not exist

slide-25
SLIDE 25

Exercise: Dictionaries

Exercises 5 and 6 on handout

slide-26
SLIDE 26

Built-in Types: Files

◮ To open a file in Python, we use the open function ◮ Syntax: open (filename, mode) ◮ mode is the string ’r’ to open the file for reading, ’w’ to

  • pen the file for writing, or ’a’ to open the file for
  • appending. No mode defaults to ’r’

◮ open gives us a file object, with lots of methods we can use to

  • perate on the file

◮ readline gives us the next line (or the empty string at EOF) ◮ read gives us the remainder of the file as one string ◮ readlines gives us the remainder of the file as a list of strings

(one string per line)

slide-27
SLIDE 27

Exercise: Files

Exercise 7 on handout

slide-28
SLIDE 28

Messing with Sounds

◮ Some of my favourite assignments have students play with

sounds and music

◮ If we import sound_media (my module, not built-in to

Python), we can use load_sound to load a wav file

◮ The resultant sound object has methods just like a built-in

Python object

slide-29
SLIDE 29

Methods in sound media

◮ create_sound (num_samples): create a silent sound with

num_samples samples

◮ get_sample (index): get the sample at a given index ◮ get_value (sample): get the value of a sample ◮ We’ll start with a function that changes the volume of a sound

slide-30
SLIDE 30

Changing Volume

import sound_media def change_volume(snd, factor): ’’’Return a copy of snd, but whose volume is scaled by factor’’’ target = sound_media.create_sound (len(snd)) i = 0 while i < len(snd): source_sample = sound_media.get_sample(snd, i) target_sample = sound_media.get_sample(target, i) value = sound_media.get_value(source_sample) * factor sound_media.set_value(target_sample, int(value)) i = i + 1 return target

slide-31
SLIDE 31

Exercise: Sounds

Exercise 8 on handout

slide-32
SLIDE 32

Further Python Resources

◮ http://rmi.net/~lutz/

◮ Mark Lutz’ Python books ◮ Constantly-updated to keep up with Python releases

◮ docs.python.org/tutorial

◮ Free online Python tutorial

◮ nifty.stanford.edu

◮ SIGCSE Nifty Assignments (some Python-related) ◮ I’ve modified a couple of the Java/C assignments to fit Python

— please get in touch!