Python基础之函数

1.函数定义

def test():
    print ('hello world!')
test()

2.函数参数:

 a.不带参数

def test():
    print ('hello world!')
test()

 b.一个参数

def test(name):
    print ('hello %s!' %(name))
test('aimar')

#name 即形参
#aimar字符串即实参

 c. 二个参数

def test(name,age):
    print ('hello %s! your age is:%d' %(name,age))
test('aimar',18)

hello aimar! your age is:18

 d. 默认参数

def test(name,age=18):
    print ('hello %s! your age is:%d' %(name,age))
test('aimar')

hello aimar! your age is:18

#不传递第二个参数,调用函数时默认取值为函数参数的默认值

  e.指定参数(制定参数时,参数的顺序无关紧要)

def test(name,age):
    print ('hello %s! your age is:%d' %(name,age))
test(age=18,name='aimar')
hello aimar! your age is:18

#函数传递时,指定参数名和值即可,顺序可改变

  f.可变长参数

def test(arg1,*arg2):
    print ('arg1: ',arg1)
    for arg in arg2:
        print ('arg2: ',arg)
test(1,2,3)

arg1:  1
arg2:  2
arg2:  3

# *arg2代表不定长的变量参数,可理解为传递的是元组

  

def test(arg1,**arg):
    print ('arg1:',arg1)
    for k in arg:
        print ('%s: %s' %(k,arg[k]))

test(arg1=1,arg2=2,arg3=3)

arg1: 1
arg2: 2
arg3: 3

# **arg可理解为传递的是字典参数,不定长

 g.return 语句(不带参数的return语句返回none,如上述示例.带参数的返回该参数值)

def test(a,b):
    c = a + b
    return c
d = test(1,2)
print (d)

3

  

   

posted @ 2018-03-12 08:51  2240930501  阅读(133)  评论(0编辑  收藏  举报