python 3.7极速入门教程4函数

4函数

菲波那契序列:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8

本例的新特性。

  • 第一行和最后一行有多赋值:第一行变量a和b同时获得了新的值0和1。最后一行右边首先完成计算,右边的表达式从左到右计算。

  • 条件(b < 10)为true时while循环执行。这里Python类似C ,任何非零整数都为true;0为 false。判断条件也可以是字符串或列表等序列;所有长度不为零的为true ,空序列为false。示例中的测试是一个简单的比较。标准比较操作符与C相同: <(小于), >(大于), ==(等于),<=(小于等于),>=(大于等于)和!=(不等于)。

  • 循环体需要缩进:缩进是Python组织语句的方法。在命令行下,缩进行需要插入空格或者tab。建议使用文本编辑 或者IDE,一般都提供自动缩进。命令行输入复合语句时,必须用空行来标识结束(因为解释器没办法猜识别最后一行),注意同一级的语句需要缩进同样数量的空白。建议使用空格而不是tab缩进。

  • print语句输出表达式的值。字符串打印时没有引号,每两个项目之间有空格。

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

逗号结尾就可以避免输出换行:

>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

定义函数

菲波那契数列的函数:

>>> 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

关键字def引入函数定义,其后有函数名和包含在圆括号中的形式参数。函数体语句从下一行开始,必须缩进的。
函数体的第一行语句可以是可选的字符串文本,即文档字符串。有些工具通过docstrings 自动生成文档,或者让用户通过代码交互浏览;添加文档字符串是个很好的习惯。
函数执行时生成符号表用来存储局部变量。 确切地说,所有函数的变量赋值都存储在局部符号表。 变量查找的顺序,先局部,然后逐级向上,再到全局变量,最后内置名。全局变量可在局部直接引用,但不能直接赋值(除非用global声明),尽管他们可以被引用, 因为python在局部赋值会重新定义一个本地变量。

函数的实际参数在调用时引入局部符号表,也就是说是传值调用(值总是对象引用, 而不是该对象的值)。
函数定义会在当前符号表内引入函数名。 函数名的值为用户自定义函数的类型,这个值可以赋值给其他变量当做函数别名使用。

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

没有return语句的函数也会返回None。 解释器一般不会显示None,除非用print打印。

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

从函数中返回

>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

return语句从函数中返回值,不带表达式的return返回None。过程结束后也会返回 None 。

语句result.append(b)称为调用了列表的方法。方法是属于对象的函数,如obj.methodename,obj 是个对象(可能是一个表达式),methodname是对象的方法名。不同类型有不同的方法。不同类型可能有同名的方法。append()向链表尾部附加元素,等同于 result = result + [b] ,不过更有效。

调用turtle库的函数

image

代码:

# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 (可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# bowtie.py
# Draw a bowtie
from turtle import *
pensize(7)
penup()
goto(-200, -100)
pendown()
fillcolor("red")
begin_fill()
goto(-200, 100)
goto(200, -100)
goto(200, 100)
goto(-200, -100)
end_fill()
exitonclick()
方法 功能
fgoto(x, y) 移到位置(x,y)。
pensize(width) 将笔绘制的线的粗细设置为width或返回当前值。
pencolor(color) 将笔颜色设置为color或返回当前值。
fillcolor(color) 将填充颜色设置为color或返回当前值。
color(color) 将笔和填充颜色设置为color或返回当前值。
begin_fill() 开始填充
end_fill() 结束填充
turtlesize(factor) 以factor拉伸。
showturtle() 开始显示。
hideturtle() 停止显示

自己写画圆的函数

image

代码:

# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 (可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# bowtie.py
# Draw a bowtie
from turtle import *
def circle_at(x, y, r):
   """Draw circle with center (x, y) radius r."""
   penup()
   goto(x, y - r)
   pendown()
   setheading(0)
   circle(r)
circle_at(-200, 0, 20)
begin_fill()
circle_at(0, 0, 100)
end_fill()
circle_at(200, 0, 20)
hideturtle()
exitonclick()

深入Python函数定义

python的函数参数有三种方式。

默认参数

最常用的方式是给参数指定默认值,调用时就可以少传参数:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
   while True:
       ok = input(prompt)
       if ok in ('y', 'ye', 'yes'):
           return True
       if ok in ('n', 'no', 'nop', 'nope'):
           return False
       retries = retries - 1
       if retries < 0:
           raise ValueError('invalid user response')
       print(reminder)

调用方式:

只给出必选参数: ask_ok('Do you really want to quit?') 给出一个可选的参数: ask_ok('OK to overwrite the file?', 2)
给出所有的参数: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

in关键字测定序列是否包含指定值。

默认值在函数定义时传入,如下所示:

i = 5
def f(arg=i):
   print(arg)
i = 6
f()

上例显示5。

注意: 默认值只赋值一次。当默认值是可变对象(比如列表、字典或者大多数类的实例)时结果会不同。实例:

def f(a, L=[]):
   L.append(a)
   return L
print f(1)
print f(2)
print f(3)
# 执行结果:
[1]
[1, 2]
[1, 2, 3]

规避方式:

def f(a, L=None):
   if L is None:
       L = []
   L.append(a)
   return L

关键字参数

关键字参数 的形式: keyword = value。

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
   print("-- This parrot wouldn't", action, end=' ')
   print("if you put", voltage, "volts through it.")
   print("-- Lovely plumage, the", type)
   print("-- It's", state, "!")

有效调用:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

无效调用

parrot()                     # 没有必选参数
parrot(voltage=5.0, 'dead')  # 关键参数后面有非关键字参数
parrot(110, voltage=220)     # 同一参数重复指定值
parrot(actor='John Cleese')  # 不正确的关键字参数名

关键字参数在位置参数之后,多个关键字参数的顺序先后无关,一个参数只能指定一次值,报错实例:

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'

最后一个如果前有两个星号(比如name)接收一个字典,存储形式参数没有定义的参数名和值。类似的单个星号比如*name表示接受一个元组。

def cheeseshop(kind, *arguments, **keywords):
   print("-- Do you have any", kind, "?")
   print("-- I'm sorry, we're all out of", kind)
   for arg in arguments:
       print(arg)
   print("-" * 40)
   for kw in keywords:
       print(kw, ":", keywords[kw])

调用

cheeseshop("Limburger", "It's very runny, sir.",
          "It's really very, VERY runny, sir.",
          shopkeeper='Michael Palin',
          client="John Cleese",
          sketch="Cheese Shop Sketch")

执行:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

注意参数顺序是随机的,可以使用sort排序。

任意参数列表

def write_multiple_items(file, separator, *args):
   file.write(separator.join(args))

参数列表解包

把列表或元组拆分成多个并列的参数。

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

同样的字典可以用两个星号解包:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

Lambda表达式

lambda关键字可创建短小的匿名函数,函数体只有一行,创建时就可使用。比如求和:lambda a, b: a+b。通常不建议使用,不过在pandas等数据分析库广泛使用。

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

除了返回表达式,lambda还可以用作函数参数。

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')](1)

文档字符串

文档字符串的内容和格式建议如下。

第一简短介绍对象的目的。不能描述对象名和类型等其他地方能找到的信息,首字母要大写。
如果文档字符串有多行,第二行为空行以分隔概述和其他描述。描述介绍调用约定、边界效应等。
Python解释器不会从多行文档字符串中去除缩进,要用工具来处理。约定如下:第一行后的第一个非空行决定了整个文档的缩进。实例:

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
   No, really, it doesn't do anything.

绘制人脸

image

代码:

# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 (可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
from turtle import *
def circle_at(x, y, r):
   """Draw circle with center (x, y) radius r."""
   penup()
   goto(x, y - r)
   pendown()
   setheading(0)
   circle(r)
def eye(x, y, radius):
   """Draw an eye centered at (x, y) of given radius."""
   circle_at(x, y, radius)

def face(x, y, width):
   """Draw face centered at (x, y) of given width."""
   circle_at(x, y, width/2)
   eye(x - width/6, y + width/5, width/12)
   eye(x + width/6, y + width/5, width/12)

def main():
   face(0, 0, 100)
   face(-140, 160, 200)
   exitonclick()

main()

递归

factorial.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-25
# factorial.py
def factorial(n):
   """Return n! = 1*2*3*...*n."""
   if n <= 1:
       return 1
   return n * factorial(n - 1)
def main():
   for n in range(20):
       print(n, factorial(n))
   print(factorial(2000))
main()

执行结果

$ python3 factorial.py 
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 6227020800
14 87178291200
15 1307674368000
16 20922789888000
17 355687428096000
18 6402373705728000
19 121645100408832000
Traceback (most recent call last):
 File "factorial.py", line 19, in <module>
   main()
 File "factorial.py", line 17, in main
   print(factorial(2000))
 File "factorial.py", line 12, in factorial
   return n * factorial(n - 1)
 File "factorial.py", line 12, in factorial
   return n * factorial(n - 1)
 File "factorial.py", line 12, in factorial
   return n * factorial(n - 1)
 [Previous line repeated 993 more times]
 File "factorial.py", line 10, in factorial
   if n <= 1:

参考资料

习题

1,画出如下图形:

image

参考资料

links