# Class notes from week 2
#
# Examples of simple for-loops in Python
import math
#--------------------------------------------------------------------
# This program adds up the first n whole numbers starting from 1.
# To run it, you have to give it the value of n as a parameter.
# For example, calling addFirst(10) will add up the first 10 numbers
# and then return the result, addFirst(100) will add up the first 100
# numbers, and so on.
def addFirst(n):
total = 0
for i in range(1, n+1):
# the line below will get executed n times, each time with a
# different value of i, starting from 1, 2, 3, ... and
# continuing up to and including n (but NOT n+1):
total = total + i
# print out the final result when the for-loop finishes
print "The sum of the numbers from 1 to", n, "is", total
#--------------------------------------------------------------------
# This program computes an approximation for pi using the rather
# amazing fact that
#
# pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
#
# if you add up an infinite number of terms. If you have less
# patience, you can just add up n terms. The program asks the
# user for n and then computes the approximation, comparing it
# to the value for pi built into Python's math library.
def approx():
n = input("Enter number of terms to add up: ")
# initialize the variables
total = 0
numerator = 4
denominator = 1
sign = +1
# perform the loop n times, once for each term to add up
for i in range(n):
# show the intermediate values of total as we go
print " total is now", total
# compute next term and add it to the running total
term = sign * float(numerator) / float(denominator)
total = total + term
# update denominator and sign for next loop cycle
denominator = denominator + 2
sign = -sign
print "Pi is approximately", total
print "Value of math.pi is", math.pi
#-----------------------------------------------------------------