码迷,mamicode.com
首页 > 编程语言 > 详细

python 函数

时间:2018-04-05 22:08:36      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:call   line   blog   注意   lin   通用   font   family   for   

函数是一个通用的程序结构部件,是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

定义一个简单的函数:

>>> def test(a):        #创建一个函数,函数名是test。
	for i in a:
            print(i)
>>> test((1,2,3,4,5))   #使用test()调用函数,同时往里面传一个参数(元组)。
1
2
3
4
5
>>> test([‘a‘,‘b‘,‘c‘,‘d‘]) #使用test()调用函数,往里面传一个参数(列表)。
a
b
c
d

 


 

参数形式:

不传参数

>>> def fun1():       #定义一个不传参的函数。
    print(‘不能传参数:‘)
    for i in range(1,10):
        print(i)

        
>>> fun1()              #调用函数。
不能传参数:
1
2
3
4
5
6
7
8
9
>>> fun1(‘a‘)        #传一个参数,结果会报错。
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    fun1(‘a‘)
TypeError: fun1() takes 0 positional arguments but 1 was given
>>>  

必备参数

>>> def fun2(a):    #这个函数必须传参数
    print(‘必须传参数:‘)
    for i in range (2,a):
        print(i)

        
>>> fun2(8)         #调用函数,并且传一个参数。函数里面的range(2,a),传入参数 ‘8‘,就变成了range(2,8)
必须传参数:
2
3
4
5
6
7
>>> 

默认参数。

>>> def fun2(a=6):    #定义一个可选参数的函数,因为参数默认有值。
    print(‘默认参数:‘)
    for i in range (2,a):
        print(i)

        
>>> fun2()         #调用函数,没有传参数。
默认参数:
2
3
4
5
>>> fun2(8)    #因为是可选参数的函数,所以也可以定义一个参数。
默认参数:
2
3
4
5
6
7
>>> fun2(a=12)  #也可以使用 “a=12” 这种方式传参数。
默认参数:
2
3
4
5
6
7
8
9
10
11
>>> 

可选参数

def fun4(*arg),这里重要的是  " * 号 ",后边的arg只是一个约定俗成的名称。注意:调用函数时也可以添加 “* 号”这样可以对参数进行 “解包”

>>> def fun4(*arg):    #有 “* 号” 开始的参数,意味着可以在这个函数里传多个或者0个参数
	print(‘可传0个或者多个参数:‘,arg)
	
>>> fun4()            #调用函数,不传参数
可传0个或者多个参数: ()
>>> fun4(1)
可传0个或者多个参数: (1,)            #(1,)证明是元组,因为元素1后边有个 ‘,号‘
>>> fun4(1,‘a‘)
可传0个或者多个参数: (1, ‘a‘)        #   #传多个参数
>>> fun4(1,{‘a‘:1})
可传0个或者多个参数: (1, {‘a‘: 1})

 >>> fun4(1,*{‘a‘:1})   #这里调用函数时,在其中一个字典参数前面添加了一个 "* 号"(*{‘a‘:1}),这个"* 号"把里面的壳去掉,结果指输出字典的 “键”
 可传0个或者多个参数: (1, ‘a‘)

 >>> fun4(1,[‘a‘,1])
 可传0个或者多个参数: (1, [‘a‘, 1])

 

 >>> fun4(1,*[‘a‘,1])   #这使用"* 号"把列表里面的壳去掉(解包)。
 可传0个或者多个参数: (1, ‘a‘, 1)

  

python 函数

标签:call   line   blog   注意   lin   通用   font   family   for   

原文地址:https://www.cnblogs.com/longxd/p/8724329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!