|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 风不会停息 于 2018-6-20 22:33 编辑
1. 如果想在函数内部定义全局变量, 用 global 关键字
- >>> count = 5
- >>> def MyFun():
- global count
- count = 10
- print(count)
- >>> MyFun()
- 10
- >>> count
- 10
复制代码
2. 对于函数嵌套, 外层函数对于内层函数来说时透明的, 而内层函数对于外层函数是不可见的, 不能在外层函数访问到内层函数的变量, 有一个特例, 当在外层函数和内层函数中定义了同一个变量时, 外层函数的变量会被暂时 “屏蔽” 掉, 例如:
- def outside():
- var = 5
- def inside():
- print(var)
- var = 3
-
- inside()
- outside()
复制代码
此时程序会报错
3. 访问内层函数的两种办法:
- def funOut():
- def funIn():
- print('宾果!你成功访问到我啦!')
- return funIn
- funOut()()
- 宾果!你成功访问到我啦!
复制代码
- def funOut():
- def funIn():
- print('宾果!你成功访问到我啦!')
- return funIn()
- funOut()
- 宾果!你成功访问到我啦!
复制代码
4. 在内层函数中如果想修改外层函数的值, 使用 nonlocal 关键字:
- >>> def Fun1():
- x = 5
- def Fun2():
- nonlocal x
- x *= x
- return x
- return Fun2()
- >>> Fun1()
- 25
复制代码
5. 闭包: 在一个外函数中定义了一个内函数,内函数里运用了外函数的临时变量,并且外函数的返回值是内函数的引用。这样就构成了一个闭包。 例如
- >>> def fun1(a):
- b = 10
- def fun2():
- print(a + b)
- return fun2()
复制代码
python中一切皆对象, 形成闭包后, 内层函数引用的外层函数定义的变量叫做闭包变量,闭包变量不会释放,会像全局变量一样, 会随着闭包函数的调用而更新
最后附一个 020 动动手第1题程序:
- str_long = """待输入的字符串"""
- length = len(str_long)
- for each in range(length):
-
- if str_long[each] == '\n':
- continue #检测换行符
-
- count_left = 0 #检测左边大写字母
- count_right = 0 #检测右边大写字母
- if each >= 2: #防止分片时发生重复
- i = each
- if str_long[each].islower(): #小写字母
- str1 = str_long[ : (each)]
- str2 = str_long[(each + 1) : ] #检查到小写字母时, 将小写字母左右分片
- while i != 0 and str1[i - 1].isupper(): #str1[i] 会越右界, 所以要用str[i - 1], i = 0 时 (i - 1) 到达左边界
- count_left += 1
- i -= 1
- i = 0 #str2从0开始计数
- while ( i != len(str2) ) and str2[i].isupper(): #i = len(str2) 到达右边界
- count_right += 1
- i += 1
- if ( count_left == 3 ) and ( count_right == 3 ):
- print(str_long[each], end = '') #打印符合条件的小写字母
复制代码 |
|