Python中函数定义及参数实例

1.函数定义

函数就是完成特定功能的一个语句组,这组语句可以作为一个单位使用,并且给它取一个名字 ,可以通过函数名在程序的不同地方多次执行(这通常叫函数调用)
  • 预定义函数(可以直接使用)

  • 自定义函数(自己编写)

为什么使用函数?

降低编程难度,通常将一个复杂的大问题分解成一系列的小问题,然后将小问题划分成更小的问题,当问题细化为足够简单时,我们就可以分而治之,各个小问题解决了,大问题就迎刃而解了。

代码重用,避免重复劳作,提高效率。

函数的定义和调用

def 函数名([参数列表])    //定义

函数名 ([参数列表])     //调用

举例:

函数定义:

def fun():

   print("hello world")

函数调用:

fun()

hello world

脚本举例:

#/usr/bin/env python

# -*- coding:utf-8 -*-

# [@time](https://my.oschina.net/u/126678)   :2018/11/26 19:49

# [@Author](https://my.oschina.net/arthor) :FengXiaoqing

# [@file](https://my.oschina.net/u/726396)   :int.py

def fun():

    sth = raw_input("Please input sth: ")

try: #捕获异常

    if type(int(sth))==type(1):

        print("%s is a number") % sth

except:

    print("%s is not number") % sth

fun()

2.函数的参数

形式参数和实际参数

在定义函数时,函数名后面,括号中的变量名称叫做形式参数,或者称为"形参"

在调用函数时,函数名后面,括号中的变量名称叫做实际参数,或者称为"实参"



def fun(x,y):  //形参

print x + y

fun(1,2)     //实参

3

fun('a','b')

ab

3.函数的默认参数

练习:

打印系统的所有PID

要求从/proc读取

os.listdir()方法



#/usr/bin/env python

# -*- coding:utf-8 -*-

# [@time](https://my.oschina.net/u/126678)   :2018/11/26 21:06

# [@Author](https://my.oschina.net/arthor) :FengXiaoqing

# @file   :printPID.py

import sys

import os

def isNum(s):

    for i in s:

        if i not  in '0123456789':

            break    #如果不是数字就跳出本次循环

        else:   #如果for中i是数字才执行打印

            print  s

for j in os.listdir("/proc"):

    isNum(j)

函数默认参数:

缺省参数(默认参数)

    def fun(x,y=100)    

        print x,y

    fun(1,2)

    fun(1)

定义:

    def fun(x=2,y=3):

        print x+y



调用:

    fun()

    5

    fun(23)

    26

    fun(11,22)

    33

猜你喜欢

转载自my.oschina.net/u/3804957/blog/2961439