函数
- 可以实现信息模块化的目标。
- 函数或方法能重复使用,便于日后的调试和维护。
- 从面向对象的角度来看,函数提供了操作接口的方法,有数据隐藏的作用。
根据程序设计的需求,Python的函数大致分为3种:
- 系统内置函数(Built-In Function,BIF),如获取类型的type()函数。
- 提供的函数标准库(Standard Library)。就像导入math模块时,会使用类math提供的类方法。
- 程序设计者使用def关键字自定义的函数。
Python内置函数
太多了,百度找
函数基础
- 定义函数:先以def关键字定义total()函数上及函数主体,它提供的是函数执行的根据。
- 调用程序:从程序语句中“调用函数”total()。
语法如下:
def 函数名称:
函数主体_suite
[return]
- def是关键字,用来定义函数,函数程序区块的开头,尾端要有“:”
- 函数名称:遵守标识符名称的命名规范。
- 参数列表:成为形式参数列表(format argument list),用来接受数值,其名称也适用于标识符名称的命名规范,可以有多个参数,也可以省略参数。
- 函数主体必须缩排,可以是单行或多行语句。
- return:返回运算后的值,无数值返回可省略。
定义函数
下面创建一个Fibonacci序列:
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
# Now call the function we just defined:
fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
函数体的第一行可以是一个可选的字符串文本;此字符串是该函数的文档字符串,或称为docstring。
如果你使用过其他语言,你可能会反对说:fib 不是一个函数,而是一个过程(子程序),因为它并不返回任何值。事实上,没有return语句的函数也返回一个值,尽管是一个很无聊的值。此值被称为 None(它是一个内置的名称)。如果 None只是唯一的输出,解释器通常不会打印出来。
返回值
用法与其他语言相同
def total(n1, n2, n3):
result = 0
for item in range(n1, n2 + 1, n3):
result += item
return result
print('cal')
key = input('start')
while key == 'y':
start = int(input('input init'))
finish = int(input('input end'))
step = int(input('input mid'))
print('total:{0:,}'.format(total(start, finish, step)))
key = input('start')
def answer(x, y):
return x + y, x * y, x / y
numA = int(input('first:'))
numB = int(input('second:'))
print('answer:', answer(numA, numB))
first:146
second:63
answer: (209, 9198, 2.31746031