First, what is a function
A function is a code snippet that can be called, reusable, to implement a single, or related function.
Role of the function:
- Reduced duplication of code and improved modularity of applications
- Keep your code consistent
- Additions and deletions change the code once, simple and rough, easier to expand
First, create a function
1. Define a rule for a function
- function code block starts with the DEF keyword, followed by the function identifier name and ()
- Any incoming parameters and arguments must be placed in the middle of the parentheses, and the parentheses can be used to define the parameters
- The first line of the function statement can optionally use the document string--for storing function descriptions
- Function contents start with a colon, and indent
- return[expression] ends the function, optionally returning a value to the caller. If there is no return, it is equivalent to returning none
Grammar:
1 def function name (parameter list) 2 function body
2. Formal parameters and arguments
Formal parameters: Virtual variables that use formal parameters when defining functions and function bodies. The purpose is to receive the arguments when the function is called, the number of arguments, and the type to correspond to the parameter one by one.
Arguments: Parameters that are passed to the function when the function is called. It can be a constant, a variable, an expression, a function.
Formal parameters do not occupy memory space, and the parametric is allocated only when it is called.
1 Import Time2 defaction1 (n):3 Print('Start action 1.')4 logger (n)5 defAction2 (n):6 Print('Start action 2.')7 logger (n)8 defAction3 (n):9 Print('Start action 3.')Ten logger (n) One deflogger (n): ATime_format ='%y-%m-%d%x' -Time_current =time.strftime (Time_format) -With open ('Log Records','a') as F: theF.write ("%s End Action%s.\n"%(time_current,n)) -Action1 (10) -Action2 (20) -Action3 (30)
3. Parameters of the function
- Required Parameters
- Keyword parameters
- Default parameters
- Indefinite length parameter
- No named parameters
- Have named parameters
Required Parameters
The number and order of required parameters must be consistent at the time of invocation and declaration.
Keyword parameters
A function call uses a keyword argument to determine the value of the passed parameter, matching the parameter value by parameter name, and using the key when the parameter is allowed to be inconsistent with the Declaration in the order of the parameters contained in the call.
Default parameters
When defining a function, set default parameters. When the function is called, the default parameter is set with the value if no value is passed in.
1 defPrint_info (name,age,sex='male'):2 3 Print('name:%s'%name)4 Print('age:%s'%Age )5 Print('sex:%s'%sex)6 return7 8Print_info ('Alex', 18)9Print_info ('Hammer', 40,'female')
Indefinite length parameter
Example 1:
1 defAdd (*args):2 Print('args:', args)3sum =04 forIinchargs:5Sum + =I6 returnsum7 Print('sum:', add (1,2,3,4,5))
Output:
Args: (1, 2, 3, 4, 515
Example 2:
1 defPrint_info (* *Kwargs):2 Print('Kwargs:', Kwargs)3sum =04 forIinchKwargs:5 Print('%s:%s'%(i, kwargs[i]))6 7Print_info (name='Oliver', age=20,sex='female')
Output:
Kwargs: {'name'Oliver'age' ' Sex ' ' female ' }name:oliverage:sex:female
*args receives incoming parameters using tuples, * *Kwargs receives incoming key-value pairs in a dictionary.
4. Return
The function of return:
(1) End Function
(2) return an object
Note the point:
If you do not add a return, none is returned by default.
If return has an object, multiple objects are encapsulated into a tuple.
When a return statement is encountered, execution is stopped and the result is returned.
5. Scope of function
l:local, local scope
E:enclosing, function nesting scope
G:global, global scope
B:built_in,python built-in scopes
Lookup Order: L→e→g→b
Global keywords:
Example: (Declaring a variable in the local scope as the global scope)
1 count =2def outer ():3 global Count # define the scope of count before you print 4 Print (count) # local variable ' count ' referenced before assignment 5 Count =6 print(count)7 outer ()
nonlocal keywords:
Example: (Declaring a variable in the local scope as a enclosing scope)
1 def outer (): 2 Count =3 def Inner ():4 nonlocal count # First declared as enclosing scope 5 count =6 print(count)7 inner ()8 print(count)9 outer ()
In a local scope, you cannot modify a global scope variable.
In Python, only modules, classes, and functions (Def, Lambda) introduce new scopes, and other blocks of code (such as if, try, for, and so on) do not introduce new scopes.
6. High-order function
Pass the function's masterpiece as an argument to another function for use.
1 def f (n): 2 return n3def foo (a,b,func):4 return Func (a) +func (b)5print(foo (1,2,f))
Output: 5
A function can be assigned not only to a value, but also as a function's parameter and as a function's return value.
7. Recursive function
Using recursive functions to print Fibonacci sequences:0 1 1 2 3 5 8 144 233 377 610 987 1597 2584 4181
The first two items are: 0 and 1, starting from the third item each item is the sum of the first two items and therefore available: F (n) = f (n-1) + f (n-2)
1 def Fibo (n): 2 if n <= 2:3 return n-14 return Fibo (n-1) + Fibo (n-2)56print(Fibo (8))
Output: 13
Recursive function Properties:
- Call self function
- There is an end condition
It is important to note that any problem that can be solved by recursion can be solved through the loop, and the efficiency of recursion is lower, the general can only be recursive 998 times, exceeding the error.
8. Built-in functions
Eval ()
The eval () function can not only convert a string to a dictionary, it can also be used as a computer.
1 Print (Eval ('1+3/8*9'))
Output: 4.375
Here are a few of the most important built-in functions:
Filter (function, sequence)
1str = ['a','b','C','D']2 deffun1 (s):3 ifs! ='a':4 returns5RET =filter (FUN1, str)6 Print(List (ret))#ret is an iterator object
Output: [' B ', ' C ', ' d ']
Map (function, sequence)
1str = ['Hello','a','b']2 deffun2 (s):3 returnS +"Alvin"4RET =map (fun2, str)5 Print(ret)#iterator to map object6 Print(List (ret))
Output:
<map object at 0x7f382ca0aba8>['helloalvin'Aalvin ' ' Balvin ']
Reduce (function, sequence, starting_value)
1 from Import Reduce 2 def add1 (x, y): 3 return x + y4print(reduce (ADD1, range (1, 101))) ### 4950 (Note: 1+2+...+99)56print(reduce (ADD1, range (1, 101)) # # 4970 (Note: 1+2+...+99+20)
Output:
50505070
Lambda
1 def Add (A, b): 2 return A + b3 4print Add (2,3)5 6 7 # Anonymous Functions 8 Lambda a,b:a + b9Print Add (2,3)
Python Learning notes--functions