【python自学】(四)-----函数

定义函数

def sayHello():
    print 'Hello World!' # block belonging to the function

sayHello() # call the function

函数形参   

函数中的参数

局部变量

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x
$ python func_local.py
x is 50
Changed local x to 2
x is still 50

输出结果x=50,因为x=2是函数中与全局变量同名的变量,其作用范围只是函数中;

可以使用globe语句将变量指定为全局变量

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
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2

默认参数值

定义函数时,可以给形参指定默认值。注意:只有在形参表末尾的那些参数可以有默认参数值(形参的赋值是根据位置)

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

say('Hello')
say('World', 5)

Hello
WorldWorldWorldWorldWorld

关键参数

如果只想指定函数中许多参数的一部分,可以通过命名来为这些参数赋值,被称为关键参数。这样就不用担心赋值的顺序。

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)

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

return语句

返回变量

DocStrings(文档字符串)

在函数的第一个逻辑行的字符串是这个函数的文档字符串,其惯例是一个多行字符串,首行以大写字母开始,句号结尾;第二行是空行;第三行开始进行详细的描述。

使用__doc__(双下划线)调用函数的文档字符串属性。

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__

5 is maximum
Prints the maximum of two numbers.

        The two values must be integers.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值