定义函数
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.