Python 函数简介 之二

时间:2023-03-08 19:44:49
Python 函数简介 之二

1.当函数有多个返回值时, 其多个返回值将以元组的形式出现

def test1():
print("in the test1")
return 'end'
def test2():
print("in the test2")
def test3():
print("in the test3")
return 1, 'Hello',['Frank','Lee'],{'name':'Frank'} #返回一个元组 x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z) #结果
in the test1
in the test2
in the test3
end
None
(1, 'Hello', ['Frank', 'Lee'], {'name': 'Frank'}) #元组

2. 有参函数调用---位置调用, 关键字调用

def test(x,y):
print(x)
print(y) test(1,2) #位置调用
print("------------我是分割线------------")
test(y=2,x=1) #关键字调用 #结果:
1
2
------------我是分割线------------
1
2

3. 实参会覆盖形参

def test(x,y=2):
print(x,y) test(1)
test(1,3) #结果
1 2
1 3

4.实参个数少于形参时, 将使用默认的形参

def conn(host,port=3306):
print(host,port,sep=':')
conn("mysql-test") #结果
mysql-test:3306