renran421 发表于 2018-8-16 08:39:44

第八节:python函数

函数的定义:  
def test():
  
    print "hello world!"
  
test()   #调用上面的test函数
  

  
定义一个参数为name的函数:
  
def mingzi(name):
  
    print "hello %s,how old are you?"%name
  
mingzi('darren')         #调用定义的函数
  

  
定义两个参数的函数:
  
def info(name,age):
  
    print "%s,%s"%(name,age)
  
info('darren','23')         #调用两个参数的函数
  

  
给函数添加一个帮助文档:
  
def mingzi(name):
  
    'this is a help doc!'
  
    print "hello %s,how old are you?"%name
  
n="darren"
  
mingzi(n)   #也可以先赋值再调用函数
  

  
>>>import tab
  
>>>import three
  
>>>help(three.mingzi)   #查看自己编写的帮助文档
  

  

  
局部变量和全局变量:
  
局部变量:函数执行结束以后会失去作用。
  
def info (name):
  
    age=22
  
    print 'your name is %s,you old is %s'%(name,age)
  
info('darren')
  

  
全局变量:在函数之外,全局生效。
  
age=26
  
def info (name):
  
    age=22
  
    print 'your name is %s,you old is %s'%(name,age)
  
info('darren')
  

  
声明把全局变量变为局部变量(不建议使用):
  
age=26
  
def info (name):
  
    global age         #声明
  
    age=22
  
    print 'your name is %s,you old is %s'%(name,age)
  
info('darren')
  
print 'age:',age         #此处第一个age:是显示age:并不是变量,后面的才是变量,这是让一个print生成两段内容的用法。
  

  

  
函数的默认参数:
  
def users(username,group='iphone'):          #group='iphone'这里也是一个赋值变量,只不过如果不赋值,默认是iphone。
  
    list={}      #定义一个字典
  
    list=group      #定义username为key,group为value,意思就是修改key的值为变量group
  
    return list
  
print users('wang')
  
print users('wangjia',"dongge")
  

  
多默认值变量:
  
def info (name,age,internation='zhongguo',provice='shandong'):
  
    age=22
  
    print 'your name is %s,you old is %s'%(name,age)
  
    print internation,provice
  
info('darren','age',provice='beijing',internation='meiguo')    #默认赋值的变量可以没有顺序,但是无默认值的变量必须在有默认值得变量的前面。
  

  
函数的关键参数:
  
def fun(a,b=5,c=10):
  
    print a,b,c
  

  
fun(3,7)
  
fun(25,c=24)
  
fun(c=50,a=100)
  

  

  
#重点:函数增加一个特殊参数,可以任意赋多个值。
  
def test(*.args):
  
    print args
  
test('darren','wang','29')
  

  
#把一个字典赋值给函数,字典key对应的值就是变量。
  
def testa (**kargs):
  
    print kargs
  
name_list={
  
'name'='wang',
  
'age'='22',
  
'iphone'='pingguo'
  
}
  
testa(name='darren',age='18',iphone='sanxing')
  

  

  
#有时候我们希望能把函数执行的结果保存下来,这时候就需要return参数:
  
def users(username,group='iphone'):
  
    list={}
  
    list=group
  
    return list
  
yonghu=users('wang','group='linux')
  
print yonghu
  

  
lambda匿名函数:
  
>>> a=lambda x:x+2
  
>>> a(2)
  
4
  
-------
  
a=range(10)
  
map(lambda x:x**2,a)
  
--------
  
def f(x):
  
      return x**2
  
print f(4)
  
普通函数和下面lambda函数相同
  
g=lambda x:x**2
  
print g(4)
  
----------


页: [1]
查看完整版本: 第八节:python函数