首页 > 代码库 > 7、函数

7、函数

语法:
  1. def fun_name():            --不带参数的函数    print xxxdef fun_name(name,age):        --带参数的函数    print ’hi ,%s ,you are %s  years old%(name,age)

     

示例:
  1. >>> def hi():...  print hello!... >>> hi()hello!>>> >>> def hi2(name):...  print hello , %s%name... >>> hi2(lk)hello , lk

     

 
参数,可以给默认值,这样调用的时候可以不输入参数:
  1. >>> def hi3(name=lk):...  print hi,%s%name... >>> hi3()hi,lk>>> hi3(tom)hi,tom

     

 
带默认值的参数要放在后面,调用函数可以指定参数名
  1. [root@likun python_scripts]# cat 11fun.py 
    #
    !/usr/bin/pythondef emp(a,b,c=10,d=20): return%s,%s,%s,%s%(d,c,b,a)print emp(1,2)print emp(b=2,a=1)print emp(1,2,3)print emp(1,2,d=30)[root@likun python_scripts]# python 11fun.py 20,10,2,120,10,2,120,3,2,130,10,2,1

     

局部变量和全局变量
局部变量在函数外不可调用:
  1. [root@likun python_scripts]# cat 11fun.py #!/usr/bin/pythondef emp():        list=[]        list.append(lk)        list.append(tom)        print list        returnlist        #函数返回值print emp()                #用来将函数赋值到变量print local var is not enable:!,list

     

  2. [root@likun python_scripts]# python 11fun.py [lk,tom][lk,tom]local var is not enable:!<type list>

     

全局变量,需先定义成global: 
  1. [root@likun python_scripts]# cat 11fun.py #!/usr/bin/pythondef emp():        global list        list=[]        list.append(lk)        list.append(tom)        print local var:,list        returnlistprint emp()list.append(jack)print global var is not enable:!,list

     

  2. [root@likun python_scripts]# python 11fun.py local var:[lk,tom][lk,tom]global var is enable:![lk,tom,jack]

     

小练习:
用函数写一个程序,列出/etc/init.d下所有进程(以4列显示并对齐),
让用户选择操作某个进程的相应命令【start|stop】等,不写默认status:如
输入:mysql start:执行启动命令
输入:mysql    :执行查看状态命令
 
  1. [root@likun python_scripts]# cat 11fun.py #!/usr/bin/pythonimport os,sysos.chdir(/etc/init.d)service_list=os.listdir(/etc/init.d)def run(servicename,action=status):        #if action==‘‘: action=‘status‘        cmd =service %s %s%(servicename,action)        print cmd        os.system(cmd)i=0for service in service_list:        i=i+1        print service,        if i%4!=0  :                print ( *(15-len(service))),        #输出4列并对齐        else:                print ‘‘ whileTrue:        option = raw_input(\nPlease input your option:)        if len(option.split())==2:        #判断输入的参数个数                servicename=option.split()[0]                action=option.split()[1]                run(servicename,action)        elif len(option.split())==1:                run(option)        else:                print wrong input!                continue

     

  1. [root@likun python_scripts]# python 11fun.py rpcidmapd        sssd             lvm2-monitor     halt postfix          cgconfig         restorecond      rpcgssd kdump            avahi-daemon     rpcsvcgssd       rpcbind ip6tables        mcelogd          rdisc            rsyslog rhnsd            ntpd             mysql            netconsole nslcd            sandbox          vsftpd           single autofs           zabbix_server    sshd             mdmonitor netfs            haldaemon        network          messagebus oddjobd          postgresql       httpd            crond sysstat          nagios           nfslock          psacct ypbind           iptables         functions        killall cgred            saslauthd        atd              snmptrapd snmpd            zabbix_agentd    certmonger       auditd cpuspeed         microcode_ctl    smartd           acpid nscd             nfs              udev-post        irqbalance abrtd            ntpdate          Please input your option:mysql restart    service mysql restartShutting down MySQL.                                       [  OK  ]StartingMySQL..                                           [  OK  ]Please input your option:

     

7、函数