WEEK01: intro to python, unix, cs21
-----------------------------------
F: loops, range, sequences
Announcements:
- Lab 1 (due Tuesday night)
PRACTICE UNIX:
ls
ls /home/jk/inclass
cp /home/jk/inclass/WHAT_I_EXPECT_FROM_YOU
cat WHAT_I_EXPECT_FROM_YOU
REVIEW of firstprog.py
"""
Calculate age, given year born.
J. Knerr
Fall 2011
"""
print
name = raw_input(" your full name: ")
yearborn = input(" year you were born: ")
print "\nHello, " + name
age = 2012 - yearborn
# this line is a comment...it does not get run
print "Sometime this year you will be " + str(age) + " years old!\n\n"
UNIX:
- how to copy stuff from my inclass folder:
cp /home/jk/inclass/firstprog.py jeff-firstprog.py
- how to start a new program:
vim newprog.py
- how to run python shell:
python
>>>
DEBUGGING:
- try to break your programs and see what happens!!
LOOPS:
example of a program that uses a loop:
$ python squares.py
I will print out the squares of all numbers from 1 to n!
Please enter n: 6
----------------------------------
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
----------------------------------
for < var > in < sequence >:
do this
and this
and any indented line
over and over and over
code here is not part of loop
< 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]
- all lines in a file (week 7)
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!!