标签:作用 imp 改变 形参 列表 规则 逻辑 variable 溢出
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。
你可以定义一个由自己想要功能的函数,以下是简单的规则:
def function_name(parameter): ‘‘‘Annotations‘‘‘ Logic *** return Value
#return Value; # *The first return ends. # return value = 0, return None # return value = 1, return Object # return value > 1, return Tuple
默认参数 *default parameters
# z is default parameter. def count(x, y, z=3): "annotations" v = x + y + z return v print(count(1, 2))
# all is position parameter. def count(x, y, z): "annotations" v = x + y + z return v print(count(1, 2, 3))
# y,z is keywords parameter def count(x, y, z): ‘annotations‘ v = x + y + z return v print(count(1, y=2, z=3))
1 # *args Received all undefined position parameter as a Tuple. 2 def count(x, *args): 3 print(x) 4 print(args) 5 6 7 count(1, 2, 3, 4, 5)
# **kwargs Received all undefined keywords parameter as a Dict. def count(x, **kwargs): print(x) print(kwargs) count(1, y=6, z=7)
# Universal, Receive all. def count(x, *args, **kwargs): print(x) print(args) print(kwargs) count(1, 2, 3, 4, 5, y=6, z=7)
引用列表 *list
引用字典 **dict
variable_NAME = [‘variable_value1‘, ‘variable_value2‘] def function_name(): NAME = ‘variable_value‘ print(NAME) function_name()
variable_NAME = [‘variable_value1‘, ‘variable_value2‘] def function_name(): NAME.append(‘variable_value3‘) print(NAME) function_name()
variable_NAME = [‘variable_value1‘, ‘variable_value2‘] def function_name(): global NAME variable_NAME = ‘variable_value‘ print(NAME) function_name()
variable_NAME = [‘variable_value1‘, ‘variable_value2‘] def function_name(): global NAME variable_NAME = [‘variable_value‘] variable_NAME.append(‘variable_value3‘) print(NAME) function_name()
全局变量为大写;
局部变量为小写
如不规范:同一函数体内,全局变量global关键字必须在局部变量前面,否则报错;
import time person_list = [‘fj‘, ‘gy‘, ‘zl‘, ‘yf‘, ‘ym‘, ‘cy‘, ‘zq‘] def ask_way(person_list): print(‘-‘ * 60) if len(person_list) == 0: return "YES" y = person_list.pop(0) # print(y) if y == ‘zq‘: return "NO" print("%s , I not know" %y) time.sleep(1) res = ask_way(person_list) return res print(ask_way(person_list))
作用域在定义函数时就已经固定了,不会随着调用位置的改变而改变.
name = ‘abc‘ def test(): name = ‘efg‘ def test1(): name = ‘hij‘ def test2(): print(name) return test2 return test1 test()()()
lambda x:x**2
name = ‘s1‘ test = lambda x: x + ‘s2‘ print(test(name))
test1 = lambda x, y, z: (x + 1, y + 1, z + 1) print(test1(1, 2, 3))
标签:作用 imp 改变 形参 列表 规则 逻辑 variable 溢出
原文地址:http://www.cnblogs.com/IMxY/p/6888809.html