python - How can I Improve this Code, using While Loop? -


create function addnumbers(x) takes number argument , adds integers between 1 , number (inclusive) , returns total number.
examples :

addnumbers(10)
55
addnumbers(1)
1

so question, have done using while loop , , worked fine. not satisfied code, did problem using loop , that's okay me, want know best way improve dis code using while loop.

def addnumbers(num):     total = 1     = 1     while < num:           += 1           total +=     return total print addnumbers(10) 

and here loop answer :

def addnumbers(num):     my_list = list(range(num+1) )     in my_list:         my_list.append(i)         return sum(my_list)   

usually isn't place such questions, anyway.. can use sum() , range(). range() return list of numbers 0 n , sum will, well, sum it.

def sumnumbers(n):     return sum(range(n+1)) 

edit: , using while loop:

def sumnumbers(n):     = 0     sum = 0     while <= n:        sum +=        += 1     return sum 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -