递归和for循环

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#http://www.cnblogs.com/BeginMan/p/3223356.html
#递归2



'非递归方式'
sum=0
#没有sum=0,会出现如下错误提示
'''
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\new.py", line 12, in <module>
    sum+=obj
TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'
'''
for obj in range(5):
    sum+=obj
    
print sum        #10


#递归方式
def foo(n):
    if n>0:
        return n+foo(n-1)
    if n<=0:
        return 0

print foo(4)

 

posted @ 2015-10-23 22:43  Xiao|Deng  阅读(1191)  评论(0编辑  收藏  举报