knerr cs21 notes...
back to schedule
WEEK01: intro to python, unix, cs21, interviews with students
---------------------------------------------------------------
F: loops, range, sequences
Announcements:
- Lab 1
- 15-min interview with me
REVIEW of hello.py
name = raw_input("your full name: ")
yearborn = input("year you were born: ")
print "\nHello, " + name
age = 2009 - yearborn
print "You are " + str(age) + " years old!\n"
UNIX:
- how to copy stuff from my inclass folder:
cp /home/jk/inclass/hello.py hello.py
or
cp /home/jk/inclass/hello.py .
- how to start a new program:
vim newprog.py
DEBUGGING:
- try to break your programs and see what happens
LOOPS:
for < var > in < sequence >:
do this
and this
but not this
< var > is a variable you choose (i, x, foo, ch, etc)
< sequence > is a special python set of values, which
can be any of these:
- a string of characters, like "Hello!!"
- a list of integers, like [1,2,3,4,5]
- a list of anything, like [1,"hi",5.6,"no]
for loop examples:
>>> for ch in "hello":
... print ch
...
h
e
l
l
o
>>> for ch in "hello class":
... print ch*5
...
hhhhh
eeeee
lllll
lllll
ooooo
ccccc
lllll
aaaaa
sssss
sssss
>>> for i in [1,2,3,4,5]:
... print "i = " + str(i)
...
i = 1
i = 2
i = 3
i = 4
i = 5
an easy way to create a list is with the range function:
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,20,2)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
and here's a for loop example using range:
>>> for i in range(20,1,-2):
... print "----->" + str(i)
...
----->20
----->18
----->16
----->14
----->12
----->10
----->8
----->6
----->4
----->2
---> can you write this program?
$ python blastoff.py
countdown start: 7
. . . . 7
. . . . 6
. . . . 5
. . . . 4
. . . . 3
. . . . 2
. . . . 1
blastoff!!