[Tutor] Need help w/ a for loop

Kent Johnson kent37 at tds.net
Thu Oct 23 13:21:43 CEST 2008


On Thu, Oct 23, 2008 at 12:09 AM, Monte Milanuk <monte at milanuk.net> wrote:

> 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)

Here you should initialize a variable to hold the sum. 'sum' is not a
good name because it is the name of a built-in function. 'total' is
better.

>     for i in range(1,n + 1,2):

Note that this loop has n/2 steps, not n.
>         #  each term is '4/i' as it steps thru the loop starting with 1
>         x = 4 / i

Do you know about integer vs float division? What is the difference
between 4/9 and 4.0/9?

>     #  output the sum - convert it to a float just in case

If it isn't already a float you won't have a very good estimate of pi.

Kent


More information about the Tutor mailing list