U of T CS4HS 2011: Python Workshop
Dan Zingaro July 13-14, 2011
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
Dan Zingaro July 13-14, 2011
◮ 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/
◮ 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)
◮ 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.
◮ 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’>
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
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
◮ 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!
◮ Create numbers by using numeric literals ◮ If you include no fractional component, it’s an integer;
◮ 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
◮ 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
◮ 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
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
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
◮ 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
◮ 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
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]
◮ 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
◮ 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
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}
◮ 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}
◮ 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
◮ 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
◮ open gives us a file object, with lots of methods we can use to
◮ 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)
◮ 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
◮ 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
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
◮ 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!