python函数
2019-08-19 08:24
1376 查看
python函数参数类型共有5种
1、必须参数
def start(yourname): print('Hello',yourname) if __name__ == __main__: start('chengxin')
yourname这个参数名是形参可设置多个,姑且认为是为了print语句中数据的传递
实际参数是‘chengxin’这个字符串,如果不传递参数的话系统会报错(形参和实参需要数目相等)
2、默认参数
def isbachelor(yourname,gender = '男',): print(yourname,gender,'单生狗') if __name__ == '__main__': isbachelor('男','chengxin') >>>男 chengxin 单生狗 #运行结果 ----------------------------------------- ----------------------------------------- def isbachelor(gender = '男',yourname): print(yourname,gender,'单生狗') if __name__ == __main__: isbachelor('chengxin')
第二个参数的位置不对会报错,因为默认参数只能跟在必须参数后面
如果形参中默认参数在必须参数之前,那么调用函数时实参中默认参数也应当在前面;
如果形参中默认参数在必须参 数之后,那么调用函数时实参中默认函数应当在后面,否则会报错。
一个参数带参数名,另一个参数不带参数名,其中默认参数必须带参数名
3、可变参数
def isbachelor(gender = '男' ,*yourname): print(gender) print(gender) for i in yourname: print(i) return if __name__ == '__main__': isbachelor('女','tom','Ken') --------------------------------------------------- --------------------------------------------------- def isbachelor(gender = '男' ,*yourname): print(gender) print(gender) for i in yourname: print(i) return if __name__ == '__main__': isbachelor(gender = '女','tom','Ken')
为什么下面一个案例中gender参数用关键字赋值会报错呢?
保险起见:还是不用关键字赋值
4、关键字参数
dir={'name':'miss','age':'18'} def Deaf(school,banji,**other): print('学校:',school,'\n','班级:',banji,'\n','学生信息:',other) if __name__ == '__main__': Deaf('清华','大二',**dir)
PS:关键词参数的实参形式前面是**两个星
5、组合参数
及上面四种参数同时引入函数作为形参,定义参数的顺序必须是:必须参数、默认参数、关键字参数、不定长参数。
相关文章推荐
- 180202—【Python 初识 D9】Python的内建函数 & 工厂函数
- PHP函数 转 PYTHON函数
- python绘图函数
- python: numpy --函数 tile用法
- Python sorted函数详解(高级篇)
- Python:python中math模块中提供的基本数学函数
- Python 函数
- Python的列表等变量的声明必须要在函数定义与函数调用之前
- 5.4Python函数(4):函数参数的定义和调用总结
- 基于Python函数和变量名解析
- linux bash shell 中getopts 命令 和 python 中 getopt 函数的比较总结
- python 2.5.4到python 3的函数变更情况
- python装饰器decorator之计算函数运行时间的例子
- 小学生都能学会的python(函数的进阶)
- Learning Python 010 函数 2
- python基础--字符串常用函数
- 浅谈python函数签名
- Python里的OS模块常用函数说明
- Python内建函数:enumerate
- python 类 函数 的基本操作 以及 垃圾回收机制