1
while i<10:
   a = a + i
   print (a)
   i = i+1

or

for i in range(10):
   sum = sum + i
   print

0
1
3
6
10
15
21
28
36
45

Then how can I add them together by writing further codes? I mean 1+3+6+10+15+21+... Then set the total as variables! That would be great if you can show me in both loop :)

1
  • Do not call your variable sum; that's the name of a built-in function. (And you might want to type help(sum) at the interpreter console, because it may help you here.) Commented Oct 25, 2012 at 23:53

3 Answers 3

2

How about this:

total, totaltotal = 0, 0
for i in range(10):
  total += i
  totaltotal += total
  print total, totaltotal

Alternatively, you can make a list of the totals and store them to operate on separately:

total, totals = 0, []
for i in range(10):
  total += i
  totals.append(total)
  print total
totaltotal = 0
for i in range(10):
  totaltotal += totals[i]
  print totaltotal

You may want to rewrite this as a list comprehension (or even a generator expression), as a useful exercise.

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

Comments

1

How about

sum(sum(i + 1 for i in range(n)) for n in range(10))

(if you want a pythonic approach)

Comments

1
In [26]: summ=0

In [27]: foo=0       

In [28]: for i in range(10):
    sum+=i          #add i to summ
    foo+=sum        #add summ to foo
   ....:     
   ....:     

In [31]: sum
Out[31]: 45

In [32]: foo
Out[32]: 165

or a one-liner:

In [58]: sum(map(sum,map(range,range(1,11))))
Out[58]: 165

timeit comparisons:

In [56]: %timeit sum(sum(i + 1 for i in range(n)) for n in range(1000))
10 loops, best of 3: 128 ms per loop

In [57]: %timeit sum(map(sum,map(range,range(1,1001))))
10 loops, best of 3: 27.4 ms per loop

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.