您的位置:首页 > 编程语言 > Python开发

python学习笔记之函数(方法)

2014-06-06 16:19 701 查看
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x


结果:

x is 50
Changed local x to 2
x is still 50


在函数内改变全局变量的值(global)

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


结果:

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

def maximum(x, y):
if x > y:
return x
else:
return y

print maximum(2, 3)


结果:3

空语句块pass

def someFunction():
pass


DocStrings

读取函数的doc注释信息,DocStrings也适用于模块

文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。

def printMax(x, y):
'''Descript:
this is printMax function descript
end.'''
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__
print '---'
help(printMax)


结果

5 is maximum
Descript:
this is printMax function descript
end.
---
Help on function printMax in module __main__:

printMax(x, y)
Descript:
this is printMax function descript
end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: