[Tutor] Need help w/ a for loop
Monte Milanuk
monte at milanuk.net
Thu Oct 23 06:09:26 CEST 2008
Hello all,
New guy here, so go easy on me ;)
I'm starting to work my way through Python Programming by Zelle, and have hit a bit of a wall on one of the programming exercises in Chapter 3 (#15 if anyone has the book handy).
What the question ask is: Write a program that approimates the value of pi by summing the terms of this series: 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11+... The program should ask the user for 'n', the number of terms to sum, and then output the sum of the first 'n' terms of this series.
Where I am running into problems is how to do the '-' & '+', depending on the value of 'n'. i.e. if 'n' = 3, it's going to be a - & an +, if 'n' =5 its going to be -, +, -, +, etc. How to make that work in terms of an algorithm is making my head hurt (and its so early in the book yet... ;) )
Here's what I have thus far:
# approximate_pi.py
# Approximates the value of 'pi' by summing the terms of a series.
#
import math
def main():
print "This program will approximate the value of pi"
print "to a degree determined by the user. "
print
# get the value of n from the user
n = input("How many terms do you want me to sum? ")
print
# create a loop from 1 to n+1, odd)
for i in range(1,n + 1,2):
# each term is '4/i' as it steps thru the loop starting with 1
x = 4 / i
# not sure where to go from here
print
# output the sum - convert it to a float just in case
print "The sum of the numbers you entered is", (float(sum))
# calculate the difference between our approximation and Python's pi
diff = sum - math.pi
# output the difference
print
print "The difference between your 'pi' & Python's pi is", diff, "."
main()
Any assistance or nudges in the right direction would be most appreciated.
Thanks,
Monte
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081022/fc3e79c5/attachment.htm>
More information about the Tutor
mailing list