Finding Sum. TypeError: 'float' object is

2019-03-06 07:37发布

问题:

Today I tried to make a program that would ask a user how many items in a series he/she wanted me to sum. This series would be used to approximate the value of pi. Here is my code thus far:

from math import pi

def pi_sum():
n = eval(input("How many terms do you want to sum: "))
for i in range(n):

    denominator= 2.0 * i + 1
    sign = (-1) ** i
    numerator = 4
    result = (4 * sign) /denominator
    print(result)
    print(sum(result))



pi_sum()

However, this code generates the error message:

File "C:/Users/Crisa/PycharmProjects/untitled/piprogram.py", line 14, in pi_sum
print(sum(result))
TypeError: 'float' object is not iterable

How can I get python to sum the values in my for loop if my for loop is generating floats? I am stuck :/

回答1:

Add your results of each iteration into a list:

myresults = []
for i in range(n):
    ...
    myresults.append(result)

Then at the end, get the sum of the list with all your results:

print(sum(myresults))