Related links
""" @author GroupiesM @date 2022/6/29 15:49 @introduction function : A piece of code to complete the specified function advantage : Code reuse 、 Hide implementation logic 、 Improve maintainability 、 Improve readability, easy to debug grammar : def Function name ( Variable 1: type 1, Variable 2: type 2,...): The body of the function Returnee return xxx Grammar shorthand : def Function name ( Variable 1, Variable 2,...): The body of the function Returnee return xxx P.S: 1. There can be no variables , According to the actual business scenario 2. There can be no return body , According to the actual business scenario """
# 1. Defined function ( There is a return value )
def sum(a, b):
c = a * 2 + b
return c
# 1. Call function ( There is a return value )
print(sum(10, 20)) # 40
# 2. Defined function ( No return value )
def print_sum(a, b): print(a * 2 + b)
# 2. Call function ( No return value )
print_sum(10, 20) # 40
""" @author GroupiesM @date 2022/6/29 17:32 @introduction Shape parameter : When defining a function , Defined parameter variables Actual parameters : When you call a function , Parameters passed """
''' Defined function Shape parameter :a,b '''
def sum(a, b):
c = a * 2 + b
return c
''' Call function Actual parameters :10,20 No formal parameter specified , Assign values in the order of function parameters '''
result = sum(10, 20)
print(result) # 40
''' Specify parameter , Assign values as specified '''
result = sum(b=10, a=20)
print(result) # 50
""" @author GroupiesM @date 2022/6/30 10:10 @introduction """
# Shape parameter b Specifies that the default value is 10
def func(a, b=10):
print(a, b)
""" Function call When formal parameters have default values (b=10), 1. If the argument does not pass a value , The default value is used (b=10) 2. If the argument specifies a value (b=30), The specified value is used (30) """
func(100) # 100 10
func(20, 30) # 20 30
# func(a=20, 30) # Report errors - If you specify parameters , All parameters need to be specified
""" @author GroupiesM @date 2022/6/30 10:17 @introduction The rules : 1. from * after , When you call a function , Only keywords can be used to pass parameters One 、 Variable parameters - Positional arguments ( Tuples ) 1. When defining a function , When the number of location arguments passed may not be determined in advance , Use variable position parameters 2. Use * Define a variable number of positional parameters 3. The result is a tuple tuple(v1,v2,...) 4. Reference resources : Decompress tuples tup = (4127, 4098, 8637678) print(14, 'Jack: {}; Sjoerd: {}; ''Dcab: {}' .format(*tup)) # Jack: 4127; Sjoerd: 4098; Dcab: 8637678 Two 、 Variable parameters - Keyword parameters ( Dictionaries ) 1. When defining a function , When the number of keyword arguments passed cannot be determined in advance , Use variable keyword parameters 2. Use ** Define a variable number of keyword parameters 3. The result is a dictionary dict{k1:v1,...} 4. Reference resources : Decompress tuples table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print(6, 'Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}' .format(**table)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678 """
# One 、 Variable parameters - Positional arguments ( Tuples )
def function_tuple(*args):
print(args)
function_tuple(10) # (10,)
function_tuple(10, 20, 30) # (10, 20, 30)
# Two 、 Variable parameters - Keyword parameters ( Dictionaries )
def function_dict(**arg):
print(arg)
function_dict(a=10) # {'a': 10}
function_dict(a=10, b=20, c=30) # {'a': 10, 'b': 20, 'c': 30}
def funciton_test(*arg1,**arg2):
pass
# def funciton_test(*arg1,*arg2): # Two variable parameters , Only... Can appear separately in a function 1 Time
""" @author GroupiesM @date 2022/6/30 10:17 @introduction The rules : 1. from * after , When you call a function , Only keywords can be used to pass parameters """
def function_star(a, b, *, c, d):
print(f'{
a=},{
b=},{
c=},{
d=}')
function_star(10, 20, d=30, c=40) # a=10,b=20,c=40,d=30
""" @author GroupiesM @date 2022/6/30 11:29 @introduction The rules : 1. * and *args Mutually exclusive , Not at the same time def func1(a, * , *args): pass # Report errors """
def func1(a, b): pass
def func2(a, b=10): pass # Functions with default values
func2(10,20)
def func3(*args): pass # Variable parameters - Position parameter
func3(10)
func3(10,)
func3(10,20)
def func4(**args): pass # Variable parameters - Keyword parameters
func4(x=10,y=20)
print('func5')
def func5(a, b, *, c, d, **args2): print(f"{
a=},{
b=},{
c=},{
d=},{
args2=}") # blend
func5(10,20,c=30,d=40,f=50) # a=10,b=20,c=30,d=40,args2={'f': 50}
def func6(*args1, **args2): pass # blend
func6(10,c=50)
print('func7:')
def func7(a, b, *args1, **args2): print(f"{
a=},{
b=},{
args1=},{
args2=}") # blend
func7(10,20,30,d=40) # a=10,b=20,args1=(30,),args2={'d': 40}
print('func8:')
def func8(a, b=10, *args1, **args2): print(f'{
a=},{
b=},{
args1=},{
args2=}') # blend
func8(10,20,30,d=40) # a=10,b=20,args1=(30,),args2={'d': 40}
""" @author GroupiesM @date 2022/6/29 17:44 @introduction The return value of the function When the function returns multiple values , Result is tuple tuple(v1,v2,...) """
# One 、 no return value
def funcOne():
print("hello")
funcOne() # hello
# Two 、 Returns a value
def funcTwo():
return 'hello'
print(funcTwo()) # hello
# 3、 ... and 、 Return multiple values
def funcThree():
return 'hello','python'
print(funcThree()) # ('hello', 'python')
# 3、 ... and 、 Return multiple values ( Split cardinality and even )
def num_split(num: list):
odd = [] # Store odd numbers
even = [] # Store even numbers
obj = [] # Store other types
for i in num:
if type(i) == int:
if i % 2:
odd.append(i)
else:
even.append(i)
else:
obj.append(i)
return odd, even, obj
print(num_split([3, 4, 6, 12, 3.14, 'luna', True, {
'doom': 18}]))
''' test result ([3], [4, 6, 12], [3.14, 'luna', True, {'doom': 18}]) '''
""" @author GroupiesM @date 2022/6/30 11:44 @introduction Scope of variable : 1. The area where the program code can access the variable 2. According to the effective range of variables, they can be divided into : Global variables 、 local variable 2.1 Global variables Variables defined outside the function , It can be used inside and outside the function 2.2 local variable Variables defined and used within a function , Only valid inside a function , Local variables use global Statement , This variable will become a global variable """
# 1. Global variables
name ='luna'
def fun2():
age=16 # 2. local variable
global money # 1. Global variables
money = 10000
# quote 1. Global variables + 2. local variable
print(name,age)
fun2()
''' test result luna 16 '''
# quote 1. Global variables
print(name,money)
''' test result luna 10000 '''
# quote 2. local variable
# print(age) # Local variables cannot be referenced outside a function
""" @author GroupiesM @date 2022/6/30 13:41 @introduction Recursive function : 1. The function body calls the function itself , This function is called a recursive function 2. Recursive function needs : Recursive Commission adjustment 、 Recursive termination condition 3. Call the function once per recursion , Will allocate a stack frame in the stack 4. Every time the function is executed , Will release the corresponding space """
# Case study : Factorial
def factorial(num:int):
if num < 1 :
print(" Parameter error , Please enter greater than 1 The number of ")
return None
if num == 1:
return 1
else:
result = num * factorial(num - 1)
return result
print(factorial(5)) # 120
""" @author GroupiesM @date 2022/6/30 14:13 @introduction Fibonacci function : From the third number , Each number is the sum of the first two numbers The number 1 1 2 3 5 8 13 21 ... Number of recursions 0 0 1 2 3 4 5 6 """
''' @length: List length @lst: By default, the first two values are 1,1 @:return lst: Fibonacci function in list dct: Fibonacci function in dict '''
def fibonacci(length: int, lst=[1, 1], dct={
' The first 1 position ': 1, ' The first 2 position ': 1}, order_number=3):
dct[f' The first {
order_number} position '] = lst[len(lst) - 2] + lst[len(lst) - 1]
lst.append(lst[len(lst) - 2] + lst[len(lst) - 1]) # The sum of the first two
if length == 3:
return lst, dct
else:
result = fibonacci(length - 1, lst, order_number=order_number + 1)
return result
print(fibonacci(10)[0]) # [1, 1, 2, 3, 5, 8, 13]
print(fibonacci(10)[1]) # {1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
22/06/30
M