Python在入门-自学笔记-10函数

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}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值