4. Python的函数
2018-03-27 本文已影响0人
edwin1993
简介
函数是重用的程序段。通过给一块语句特定的名称(函数名),使用名称来在程序的任意位置使用该语句块。
函数可以携带参数。参数在函数定义的圆括号对内指定,用逗号分割。当我们调用函数的时候,我们以同样的方式提供值。
stringEx = " hello world "
# 声明
def sayHi(santence):
print santence
# 调用
sayHi('hello Python')# 实参调用
sayHi(stringEx)#形参调用
# 结果
hello Python
hello world
局部变量
当你在函数定义内声明变量的时候,它们与函数外具有相同名称的其他变量没有任何关系,其作用范围为函数内部,所以称为局部变量。
可以使用global语句实现函数内的变量在全局有效。
def fun():
global x = 3
fun()
print x
# 结果
3
默认参数与关键参数
可以在函数定义的形参名后加上赋值运算符(=)和默认值,从而给形参指定默认参数值。
def fun (a = 3, b = 4)
print a
print b
fun (1)
fun(b =1)
# results:
1 4
3 1
return
return语句用来从一个函数返回,即跳出函数。也用于将函数内的内容输出。
DocStrings
文档字符串被简称为 docstrings ,被用于对程序进行说明。
函数的第一个逻辑行的字符串是这个函数的 文档字符串
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
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
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。
以使用doc(注意双下划线)调用printMax函数的文档字符串属性。