Python零基础入门自学笔记
参考教程【Python教程】《零基础入门学习Python》最新版@B站@鱼C-小甲鱼
本文记录的主要是Python中函数的使用。
0.创建和调用函数
def myfunc(): #创建时,def 函数名():
for i in range(3):
print('Hello World!')
myfunc() #调用时,写函数名加括号就可以了
'''
Hello World!
Hello World!
Hello World!
'''
1. 参数
1.0 返回值
def div(x,y):
if y == 0:
return '除数不能为0!'
return x / y
div(4,2) #2.0
div(4,0) #'除数不能为0!'
1.1 位置参数:形式参数、实际参数
def myfunc(name,times): #创建时,def 函数名(形参名):
for i in range(times):
print(f'Hello {name}!')
myfunc('World',5) #调用时,函数名(实参名)
'''
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
'''
- / 左侧必须使用位置参数。
help(abs)
abs(x, /)
1.2 关键字参数
- 必须在位置参数之后
def myfunc(name,times):
for i in range(times):
print(f'Hello {name}!')
myfunc(times = 5, name = 'World')
- * 右侧必须使用关键字参数
def abc(a, *, b, c):
print(a, b, c)
abc(1, 2, 3) #会报错
abc(1, b=2, c=3) #1,2,3
1.3 默认参数
- 应该在最后
def myfunc(a, b,c = 'szd' ): #不改就是默认的,使用就覆盖
return ''.join((a,b,c))
myfunc('ftcy','ttl') #'ftcyttlszd'
myfunc('ftcy','hthz','kjh') #'ftcyhthzkjh'
1.4 收集参数
1.4.0 形参前面加 *
def myfunc(*xingcan):
print('有{}个参数。'.format(len(xingcan)))
print('第2个参数是{}'.format(xingcan[1]))
myfunc('cy','ftcy')
'''
有2个参数
第2个参数是ftcy
'''
1.4.1 收集成一个元组
def myfunc(*xingcan):
print(xingcan)
myfunc(1,2,3) #是一个元组
'''
(1,2,3)
'''
1.4.2 收集参数和关键参数
def myfunc(*args, a, b):
print(args, a, b)
myfunc(1,2,3,a=4,b=5)
#(1, 2, 3) 4 5
1.4.3 组成字典
def myfunc(**zidian):
print(zidian)
myfunc(w=5, x=3, j=1)
#{'w': 5, 'x': 3, 'j': 1}
1.4.4 综合
def myfunc(a, *b, **c): #位置参数,*收集参数,**字典
print(a,b,c)
myfunc(1,2,3,4,x=5,y=6)
#1 (2, 3, 4) {'x': 5, 'y': 6}