[Solved] Writing a python program takes an int argument and adds 1+1/2+1/3+1/4….1/n [closed]


Your problem is that you are adding a preliminary 1 to 1/1 which gives 2. Try this:

def count(n):
    sum = 0 #Intializing the return variable
    for i in range(1, n+1):
        sum+=1.0/i #Adding to the return variable
    return sum

This works as such:

>>> def count(n):
...     sum = 0
...     for i in range(1, n+1):
...             sum+=1.0/i
...     return sum
... 
>>> count(4)
2.083333333333333
>>> count(1)
1.0
>>> count(2)
1.5
>>> count(3)
1.8333333333333333
>>> count(4)
2.083333333333333
>>> 

4

solved Writing a python program takes an int argument and adds 1+1/2+1/3+1/4….1/n [closed]