CS52 - Fall 2015 - Class 12
Example code in this lecture
while.py
bit.py
Lecture notes
admin
- how did assignment 4 go?
- assignment 5
- out
- should be able to finish it after today's class
high level
- look at first two functions of
while.py code
- lists
- defining classes in python: look at
bit.py code
python basics
- running python and interacting with the python shell
- python is an interpreted language, like SML
- can just type "python" at the terminal to get a shell
- execfile
- like "use" in SML
- it's a function, though:
>>> execfile("while.py")
- :
- defines a block, we'll see it a lot
- indentation indicates blocks (the role previously reserved for curly braces)
- indentation is critical and is not just stylistically important
- basic control flow
- if/elif/else
- for
- use of range
- while
- defining functions
- def
- no return type
- no parameter types
- comments
- docstrings
- print
- using str()
- talk about pass
lists
- similar to arrays in Java
- indexable
- can iterate over
- some differences
- actually a class, so they have methods
- they're extensible and mutatable (sort of like ArrayList class in Java)
- can append to them
- can insert into them
- can delete elements in them
- creating with []
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> l = ["apples", "bananas", "carrots"]
>>> l
['apples', 'bananas', 'carrots']
>>> l = [1, "apples", [1, 2]]
>>> l
[1, 'apples', [1, 2]]
- indexing
>>> l = [1, 2, 3, 4]
>>> l2 = ["apples", "bananas", "carrots"]
>>> l3 = [1, "apples", [1, 2]]
- starts counting at 0, like in Java
>>> l[0]
1
>>> l2[2]
'carrots'
>>> l3[1]
'apples'
- can index from the back using negative numbers
>>> l[-1]
4
- slicing
- can also "slice" the list to get a sublist
>>> l[1:3]
[2, 3]
- many methods (see the documentation)
- append
>>> l = []
>>> l.append(2)
>>> l.append(3)
>>> l
[2, 3]
- indexing
- iterating over
- using for
- talk about what range does
defining classes in python: look at
bit.py code