1

I am working on a project for school in python 2 and I am having a lot of trouble with one of the problems:

Write a program that computes the following sum: sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N N is an integer limit that the user enters.

For example:
Enter N: 4
Sum is: 2.08333333333

The code I currently have written is:

NumOfN = int(input("What is N? : "))
total = 0
for i in range (NumOfN):
  NextNum = 1.0/(NumOfN)
  total = NextNum
  NumOfN = NumOfN-1
print "the sum is", total

However whenever I run this I get an output of "1.0" any help would be greatly appreciated.

-Thank you.

2
  • 1
    This can be done in one line with a list comprehension and sum. total = sum([1.0/x for x in range(1,NumOfN+1)]) Commented Jan 7, 2016 at 3:04
  • @erip the things you can do with python :) Commented Jan 7, 2016 at 3:20

2 Answers 2

1

You were not incrementing total with itself and NextNum. I changed total = NextNum to total += NextNum:

NumOfN = int(input("What is N? : "))
total = 0
for i in range(NumOfN):
  NextNum = 1.0/(NumOfN)
  total += NextNum
  NumOfN = NumOfN-1
print "the sum is ", total

or more simply:

NumOfN = int(input("What is N? : "))
runningTab = []
for i in range(NumOfN, -1, -1):
    if i != 0:
        runningTab.append(1.0/(i))

print "the sum is ", sum(runningTab)

It is better to use lists and sum at the end than to keep a running tally of numbers.

Sign up to request clarification or add additional context in comments.

1 Comment

@erip well it does reduce the number of variables used and improves upon a few things. Less code is simplified
0

Second line of the for loop:

total = NextNum

The variable total should have NextNum added to it, not just reassigned. This is because total must be added over and over by adding NextNum to itself. Let's change that to:

total = total + NextNum

This would mean: total needs to add NextNum to itself, so we will add them together so that the new total is now equal to the old total + NextNum.

A side note:

You may have noticed that @heinst used += in his line of code, total += NextNum. This is the same as total = total + NextNum , but it is like an abbreviation. You can do this with += , -= , *=,and /=. All of them are ways to abbreviate the line of code that would reassign a variable after doing some arithmetic on it.

With that being said, the following line of code:

NumOfN = NumOfN-1

Can become:

NumOfN -= 1

This is an abbreviation.

2 Comments

I never knew I could do NumOfN -= 1 like that, that will make life a lot easier, thanks
No problem :D @TheRIProgrammer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.