By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,363 Members | 1,291 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,363 IT Pros & Developers. It's quick & easy.

syntax question

P: 1
Expand|Select|Wrap|Line Numbers
  1. def sumTo(n):
  2.     sum = 0
  3.      for i in range(1, n+1):
  4.        sum = sum + i
  5. return sum
  6.  
hi with the code above can someone please walk me through what is actually happening with n is equal to say 10 and the output is 55?

many thanks!
Apr 7 '13 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
To begin, you need to fix your indentation:
Expand|Select|Wrap|Line Numbers
  1. def sumTo(n):
  2.     sum = 0
  3.     for i in range(1, n+1):
  4.         sum = sum + i
  5.     return sum
The code iterates over the list created by calling range() (1, 2,....,10) and adds all the numbers to the initial value of "sum" which is 0. BTW, you should not use the name "sum" as an identifier, because the built-in function sum() will be masked. Another way to express your function would be:
Expand|Select|Wrap|Line Numbers
  1. reduce(lambda x, y: x+y, range(1, n+1), 0)
or:
Expand|Select|Wrap|Line Numbers
  1. >>> import operator
  2. >>> reduce(operator.add, range(1, n+1))
  3. 55
  4. >>> 
Apr 7 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.