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

Python notes 11- functions, return values, anonymous functions

編輯:Python

One 、 function / Method

1. summary

 In a complete project , Some functions may be used repeatedly , If you encapsulate recurring code into functions , If you want to continue using this function in the future, you can directly use the function , in addition , If you want to modify the requirements , Just modify the function

The essence : Encapsulation of certain special functions

advantage :

a. Simplify the code structure , Improve the modularity of the application
b. Improved code reusability
c. Improved code maintainability
# demand : Find the area of a circle
# 1.
r1 = 45
area1 = 3.14 * r1 ** 2
print(area1)
r2 = 10
area2 = 3.14 * r2 ** 2
print(area2)
r3 = 5
area3 = 3.14 * r3 ** 2
print(area3)
# 2. Optimize
def area(r):
return 3.14 * r ** 2
print(area(45))
print(area(10))
print(area(5))

2. Definition

grammar :

def Function name ( Variable 1, Variable 2....):
The body of the function
return Return value

explain :

a.def It's a keyword , yes definition Abbreviation , Specifically define functions
b. Function name : Just follow the rules and specifications of legal identifiers , Try to see the name and know the meaning
c.( Variable 1, Variable 2....): It's called a formal parameter , It's a list of parameters , Are just variables that have no assignment
d. The body of the function : Encapsulate some special functions
e.return It's a keyword , Said to return to , Can only be used in functions , Represents the end function , Can be used alone , You can also carry data , When carrying data , Means the return value of the function
f. Return value : Constant , Variable , expression
g. The definition of a function is divided into two parts : Function declaration and function implementation
h. Variable 1, Variable 2.... and return Return value It can be selectively omitted according to specific requirements
"""
def Function name ( Parameters ):
The body of the function
return Return value
"""
"""
Be careful :
a. In actual project development , In general, different functions are encapsulated into different functions
b. The process of function definition , It is equivalent to loading a function into memory , Defining a function is equivalent to defining a variable , The function name is equivalent to a variable name
c. After the function is defined , If not used 【 call 】, The code will not be executed
"""
# print('start')
# 1. No parameter no return value
def func1():
print("11111")
# print('end')
# 2. Return value with parameter or not
def func2(a):
print("22222")
# 3. No parameter return value
def func3():
print("33333")
return 10
# 4. With parameter and return value
def func4(a):
print("444444")
return 10
# Expand
num = 10
print(type(num)) # <class 'int'>
print(type(func4)) # <class 'function'>

3. call

def Function name ( Formal parameters ):

 The body of the function

Syntax of the calling function : Function name ( The actual parameter )

Formal parameters : Appears in the declaration section of the function , It's called formal parameter for short , It can be understood as a variable waiting for assignment

The actual parameter : Appears in the call part of the function , It's called argument for short , An argument is the data assigned to a formal parameter

The process of calling a function is actually the process of transferring parameters

The process of transferring parameters : The process of assigning a formal parameter to an argument , If there is no formal parameter , There are no arguments

print('start')
# 1. Call directly
def func1():
print("11111")
func1()
print('end')
def func2(a):
print("22222",a)
func2(34)
def func3():
print("33333")
return 10
func3()
def func4(a):
print("444444",a)
return 10
func4('abc')
print("*" * 50)
# 2. Mutual invocation
def show1():
print("show~~~11111")
show3()
def show2():
print("show~~~22222")
def show3():
show2()
print("show~~~33333")
show1()
# 3. Malicious call , Be careful : Avoid writing the following function calls
# a
# def f1():
# print("hello")
# f1()
# f1()
# b
# def f1():
# print("hello~~~~1111")
# f2()
# def f2():
# print("hello~~~2222")
# f1()
# f1()
"""
Be careful :
a. Once the function is defined , Manual call required , Otherwise, the function body cannot be executed
b. During code execution , Once you encounter a function call , The corresponding function body will be executed first , When the function is finished executing ,
Return to the location of the function call , Continue with the rest of the code
c. Functions can be called directly , You can also call each other between functions , You can also apply function calls to if Statement or operation expression
"""

4. Parameters

4.1 Basic use

# 1. When encapsulating a function , Whether to set parameters
# The basis of judgment : Check whether there are unknown items involved in the requirements
# a. Encapsulate a function , Find the sum of two numbers
def add(num1,num2):
total = num1 + num2
print(total)
# b. Encapsulate a function , Realize the ascending sort of the number list
def mysort(numlist):
numlist.sort()
print(numlist)
# 2. When a function is called , Matters needing attention when assigning formal parameters with arguments
add(34,67)
mysort([345,17,10])
# 3.
# a. Required parameters
def func1(num1,num2):
t = num1 + num2
print(t)
func1(29,10)
# b. Default parameters
def func2(num1,num2=0):
t = num1 + num2
print(t)
func2(29)
func2(29,10)
# c. Key parameters
def func3(num1,num2=0):
print(num1,num2)
t = num1 + num2
print(t)
func3(num2=5,num1=76)
# d. Indefinite length parameter
# *x:x Treat as tuples
def func41(*num): # pack
print(num) # Tuples
print(*num) # unpacking
func41()
func41(34,56)
func41(23,5,7,8,9)
# **x:x Treat as a dictionary
def func42(**num): # pack
print(num)
func42()
func42(x=10,y=20)
"""
summary :
a. The number of arguments and formal parameters needs to match
b. According to the implementation of the function body , The types used in the implementation and requirements need to match
"""

4.2 Parameter classification

Parameter classification :

  • Required parameters : Commonly used
  • Default parameters
  • Key parameters
  • Indefinite length parameter 【 Variable parameters 】
  • # 1. Required parameters
    # a. Be careful 1: When transferring required parameters , Be sure to match the quantity
    def func1():
    print("func~~~1111")
    func1()
    # func1(34) # TypeError: func1() takes 0 positional arguments but 1 was given
    # b
    def func2(a):
    print("func~~~222",a)
    # func2() # TypeError: func2() missing 1 required positional argument: 'a'
    func2(10)
    func2("abc")
    # c. Be careful 2: When transferring required parameters , Be sure to pay attention to the sequence matching
    def func3(name,age):
    print(f" full name :{name}, Age :{age}")
    # func3(18,"jack")
    func3("jack",18)
    # d. Be careful 3: When transferring required parameters , Be sure to pay attention to type matching
    def func4(name,age):
    print(" full name :%s, Age :%d" % (name,age))
    # func4("aaa","gahjg") # TypeError: %d format: a number is required, not str
    func4(" Zhang San ",10)
    print("*" * 30)
    # 2. Default parameters
    # a. Be careful 1: The default parameter is reflected in the formal parameter
    def test1(a,b = 0): # a Is a required parameter ,b Is a default parameter
    print(a,b,a + b)
    # Be careful 2: Formal parameters use default parameters , If the actual parameter is given to the parameter and no parameter is passed , The default value is used
    test1(3)
    test1(3,5) # 5 Will give b Reassign
    # b.
    def test2(a = 0,b = 0,c = 0):
    print(a,b,c)
    test2()
    test2(2,6)
    test2(3,4,6)
    def test3(a,b = 0,c = 0):
    print(a,b,c)
    test3(6)
    def test4(a,b,c = 0):
    print(a,b,c)
    test4(6,3)
    # Be careful 3: If there are more than one formal parameter , You can mix required parameters with default parameters , But in the formal parameters , The default parameter is written later
    # def test4(a,b = 0,c): # SyntaxError: non-default argument follows default argument
    # print(a,b,c)
    # test4(6,3)
    # Be careful 4: The meaning of the default parameter is to simplify the function call
    # end The default value is \n
    print(45)
    print(60)
    # print(34,end="*")
    # 3. Key parameters
    # Be careful 1: Keyword parameters are embodied in the arguments
    def check1(name,age,score):
    print(f" full name :{name}, Age :{age}, achievement :{score}")
    # check1("jack",18,100)
    # check1(18,"jack",100) # Illogical , full name :18, Age :jack, achievement :100
    # Be careful 2: You can use keyword parameters to transfer parameters without matching order , however , The keyword should be consistent with the variable name of the formal parameter
    check1(age=18,name="jack",score=100) # full name :jack, Age :18, achievement :100
    # check1(age=18,name1="jack",score=100) # TypeError: check1() got an unexpected keyword argument 'name1'
    check1('aaa',score=88,age=10)
    check1("bbb",12,score=99)
    # Be careful 3: In the argument , Keyword parameters can only be written after parameters
    def check2(name,age,score):
    print(f" full name :{name}, Age :{age}, achievement :{score}")
    # check2(name="tom",10,66) # SyntaxError: positional argument follows keyword argument
    # check2(10,66,name="tom") # TypeError: check2() got multiple repeat values for argument 'name'
    # Be careful 4: Default parameters and keyword parameters can be used in combination
    def check3(name,age,score=0):
    print(f" full name :{name}, Age :{age}, achievement :{score}")
    check3("jack",10)
    check3("jack",10,67)
    check3(name="jack",age=10,score=67)
    check3("jack",age=10,score=67)
    check3("jack",10,score=67)
    print("*" * 30)
    # 4. Indefinite length parameter / Variable parameters : Variable length parameters are acceptable
    # a.*xxx,
    # Be careful 1:*xxx,xxx Treated as a tuple
    def text1(*num):
    print(num)
    text1()
    text1(34)
    text1(34,56,67,68,7,8)
    text1(34,56,67,68,7,8,"abnfa",True)
    # Be careful 2: Required parameters can be mixed with variable length parameters
    def text2(num1,*num2):
    print(num1,num2)
    text2(10,45,56,67,6,8,7,8)
    # Be careful 3: If the variable length parameter appears in front of the formal parameter list , You can transfer parameters in combination with keyword parameters
    def text3(*num1,num2):
    print(num1,num2)
    # text3(10,45,56,67,6,8,7,8) # TypeError: text3() missing 1 required keyword-only argument: 'num2'
    text3(10,45,56,67,6,8,7,num2 = 8)
    # Be careful 4:*xxx It can only be used once in the formal parameter list
    # def text4(*num1,*num2):
    # print(num1,num2)
    # text4(45,57,6,77,8)
    print("*" * 30)
    # b.**xxx
    # Be careful 1:**xxx,xxx Will be treated as a dictionary
    def f1(**num):
    print(num)
    # Be careful 2: to **xxx Parameter transfer of , You have to use key=value In the way of transmission
    f1(x=10,y=20,z=30) # {'x': 10, 'y': 20, 'z': 30}
    # Be careful 3:**xxx It can only appear once in the formal parameters of the same function
    # def f2(**num1,**num2):
    # print(num1)
    # f2(x=10,y=20,z=30)
    # Be careful 4:*xxx and **xxx Can be used at the same time , however , Each can only be used once
    def f3(*num1,**num2):
    print(num1,num2)
    f3(45,45,65,7,67)
    f3(45,45,65,7,67,a=4,b=467,fag="abc")
    f3(a=4,b=467,fag="abc")
    # Be careful 5: In general , If *xx and **xxx Use a combination of , Name it :*args,**kwargs
    

4.3 Parameter passing

"""
【 Interview questions 】 The difference between value passing and reference passing
Value passed : When passing on the ginseng , What is passed is an immutable data type , Such as :int float bool str tuple, When the formal parameters change , No effect on arguments
reference : When passing on the ginseng , Variable data types are passed , Such as :list dict set, When the element in the formal parameter changes , The arguments are modified as they are
"""
# 1. Value passed
def func1(num):
num = 100
print(f"num={num}")
n = 66
func1(n)
print(f"n={n}") # 66
"""
num=100
n=66
"""
# 2. reference
def func1(num):
num[1] = 100 # The arguments are modified as they are
# num = 100 # The arguments are not modified
print(f"num={num}")
n = [2,3,4]
func1(n)
print(f"n={n}")
"""
num=[2, 100, 4]
n=[2, 100, 4]
"""

Two 、 Function basis 【 Focus on mastering 】

1. Return value

return Use of keywords , Be careful :return Can only be used in functions

# The return value of the function : The result of function execution , Where to call a function , Where you can connect the return value
# 1. Be careful 1: If the return value is not set for the function , Default return None
def func1():
print('1111')
r1 = func1() # explain :r1 = func1 The return value of the function
print(r1) # None
# 2. Be careful 2:return It's a keyword , Can be used alone , Represents the end function ,
# therefore return hinder , and return There is no chance for peer code to be executed , In the and return Generally, the code is not written after the level
# a.
def func21(a,b):
print('22222~~~1111')
return # return It will certainly be carried out
# print("over") # Certainly not , There is never a chance of execution
func21(4,2)
print('*' * 30)
# b
# Be careful 3: and return In case of uneven grades ,return The following code may have a chance to execute
def func22(a,b):
print('22222~~~~2222')
if a + b > 5:
return # return Possible implementation
print("over") # There are opportunities for implementation
func22(4,2)
# c.
def func31():
for i in range(3): # 0 1 2
for j in range(5): # 0 1 2 3 4
print(f"{i}={j}")
if j == 2:
break # break End the current cycle
print('over~~31')
func31()
"""
0=0
0=1
0=2
1=0
1=1
1=2
2=0
2=1
2=2
over~~31
"""
# Be careful 4: No matter return Write in how many levels of nested loops , As long as the implementation of the return, The function ends immediately
def func32():
for i in range(3):
for j in range(5):
print(f"{i}={j}")
if j == 2:
return
print('over~~32')
func32()
"""
0=0
0=1
0=2
"""
# 3.return xxx
# Be careful 5:return xxx Indicates that the specified data will be returned after the function is executed
# The return value can be commonly used , Variable , expression
# a
def func41():
return "abc"
r41 = func41()
print(r41)
# b.
def func42(a):
return a + 5
r42 = func42(34)
print(r42)
# c.
def func43(a,b):
return a > b
r43 = func43(3,89)
print(r43)
# d.
def func44(a,b):
return a,b # pack
r44 = func44(23,78)
print(r44) # (23, 78)
# e.
def func45(a,b):
if a > b:
return a
elif a < b:
return b
else:
return " equal "
r45 = func45(56,56)
print(r45)
print("*" * 50)
# 4.return The meaning of
def func51():
num1 = 66 # num1 Can only be used inside a function
print(num1)
func51()
# print(num1 + 5) # NameError: name 'num1' is not defined
def func51():
num1 = 66
return num1
r5 = func51()
print(r5 + 5)
# give an example
list1 = [34,65]
list1.append(10)
print(list1)
r = list1.pop()
print(r)

2. Function exercises

 How to encapsulate functions :
a. Whether to set parameters : Whether there are unknown items involved in the requirements , There are several unknowns involved in the operation
b. Do you need to set the return value : Whether there is any result after the function body is executed perhaps Whether the result needs to be used outside the function
# 1. Encapsulate a function , Verify whether a year is a leap year
def isleapyear(year):
# if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
# return True
# return False
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
r = isleapyear(2021) # isdigit()
print(r)
# 2. Encapsulate a function Gets the number of days in the specified month
def get_days(year,month):
if month in [4,6,9,11]:
return 30
elif month in [1,3,5,7,8,10,12]:
return 31
else:
if isleapyear(year):
return 29
return 28
r2 = get_days(2020,2)
print(r2)
# 9. In the simulation list sort Use , Sort list , Default ascending order , It can also be in descending order
def mysort(numlist,reverse=False):
if reverse:
# Descending
for i in range(len(numlist) - 1):
for j in range(len(numlist) - 1 - i):
if numlist[j] < numlist[j + 1]:
numlist[j],numlist[j + 1] = numlist[j + 1],numlist[j]
else:
# Ascending
for i in range(len(numlist) - 1):
for j in range(len(numlist) - 1 - i):
if numlist[j] > numlist[j + 1]:
numlist[j],numlist[j + 1] = numlist[j + 1],numlist[j]
list1 = [34,56,6,2,34,6]
mysort(list1) # Ascending
print(list1)
ist1 = [34,56,6,2,34,6]
mysort(list1,reverse=True) # Descending
print(list1)

3、 ... and 、 Anonymous functions 【 Focus on mastering 】

Concept : No longer use def This standard form defines the function , But use lambda Expression to create a function , The function has no function name , It is called an anonymous function

grammar :lambda Parameter list : The body of the function

explain :

a.lambda It's just an expression , Implement a simple logic in one line of code , It can simplify the function 【 advantage 】
b.lambda The subject is an expression , Not a block of code , Only limited logic can be encapsulated 【 shortcoming 】
c.lambda Have your own namespace , You cannot access parameters outside your own list or in the global namespace
# 1. Basic use
# a.
def func1():
print('11111')
func1()
print(func1) # <function func1 at 0x103c9c1e0>
print(type(func1)) # <class 'function'>
# b.
# grammar :lambda Parameter list : The body of the function
# Mode one
func2 = lambda : print('2222')
print(func2) # <function <lambda> at 0x1049916a8>
print(type(func2)) # <class 'function'>
# Call anonymous functions
func2()
# Mode two
(lambda : print('2222~~~~~'))()
"""
Definition and call of anonymous function
Mode one :
func2 = lambda : print('2222')
func2()
Mode two :
(lambda : print('2222~~~~~'))()
"""
# Be careful : Whether it's def Defined function , still lambda Defined anonymous functions , After the function definition is complete , Both need to be called manually
# 2. application
# a.
def add1(num1,num2):
return num1 + num2
r1 = add1(3,6)
print(r1)
# Be careful : The return value of an anonymous function can be written directly , No need to rely on return
add2 = lambda num1,num2: num1 + num2
r2 = add2(2,5)
print(r2)
# b.
def isleapyear1(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return ' Leap year '
return ' Ordinary year '
r1 = isleapyear1(2021)
print(r1)
isleapyear2 = lambda year: ' Leap year ' if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else ' Ordinary year '
r2 = isleapyear2(2020)
print(r2)
# c
iseven = lambda num:True if num % 2 == 0 else False
r = iseven(34)
print(r)
# 3. matters needing attention
# Be careful : An anonymous function is still essentially a function , So the default parameters , Key parameters , Variable length parameters can be used
# a
f1 = lambda a,b = 0:a + b
print(f1(4))
print(f1(4,2))
# b.
print(f1(a = 5))
print(f1(a = 5,b = 9))
print(f1(b = 6,a = 5))
# c
f1 = lambda *num:sum(num)
print(f1(34,56,6,7,8))
# 4. Use scenarios
# Commonly used for parameters of other functions , Such as :sort(), Common higher order functions :sorted,map etc.
# demand : List sorted by student grade
students = [
{'name': ' floret ', 'age': 19, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' Mingming ', 'age': 20, 'score': 40, 'gender': ' male ', 'tel':
'15300022838'},
{'name': ' Huazai ', 'age': 18, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' quietly ', 'age': 16, 'score': 90, 'gender': ' Unknown ', 'tel':
'15300022428'},
{'name': 'Tom', 'age': 17, 'score': 59, 'gender': ' Unknown ', 'tel':
'15300022839'},
{'name': 'Bob', 'age': 18, 'score': 90, 'gender': ' male ', 'tel':
'15300022839'}
]
"""
list .sort() How it works
a. If the list element is a number , The bottom is through > or < To compare numbers
b. If the list element is a string , The bottom is through > or < Conduct ASCII Code comparison
c. however , If the element in the list is a dictionary, it is not supported > or < The data of , You need to customize the sorting rules , Format :sort(key= Sorting function )
d. If the custom collation , list .sort(key=func) How it works : Pass the elements in the list to func Parameters of
func The return value of will be used as the basis for sorting 【func The return value of must support > or < Comparison 】
"""
# a.
# def func(subdict):
# return subdict['score']
# students.sort(reverse=True,key=func)
# print(students)
# b.
students.sort(reverse=True,key=lambda subdict:subdict['score'])
print(students)
# 【 Thinking questions 】/【 Interview questions 】
def func():
l = []
for i in range(5):
l.append(lambda x:i * x)
return l
r = func()
print(r[0](2))
print(r[1](2))
print(r[2](2))
print(r[3](2))
print(r[4](2))

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