python学习笔记(三)函数

3.1函数的定义

def是定义函数的关键字,冒号表示接下来是函数体。
def CompareNum(a, b):
    if a > b:
        print(a, "is bigger than ", b)
    elif a == b:
        print(a, "is equal to", b)
    else:
        print(a, "is smaller than ", b)
        
CompareNum(2, 3);
运行结果:
2 is smaller than  3

3.2 global语句

global语句用来声明变量是全局的,作用是在函数内使用定义在函数外的变量。
x = 20

def func():
    global x
    x = 2
    print("x is", x)

func()
print("x is", x) 
运行结果:
x is 2
x is 2

3.3非局部语句

非局部作用域位于局部作用域和全局作用域之间,下例中func()中定义的x即称为非局部变量x。
def func():
    x = 20
    print("x is", x)
    def func_inside():
        nonlocal x
        x = 5
    func_inside()
    print("x is", x)

func()
运行结果:
x is 20
x is 5

3.4默认参数

默认参数是在函数定义的形参名后加上=和默认值。
def func(str, num = 1):
    print(str * num)

func("python")
func("python", 3)

运行结果:

python
pythonpythonpython

3.5关键参数

关键参数使用名字而不是位置来指定函数参数。优点是不必担心参数的顺序,以及在其他参数都有默认值时,只给想要的参数赋值。

def func(a, b = 1, c = 5):
    print("a is ", a, "b is ", b ,"c is ", c)

func(3, 4)
func(3, c = 10)
func(c = 10, a = 3)
运行结果:

a is  3 b is  4 c is  5
a is  3 b is  1 c is  10
a is  3 b is  1 c is  10

3.6 VarArgs参数

用*来定义一个任意个数参数的函数,用**来定义一个任意个数关键字参数的函数。

下例中*numbers表示参数被收集到number列表,**keywords表示关键字参数被收集到keywords字典。

def func(init = 5, *numbers, **keywords):
    count = init
    for i in numbers:
        count += i
    for key in keywords:
        count += keywords[key]
    return count


result = func(10, 1, 2, 3, veg = 1, fru = 2)
print("result = ", result)

运行结果:

result =  18

3.7 Keyword-only参数

带星号的参数后面申明参数会导致Keyword-only参数。如果参数没有默认值,且不给它赋值,如下例中func(10, 1, 2, 3)会引发错误。
def func(init = 5, *numbers, num):
    count = init
    for i in numbers:
        count += i
    count += num
    return count


result = func(10, 1, 2, 3, num = 2)
print("result = ", result)
运行结果:
result =  18

3.8 return语句

return语句用来从函数返回。没有return语句等价于return None。None表示没有任何东西的特殊类型。如变量值为None,表示它没有值。

3.9 DocStrings

DocStrings表示文档字符串,它的作用是:使程序文档简单易读。

文档字符串位于函数的第一个逻辑行,一般是多行字符串,首行大写字母开始,句号结尾。第二行是空行,第三行开始是详细的描述,使用时尽量遵循上述惯例,__doc__用于获取函数文档字符串属性。

def getMax(x, y):
'''Print the Maximum of two number.

   the num must be integers'''
x = int(x) #convert to integers
y = int(y)
if x > y:
	print(x, "is Maximum")
else:
	print(y, "is Maximum")

getMax(3, 5)
print(getMax.__doc__)

运行结果:

5 is Maximum
Print the Maximum of two number.
       the num must be integers







猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/69675714