一.函数的定义
def 函数名():
函数体
return 返回值1 返回值2
二.函数的调用
函数名()
实现答应返回值:print 函数名()
总结:
定义函数时,函数不执行
定义函数时,函数才执行
1.有参数的函数
(1)必选参数
#形式参数
def add(x,y)
print x + y
#实参,x=1,y=2
add(1, 2)
3
(2)默认参数
def mypow(x, y=2):
print x**y
mypow(2)
(3)可变函数
#形式参数
#args可以改为其他变量名;
def add(*args):
#args实质上是一个元组;
##print args # sum = 0 # for i in args: # sum += i # print sum add(1, 2, 3, 4, 5, 6)
(4)关键字参数
#kwargs可以改为其他变量名;
#def inuser(name, age, **kwargs):
##kwargs实质上是一个字典;
#print name, age, kwargs
inuser("user1" 12 city="xi'an" brith="20180102"
如果必选参数, 默认参数, > 可变参数, > 关键字参数
```;
(5)返回值
#函数中如果没有返回值return时,默认返回值None;
def add(x,y):
return x+y
print add(1,2)
3
None
#返回多个值
def fun(*args):
"""
返回最大值和最小值
:param args::return:"""#实质上python只能返回一个值;#间接通过元组返回多个值;return max(args), min(args)
print fun(23, 21, 1, 8,12)
/usr/bin/python2.7 /root/PycharmProjects/untitled/file/retu.py
(23, 1)
(5)函数作用域1)global关键字必须先声明,再赋值;#全局变量
num = 1
def fun():
num = 5
fun()
print num
1
num = 1
def fun():
global num #global声明num为全局变量
num = 5 #局部变量
fun()
print num
5
三.高级特性1.切片2.迭代(1)是否可以for循环遍历的对象;(2)isinstance判断是否可迭代;
In [1]: from collections import Iterable
In [2]: isinstance('hello', Iterable)
Out[2]: True
In [3]: isinstance([1, 2, 3, 4], Iterable)
Out[3]: True
In [4]: isinstance((1, 2, 3, 4), Iterable)
Out[4]: True
In [6]: isinstance({'c':3, 'd':4}, Iterable)
Out[6]: True
In [7]: isinstance({1, 2, 3}, Iterable)
Out[7]: True
li = []
for i in range(2,100,2):
...: li.append(i2)
...: print li
...:
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500, 2704, 2916, 3136, 3364, 3600, 3844, 4096, 4356, 4624, 4900, 5184, 5476, 5776, 6084, 6400, 6724, 7056, 7396, 7744, 8100, 8464, 8836, 9216, 9604]
方法2:
In [10]: [i2 for i in range(2, 10, 2)]
Out[10]: [4, 16, 36, 64]
In [12]: [i+j for i in 'xyz' for j in '123' ]
Out[12]: ['x1', 'x2', 'x3', 'y1', 'y2', 'y3', 'z1', 'z2', 'z3']
#for嵌套if语句
In [13]: [i**2 for i in range(2, 20, 2) if i%2==0]
Out[13]: [4, 16, 36, 64, 100, 144, 196, 256, 324]
应用:找出/etc下文件中以.conf结尾的文件;提示: os.listdir("/etc") s.enswith(".conf")
In [14]: import os
In [17]: print [i for i in os.listdir('/etc') if i.endswith('.conf')],
['host.conf', 'kdump.conf', 'sysctl.conf', 'ld.so.conf', 'sestatus.conf', 'nsswitch.conf', 'nfsmount.conf', 'man_db.conf', 'libaudit.conf', 'dnsmasq.conf', 'request-key.conf', 'krb5.conf', 'dracut.conf', 'libuser.conf', 'rsyslog.conf', 'logrotate.conf', 'e2fsck.conf', 'yum.conf', 'mke2fs.conf', 'idmapd.conf', 'ovirt-guest-agent.conf', 'rsyncd.conf', 'chrony.conf', 'sudo-ldap.conf', 'sudo.conf', 'vconsole.conf', 'locale.conf', 'resolv.conf', 'grub.conf', 'asound.conf', 'fuse.conf', 'colord.conf', 'hba.conf', 'sos.conf', 'oddjobd.conf', 'usb_modeswitch.conf', 'ipsec.conf', 'ksmtuned.conf', 'mtools.conf', 'radvd.conf', 'numad.conf', 'brltty.conf', 'fprintd.conf', 'wvdial.conf', 'pbm2ppa.conf', 'pnm2ppa.conf', 'updatedb.conf', 'lftp.conf', 'Trolltech.conf']