Comp 150, Dordal
Follow along with the following as I talk about them in class. The part you are to submit is at the bottom, under What you are to turn in. You should turn it in, by email, by Thursday, May 21.
1. To start python:
2. Things to try:
def greet(person):How does Python tell when you're done with def?
print "Hello", person
print "How are you today?"
4: ranges
for i in range(1,10):
print i
Tweak this to make a table of i, i*i.
Here's another example:
sum = 05. What, by the way, is range(10), or range(20,40)? Can you type it by itself?
for i in range(1,100):
sum += i
sum
z = range(1,10)
z
6. The factorial function:
def fact2(n):7. That's the iterative version. But the standard mathematical definition of factorial,
prod = 1
for i in range(1,n+1):
prod *= i
return prod
1 if n=0tends to suggest the following recursive definition (this is also our first look at if-else):
n! =
n*(n-1)! if n>0
def fact1(n):8. fact1 gets into trouble at fact1(1000). What goes wrong? What is the largest value you can calculate?
if n==0: return 1
else: return n*fact1(n-1)
9. More examples of printing. Note the middle line ends with a
comma. What happens? You may have to put these in a function to see the
difference.
print 3,4
print 5,6,
print 7,8
10. Here's a function with an error. What is it? How can it be fixed?
def addup(n):
for i in range(n):
sum += j
return sum
11. Square roots. To find the square root of x, use math.sqrt(x). But note that the statement
import math
must have been included (just once!) somewhere before using math.sqrt(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], etcThe in operator:
len(z)
[z, [z,z]]
61 in zConcatenation:
z+zSlicing (maybe you need a longer z: try z=z+z to get one)
z[1:3]14. The quadratic formula. The formula for the roots of ax2+bx+c is x = (-b ± sqrt(b2-4ac))/2a. Implement a python function roots(a,b,c) to calculate this. Be careful of the denominator; it has to be in parentheses!You can calculate either just one of the two roots, or else return a list of both roots. If b2-4ac is negative, there are no (real) roots. Can you get the program to return the string "no roots" in this case?