Function definition and call:
**def function name (parameter 1, parameter 2): **
'''Function comment'''
print('function body')
return return value
Definition: def keyword switch, followed by a space followed by the function name and parentheses, and finally a colon at the end
def is fixed and immutable
Function name: The function name contains any combination of letters, numbers, and underscores (cannot start with a number)
Function call: return value = function name (parameter 1, parameter 2)
Function return value:
1- The role of return: end the execution of a function
2- First, the return value can be any data type
3- The function can have a return value: if there is a return value, it must be accepted by a variable to have an effect
There can also be no return value:
4- return returns a value (a variable)
5- return returns multiple values (multiple variables): multiple values are separated by commas and returned in the form of a tuple
Accept: You can use one variable to receive, or you can use multiple variables to receive (return only a few variables to use)
The parameters of the function:
1- Actual and formal parameters:
Formal parameters: are the parameters defined when the function is defined
Actual parameters: the parameters passed in when the function is called
2- Pass multiple parameters:
Multiple parameters can be passed, separated by commas.
From the perspective of passing parameters, there are two ways to call a function by passing parameters:
Usage: 1-Positional parameters must be before the keyword parameters
2- Can only be assigned once for a parameter
3- Default parameters:
Usage: Why use default parameters? Set the small change value as the default parameter
Definition: The default parameter can not be passed. When it is not passed, the default value is used. If passed, the default value will be overwritten.
The default value is determined when the function is defined
3- Dynamic parameters:
The redundant parameters passed by position will be received uniformly by args and saved in the form of a tuple
Receive multiple keyword parameters by value by keyword, received by kwargs, and saved in the form of a dict
summary:
Definition: The def keyword starts with the function name and parentheses () after the space.
Parameters: Parentheses are used to receive parameters. If multiple parameters are passed in, separate the parameters with commas.
Multiple parameters can be defined or not defined.
There are many kinds of parameters. If multiple parameter definitions are involved, they should always be defined in the order of positional parameters, *args, default parameters, and **kwargs.
For example, a certain parameter type defaults in the above definition process, and other parameters still follow the above order
Comment: The first statement of the function should be commented.
Function body: The function content starts with a colon and is indented.
Return value: return [expression] End the function. Return without expression is equivalent to returning None
def function name (parameter 1, parameter 2, *args, default parameter, **kwargs):
""" Note: Function and parameter description """
Function body
……
return return value
Advanced learning of python functions
Ternary operator
Result + if + condition + else + result
One, namespace and scope
The essence of the namespace: stores the name and worthy binding relationship
There are three types of namespaces:
Global namespace
Local namespace
Built-in namespace
The order of loading and value selection among the three: (namespace and scope are inseparable)
Loading sequence: built-in namespace (load before running) ->
Global namespace (running: loading from top to bottom) ->
Local namespace (run: load only when called)<
Value:
Called locally: local namespace -> global namespace -> built-in namespace
Call in the global: global namespace -> built-in namespace
Scope:
Why is there a concept of scope:
In order that the variables in the function will not affect the global
The scope is the scope, according to the effective scope can be divided into global scope and local scope
Global scope: Contains built-in name space, global name space, can be referenced anywhere in the entire file, globally effective
Local scope: local namespace, which can only take effect in the local scope
Look at the big picture: use names:
If the global is useful, the global: if the global is not used, the built-in
Two, function nesting and scope chain
Nested function calls:
1 # Nested function call
23 def max2(x,y):45 m = x if x>y else y
67 return m
891011 def max4(a,b,c,d):1213 res1 =max2(a,b)1415 res2 =max2(res1,c)1617 res3 =max2(res2,d)1819return res3
20212223... max4(23,-7,31,11)...
Nested definition: functions defined inside cannot be directly called globally
In order to protect internal functions, make sure that internal functions can only be called in external functions
def animal():
def tiger():print(‘ bark ’)print(‘ eat ’)tiger()animal()
The scope chain of the function:
Third, the essence of the function name (——memory address)
1- Can be quoted
2- Can be used as a container type element
3- Can be used as function parameters and return values (can be used as ordinary variables)
Four, closure
Internal functions contain references to externally-scoped rather than global-acting names. (Function reference to the upper domain name)
def func():
name = ‘eva’
def inner():print(name)
Decorator
The essence of decorator: a closure function
The function of the decorator: extend the function of the original function without modifying the original function and its calling method
**Syntactic sugar: **
1 import time
23 def timer(func):45 def inner():67 start = time.time()89func()1011print(time.time()- start)1213return inner
1415 @ timer# ==> func1 =timer(func1)===>Syntactic sugar
1617 def func1():1819print(‘in func1’)2021func1()
·Open and closed principle: open to expansion and closed to modification
1- Open to expansion
Why should it be open to extensions?
We said that for any program, it is impossible to have all the functions in mind at the beginning of the design and do not make any updates or modifications in the future. So we must allow code expansion and add new features.
2- Closed for modification
Why should it be closed to modification?
As we just mentioned, because a function we wrote is likely to have been delivered to others to use, if we modify it at this time, it is likely to affect other users who are already using the function.
The decorator perfectly follows this open and closed principle.
The main function and fixed format of the decorator: add some functions before and after the function without changing the way the function is called.
Fixed format: (fixed universal format)
1 def timer(func):2345 def inner(*args,**kwargs):6789...What to do before executing the function...10111213 re =func(*args,**kwargs)14151617...What to do after executing the function...18192021return re
22232425 return inner
Decorator with parameters:
def outer(flag):
def timer(func):
def inner(*args,**kwargs):if flag:print("What to do before executing the function")
re =func(*args,**kwargs)if flag:print("What to do after executing the function")return re
return inner
return timer
@ outer(False)
def func():print(111)func()
Multiple decorators decorate the same function:
def wrapper1(func):
def inner():print(‘wrapper1,before func’)func()print(‘wrapper1,after func’)return inner
def wrapper2(func):
def inner():print(‘wrapper2,before func’)func()print(‘wrapper2,after func’)return inner
@ wrapper1
@ wrapper2
def f():print(‘in f’)f()
Recursion and bisection algorithm
Recursion: call the function itself in a function
1 import sys
23 print(sys.setrecursionlimit(100000))
Recursively implement a three-level menu:
1 menu ={2'Beijing':{3'Haidian':{4'Wudaokou':{5 ‘soho’:{},6'NetEase':{},7 ‘google’:{},8},9'Zhongguancun':{10'iqiyi':{},11'Car House':{},12 ‘youku’:{},13},
14 'Shangdi':{15'Baidu':{},16},17'Changping':{18'Shahe':{19'Old Boy':{},20'Beihang':{},21},
22 'Tiantongyuan':{},23'Huilongguan':{},24},25'Chaoyang':{},26'East City':{},27},
28 'Shanghai':{29'Minhang':{30'People's Square':{31'Fried Chicken Shop':{}32},33},34'Pudong':{},35},36'Shandong':{},37}3839 def three(dic):40for key in dic :41print(key)42 k =input(“>>>>>>>>”)43if k in dic:44three(dic[k])45three(dic)
Binary search algorithm:
1 l =[2,3,5,10,15,16,18,22,26]23 def find( l,aim,start,end ):45 mid =( end+start )// 267if(l[mid]> aim):89 end = mid
1011 returnfind(l,aim,start,end)1213elif(l[mid]< aim):1415 start = mid
1617 returnfind(l,aim,start,end)1819else:2021return mid
2223 print(find( l,15,start=0,end=len(1)-1))
Recommended Posts