当前位置:网站首页>XV Function definition and call
XV Function definition and call
2022-07-06 12:57:00 【Name it casually】
Catalog
3、 ... and . Function creation
Four . Parameter passing for function calls
5、 ... and . Memory analysis of function calls
6、 ... and .return When the function returns multiple values , Result is tuple
7、 ... and . The return value of the function
8、 ... and . Parameter definition of function
One . What is a function
· A function is a piece of code that performs a specific task to complete a specific function
Two . Why function is needed
· Code reuse
· Hide implementation details
· Improve maintainability
· Improve readability, easy to debug
3、 ... and . Function creation
def Function name ( Input parameters ):
The body of the function
return xxx
Function creation :
def sum(a,b):
c =a+b
return print(c)
Function call :
sum(10,20)
Print :
30
-----------------------------------------------
def sum(a,b):
c =a+b
return c
print(sum(10,20))
Four . Parameter passing for function calls
- Location parameter
- The argument is passed according to the position corresponding to the formal parameter
def calc(a,b):
calc(10,20) #10 Corresponding a,20 Corresponding b
- Keyword arguments
- Pass arguments according to the formal parameter name
def calc(a,b):
calc(b=10,a=20)
5、 ... and . Memory analysis of function calls
''' During a function call , Pass parameters If it's an immutable object , Changes in the function body do not affect the value of the argument If it's a mutable object , Changes in the function body will affect the value of the argument '''
n1=11
n2=[22,33,44]
print('n1:',n1)
print('n2:',n2)
print('------------------------------------------------')
def fun(arg1,arg2):
print('arg1:',arg1)
print('arg2:',arg2)
arg1=100
arg2.append(10)
print('arg1:',arg1)
print('arg2:',arg2)
fun(n1,n2)
''' During a function call , Pass parameters
If it's an immutable object , Changes in the function body do not affect the value of the argument
If it's a mutable object , Changes in the function body will affect the value of the argument
'''
print('-------------------------------------------------')
print('n1',n1)
print('n2',n2)
Print :
n1: 11
n2: [22, 33, 44]
------------------------------------------------
arg1: 11
arg2: [22, 33, 44]
arg1: 100
arg2: [22, 33, 44, 10]
-------------------------------------------------
n1 11
n2 [22, 33, 44, 10]
6、 ... and .return When the function returns multiple values , Result is tuple
def fun2(num):
odd=[]
even=[]
for i in num:
if i % 2:
odd.append(i)
else:
even.append(i)
return odd,even
lis=[1,2,3,4,5]
print(fun2(lis))
Print :
([1, 3, 5], [2, 4])
---------------------------------------------
def fun2(num):
odd=[]
even=[]
for i in num:
if i % 2:
odd.append(i)
else:
even.append(i)
return odd
lis=[1,2,3,4,5]
print(fun2(lis))
Print :
[1, 3, 5]
7、 ... and . The return value of the function
- If the function does not return a value 【 After the function is executed , There is no need to provide data to the caller 】return You can omit it
- The return value of the function , If it is 1 individual , Direct return type
- The return value of the function , If more than one , The returned result is a tuple
- When a function is defined , Whether to return a value , As the case may be
def fun1():
print("hello")
fun1()
def fun2():
return 'hello,word'
print(fun2())
def fun3():
return 'hell','word'
print(fun3())
Print :
hello
hello,word
('hell', 'word')
8、 ... and . Parameter definition of function
1. Function defines default value parameters
- When a function is defined , Set default values for parameters , Arguments need to be passed only if they do not match the default values
def fun1(a,b=10):
print(a,b)
fun1(30)
fun1(30,20)
Print :
30 10
30 20
2. Variable number of position parameters *
- When defining a function , When the number of location arguments passed may not be determined in advance , Use variable position parameters
- Use * Define a variable number of positional parameters
- The result is a tuple
- When there are multiple parameters , Only the last parameter can be defined *
- * and ** When used at the same time , Need to be * before ** After
- Each function can only have 1 individual
def fun1(*a):
print(a)
fun1(10,220,30)
Print :
(10, 220, 30)
----------------------------
def fun1(a,*b):
print(a,b)
fun1(10,220,30)
Print :
10 (220, 30)
- Reversible call , Turn the elements in the list into arguments and pass them in *list
- The elements in the list need to correspond to the number of parameters in the function
def fun1(a,b,c):
print(a,b,c)
lis=[10,20,30]
fun1(*lis)
Print :
10 20 30
3. Variable number of keyword parameters **
- When defining a function , When the number of keyword arguments passed cannot be determined in advance , Use variable keyword parameters
- Use ** Define a variable number of keyword parameters
- The result is a dictionary
- When there are multiple parameters , Only the last parameter can be defined **
- * and ** When used at the same time , Need to be * before ** After
- Each function can only have 1 individual
def fun1(**a):
print(a)
fun1( Xiao Ming =10, petty thief =20)
Print :
{' Xiao Ming ': 10, ' petty thief ': 20}
-----------------------------------
def fun1(a,**b):
print(a,b)
fun1(10, Xiao Ming =10, petty thief =20)
Print :
10 {' Xiao Ming ': 10, ' petty thief ': 20}
------------------------------------
def fun1(*a,**b): #* and ** When used at the same time , Need to be * before ** After
pass
def fun1(**a,*b): # Report errors
pass
- Reversible call , Turn the elements in the list into arguments and pass them in **dict
- The elements in the list need to correspond to the number of parameters in the function
- key The value needs to be consistent with the parameter name in the function
def fun1(a,b,c):
print(a,b,c)
dic={"a":50,"b":20,"c":60}
fun1(**dic)
Print :
50 20 60
4.def fun1(a,b,*,c,d):# Add * Number , representative * The parameters after No. can only be passed by keywords
def fun1(a,b,*,c,d):
print(a)
print(b)
print(c)
print(d)
fun1(10,20,c=30,d=40)
Print :
10
20
30
40
---------------------------
def fun1(a,b,*,c,**d): # Sure
pass
def fun1(a,b,*,c,*d): # Can not be
pass
边栏推荐
- [algorithm] sword finger offer2 golang interview question 6: sum of two numbers in the sorting array
- Usage differences between isempty and isblank
- 【无标题】
- 【rtklib】在rtk下使用抗差自适应卡尔曼滤波初步实践
- The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
- 1041 be unique (20 points (s)) (hash: find the first number that occurs once)
- Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance
- [算法] 劍指offer2 golang 面試題2:二進制加法
- Unity3d camera, the keyboard controls the front and rear left and right up and down movement, and the mouse controls the rotation, zoom in and out
- [算法] 剑指offer2 golang 面试题9:乘积小于k的子数组
猜你喜欢
Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
Unity3D基础入门之粒子系统(属性介绍+火焰粒子系统案例制作)
[algorithm] sword finger offer2 golang interview question 4: numbers that appear only once
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
[算法] 劍指offer2 golang 面試題2:二進制加法
第一人称视角的角色移动
FairyGUI简单背包的制作
KF UD分解之UD分解基础篇【1】
Unity3d, Alibaba cloud server, platform configuration
[GNSS data processing] Helmert variance component estimation analysis and code implementation
随机推荐
There is no red exclamation mark after SVN update
Basic DOS commands
isEmpty 和 isBlank 的用法区别
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
MySQL 三万字精华总结 + 面试100 问,吊打面试官绰绰有余(收藏系列
The master of double non planning left the real estate company and became a programmer with an annual salary of 25W. There are too many life choices at the age of 25
Office prompts that your license is not genuine pop-up box solution
使用rtknavi进行RT-PPP测试
FairyGUI复选框与进度条的组合使用
Meanings and differences of PV, UV, IP, VV, CV
How to improve the deletion speed of sequential class containers?
FairyGUI摇杆
Prove the time complexity of heap sorting
Problems and solutions of robust estimation in rtklib single point location spp
[algorithm] sword finger offer2 golang interview question 12: the sum of the left and right sub arrays is equal
Mysql database index
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
Chromatic judgement bipartite graph
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)