Harold Nelson
1/25/2018
Run these following batches of commands by hand in the python shell.
help(turtle)
help('turtle')
import turtle
help(turtle)
import turtle
joe = turtle.Turtle()
help('joe')
help(joe)
What can you infer about the use of help() from these examples?
Run the following batches of commands by hand in the python shell.
print(2**.5)
print(sqrt(2))
import math
print(math.sqrt(2))
print(pi)
print(math.pi)
What does this tell you?
When you start python, it has very limited mathematical capabilities. If you import the math module, python gains a lot of mathematics.
See the publisher’s powerpoint starting with slide 4.
import math
def archimedes(numSides):
innerangleB = 360.0/numSides
halfangleA = innerangleB/2
onehalfsideS = math.sin(math.radians(halfangleA))
sideS = onehalfsideS * 2
polygonCircumference = numSides * sideS
pi = polygonCircumference/2
return pi
# Test it
pi_est = archimedes(10)
print(pi_est)
## 3.09016994375
How many sides does it take to get a good approximation of \(\pi\)?
A better question: How do we measure the quality of an approximation.
All of these estimates are low. We can measure the quality by taking the ratio of the estimate to the true value given by math.pi.
Write python code to compute the sum of the first 4 integers.
total = 0
for i in range(1,5):
total = total + i
print(total)
## 10
Write a python function to compute the sum of the first N integers. Test it by using 4 as the input.
def sum_first_N(N):
total = 0
for i in range(1,N+1):
total = total + i
return total
testval = sum_first_N(4)
print(testval)
## 10
Write a python function to compute the average of the first N integers.
def avg_first_N(N):
total = 0
count = 0 # Could avoid, but...
for i in range(1,N+1):
total = total + i
count = count + 1.0
avg = total/count
return avg
testavg = avg_first_N(4)
print(testavg)
## 2.5
Write python code to calculate the product of the first 4 integers.
prod = 1
for i in range(1,5):
prod = prod * i
print(prod)
## 24
Write a python function to compute the product of the first N integers.
def pfN(N):
prod = 1
for i in range(1,N+1):
prod = prod * i
return prod
# Test with 4
print(pfN(4))
# Test with 10
print(pfN(10))
## 24
## 3628800