python学习之路-第三天-函数

函数

  • 函数的定义关键字:def

  • 使用global语句可以清楚地表明变量是在外面的块定义的

  • 示例:(函数运行完毕后x的值是2)

#!/usr/bin/python
# Filename: func_global.py

def func():
    global x

    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x
  • 可以给形参加上默认值,默认参数是不可变的,而且只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认
    值的形参。这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是无效的。

  • 示例:

#!/usr/bin/python
# Filename: func_default.py

def say(message, times = 1):
    print message * times

say('Hello')
say('World', 5)
Hello
WorldWorldWorldWorldWorld
  • 关键参数,很有意思,可以根据指定的参数名字赋值,而不必每次都要按位置赋值

  • 示例:

#!/usr/bin/python
# Filename: func_key.py

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

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

运行结果:

$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
  • pass语句在Python中表示一个空的语句块。就像在java/c++里面的;

  • 除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句

  • 文档字符串DocStrings,它所做的只是抓取函数的__doc__属性,然后整洁地展示给你

#!/usr/bin/python
# Filename: func_doc.py

def printMax(x, y):
    '''Prints the maximum of two numbers.

    The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)

    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__
posted @ 2017-11-16 12:08  dreamOnly  阅读(187)  评论(0编辑  收藏  举报