0
k = 1
M = input("Enter an integer: ")
for M in range(k,M):
    s = 1/float(M)
    print sum(s)

How do I get the sum of s? I keep getting an error message:

File "C:/Python27/summation.py", line 7, in <module>
  print sum(s)
TypeError: 'float' object is not iterable
2
  • sum of what? Of a single element? Commented Jul 8, 2016 at 5:23
  • Please provide the whole error message that you get Commented Jul 8, 2016 at 5:24

5 Answers 5

3

s is not a list it is a float. Try this instead:

k = 1
M = input("Enter an integer:")
print sum(1/float(s) for s in range(k, M))
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

s=[]
k = 1
M = input("Enter an integer: ")
for M in range(k,M):
    s.append(1/float(M))
print(s)
print(sum(s))

Output(M=10):

[1.0, 0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666, 0.14285714285714285, 0.125, 0.1111111111111111]
2.8289682539682537

Comments

0

In this source code, value M is override twice. So if change the M in the for loop, you can get the sum of s. The fixed coed is below.

k = 1
M = input("Enter an integer: ")
S = []
for V in range(k,M): S.append(V)
print sum(s)

Also, If you want to get a sum of list, you must make a value list and append the value(V) in the list.

Comments

0

You can try with the following code:

result = 0
k = 1
M = int(input("Enter an integer: "))
for M in range(k, M):
    result += (1 / float(M))
print(result)

How it works? It will ask for an input, and do the operation. The result of each cycle of the loop will be added to a variable called result.

Simple, hope it works for you.

Comments

0

I guess you need to count the sum of 1/1.0 + ... + 1/yourInput.

You can use the method below.

def getSum(yourInput):
    scoreLst = [1/float(e) for e in range(1, yourInput)]
    return sum(scoreLst)

e.g:getSum(10), you will get the output:2.828...

Comments

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.