程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

6.1_ 7 Python3. X entry P7 [function]

編輯:Python

Related links

  • Catalog
  • Mac M1 Python Environment building
  • Python3.x introduction P1 【 Basics 】 notes 、 identifier 、 Variable 、 data type
  • Python3.x introduction P2 【 Basics 】 Operator
  • Python3.x introduction P3 【 Basics 】 Process statement 【 Loop structure 】
  • Python3.x introduction P4 【 Basics 】 Variable sequence ( list list、 Dictionaries dict、 aggregate set)
  • Python3.x introduction P5 【 Basics 】 Immutable sequence ( Tuples tuple、 character string str)
  • Python3.x introduction P6 【 String formatting 】 Four ways ( Manual 、%-formatting、str.format()、f-String)
  • Python3.x introduction P7 【 function 】

One 、 Function definition and call

""" @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

Two 、 The parameters of the function

2.1 Parameter passing

""" @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

2.2 Parameter default

""" @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 

2.3 Variable parameters

""" @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 

2.4 Parameters *

""" @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

2.5 A variety of parameters are mixed

""" @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}

3、 ... and 、 Function return value

""" @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}]) '''

Four 、 Scope of variable

""" @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 

5、 ... and 、 Recursive function

5.1 Factorial

""" @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

5.2 Fibonacci function

""" @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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved