Lab 0: intro to python

Comp 150, Dordal, January 20, 2006

Follow along with the following as I talk about them in class. Your only assignment is to download and install python on your home computer (if applicable).

1. To start python:

The file "foo.py" in your startup directory can be loaded with import foo.

2. Things to try:

3. A simple function
def greet(person):
	print "Hello", person
	print "How are you today?"
How does Python tell when you're done with def?

4: ranges

for i in range(1,10):
    print i

Tweak this to make a table of i, i*i

sum = 0
for i in range(1,100):
    sum += i

sum
5. What, by the way, *is* range(10), or range(20,40)?
	z = range(1,10)
	z

6. The factorial function:

def fact2(n):
	prod = 1
	for i in range(1,n):
		prod *= i
	return prod
7. That's the iterative version. But the standard mathematical definition of factorial,
		1 if n=0
	n! =
		n*(n-1)! if n>0
tends to suggest the following recursive definition:
def fact1(n):
	if n==0: return 1
	else:	return n*fact1(n-1)
8. fact1 gets into trouble at fact1(1000). What is the largest value you can calculate?

9. Create the file chaos.py containing

def main():
        print "This program illustrates a chaotic function"
        x = input("Enter a number between 0 and 1: ")
        for i in range(10):
                x = 3.9*x*(1-x)
                print x
Now type "import chaos".

Try to run main:

	main
	main()
	chaos.main
	chaos.main()

10. More examples of printing. Note the middle line ends with a comma.

print 3,4
print 5,6,
print 7,8

10. Here's a function with some errors. What are they? How fatal are they?

def addup(n):
    for i in range(n):
        sum += j
    return sum

11. Simultaneous assignment:

x,y = y,x

12. Some lists

[1,2,2,3,4,5]
[[1], [1,2], "hello", 61]

z = [[1], [1,2], "hello", 61]

13. Now we can involve those lists in expressions:

z[0], etc
len(z)

[z, [z,z]]
The in operator:
61 in z
Concatenation:
z+z
Slicing (maybe you need a longers z: try z=z+z to get one)
z[1:3]