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

时间:2020-12-27 21:37:48
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.