python学习:1.5.4递归和闭包

对我来说闭包是块大生肉。

# -*- coding: utf-8 -*-
"""
Created on Thu May  9 17:32:57 2019

@author: Administrator
"""

# 递归函数
def addn(n):
    if n == 1:
        return 1
    return n + addn(n - 1)

print('递归:', addn(100))

#闭包
def adderx(x):
    def addery(y):
        return x + y
    return addery
    
s = adderx(1)
print('闭包:',s(100))

def counter(name):
    c = [0]
    def count():
        c[0] += 1
        if c[0] == 1: print('this is the', '1st', 'access to', name)
        elif c[0] == 2: print('this is the', '2nt', 'access to', name)
        elif c[0] == 3: print('this is the', '3rd', 'access to', name)
        else:  print('this is the', repr(c[0]), 'th access to', name)
    return count

print('a--------------')
a = counter('example')
print(a())
print(a())
print(a())
print(a())

print('b--------------')
a = counter('example')
print(a())
print(a())

运行:

递归: 5050
闭包: 101
a--------------
this is the 1st access to example
None
this is the 2nt access to example
None
this is the 3rd access to example
None
this is the 4 th access to example
None
b--------------
this is the 1st access to example
None
this is the 2nt access to example
None

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值