n = int(input("Enter the nth term"))
fsum = 0
#Recommended to not use 'sum' itself
#as it can cause problems with python's built in function which also has the same name
for i in range(1, n+1):
fsum += i/(i+1)
print(fsum)
def sum_fraction(n):
# Initialize the sum variable
sum = 0
# For loop : start from 1 ( n greater than zero ) : end with n
for i in range(1, n):
# Sum current term with all previous term (term by term)
sum += i / (i + 1)
return sum
n = 5
res = sum_fraction(n)
我想这应该能解决你的问题
如果你想了解更多关于范围函数的信息,请参见 https://www.w3schools.com/python/ref_func_range.asp
注意,range函数只返回
stop
值,不包括stop
值。在您的例子中stop
值是变量n
。这就是为什么我们必须在range函数中使用n+1
你可以试试
相关问题 更多 >
编程相关推荐