① Function definition and call:
- Define function format
#def function name (formal parameter): # content def Num(a,b): return a+b print(Num(5,10)) #Execution results: ''' 15 '''
② Arguments to function:
- Required parameter
def sum(a,b): sum = a+b print(sum) sum(333,333) #Execution results: ''' 666 '''
- Default parameters
def sum(a=333,b=111): sum = a+b print(sum) sum(b=333) #Execution results: ''' 666 '''
- Optional parameters
The passed in parameter list is Yuanzu
def sumCount(*args): result = 0 for item in args: result += item print(result) sumCount(111,222,333) #Execution results: ''' 666 '''
- Keyword parameters
The parameter list passed in is a dictionary
def demo(**dict): print(dict) pass demo(name='cjl', age=18) #Execution results: ''' {'name': 'cjl', 'age': 18} '''
- Parameter related cases
def people(name, age=18, *phone, **contact): print("I am{0},this year{1}year".format(name,age)) print("My cell phone number is:{0}".format(phone)) print("My other contact information:%s"%contact) people("cjl","19",12345,54321,qq="2653644677",wechat="chen2653644677") #Execution results: ''' I am cjl,He is 19 years old My cell phone number is:(12345, 54321) My other contact information:{'qq': '2653644677', 'wechat': 'chen2653644677'} '''
③ Reference to parameter:
- In python, everything is an object. When calling a function, the argument passes the reference of the object
- After understanding the principle, we can better control whether the processing inside the function will affect the data changes outside the function
- Parameter passing is done through object references
li=[] def test(parms): li.append([1,2,3]) print(id(parms)) print("Internal{}".format(parms)) print(id(li)) test(li) print("External{}".format(li)) #Execution results: ''' 2712787529992 2712787529992 Internal[[1, 2, 3]] External[[1, 2, 3]] '''
④ Function return value:
- return
def fun(a,b): sum = a + b return sum, sum * a rs1,rs2 = fun(10,10) print('rs1={0},rs2={1}'.format(rs1,rs2)) #Execution results: ''' rs1=20,rs2=200 '''
⑤ Nesting of functions:
- Execute from top to bottom
def fun1(): print("666") def fun2(): print("*****") fun1() print("*****") fun2() #Execution results: ''' ***** 666 ***** '''
⑥ Variable scope:
- local variable
def text1(): a = 123 print("Before modification:%d"%a) a = 666 print("After modification:%d"%a) def text2(): a = 888 print("text2 of a Value sum text1 Medium a Values do not conflict--%d"%a) text1() text2() #Execution results: ''' Before modification: 123 Modified: 666 text2 of a Value sum text1 Medium a Values do not conflict--888 '''
- global variable
a = 666 #global variable def text1(): print(a) #Call global variable a def text2(): print(a) #Call global variable a text1() text2() #Execution results: ''' 666 666 '''
- The local and global variable names are the same
a = 100 #Global variable a def text1(): a = 123 #When the local variable a has the same name as the global variable, the local variable takes precedence print("Before modification:%d"%a) a = 666 print("After modification:%d"%a) def text2(): print("a The value of is:%d"%a) #If there is no local variable, the global variable is called by default def text3(): global a #Declare the identifier of the global variable in the function a = 200 print("use global After modifying the global variable:%d"%a) text1() text2() text3() #Execution results: ''' Before modification: 123 Modified: 666 a The value of is: 100 use global After modifying the global variable: 200 '''
⑦ Anonymous function:
- lambda expressions
rs1 = lambda x,y: x if x>y else y rs2 = (la4mbda x,y: x if x>y else y)(10,5) print(rs1(10,5)) print(rs2) #Execution results: ''' 10 10 '''
⑧ Recursive function:
- The function calls itself
def digui(n): if n == 1: return 1 else: return n*digui(n-1) print(digui(5)) #Execution results: ''' 120 '''
⑨ Some built-in functions:
- cmp(a,b)
- It is used to judge the size relationship between a and b. A < b returns - 1, a==b returns 0, and a > b returns 1
- eval('')
- Used to execute a string expression and return the value of the expression
-
a,b = 10, 6 print(eval('a*b + pow(b,2) - 66')) # 30
- all(xxx)
- If the parameter list contains False and 0, it returns False; otherwise, it returns True
-
li=[0,1,2] print(all(li)) # False
- any(xxx)
- If the parameter list is False, empty, or 0, False is returned; otherwise, True is returned
-
li=[0,1,2] print(any(li)) # True
- xxx.sort()
- Only sort the list, directly modify the original object, and the default is ascending
- Parameters:
- key=len: sort by string length
- key=str.lower: ignore case sorting
- reverse=True: change to descending order
- sorted(xxx)
- Sort all iteratable objects. Instead of changing the original object, a new list is returned. When the parameter reverse=True, the sorting order is descending
- zip(xx,xx,...)
- The element of the corresponding index position in the sequence is stored as a primitive ancestor, which can be forcibly converted to list output
-
li=['a','b','c'] ls=['I','you','he'] print(list(zip(li,ls))) # [('a ',' I '), ('b', 'you'), ('c ',' him ')]
- enumerate()
- Returns an enumeration object used to combine a traversable data object (such as list, ancestor, string) into an index sequence
-
li=['you','really','food'] for item in enumerate(li,1): print(item,end=' ') # (1, 'you') (2, 'true') (3, 'dish')
- hasattr(x,x)
- Used to determine whether an object contains corresponding attributes
-
class hasattrDemo: a = 1 demo = hasattrDemo() print(hasattr(demo,'a'),hasattr(demo,'b')) # True False
- isinstance(a,b)
- It is used to judge whether a is type b, similar to type()
- vars()
- A dictionary object that returns the properties and property values of an object