4函數(shù)
菲波那契序列:
>>> # 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抑月。最后一行右邊首先完成計算,右邊的表達(dá)式從左到右計算村刨。
條件(b < 10)為true時while循環(huán)執(zhí)行十减。這里Python類似C 栈幸,任何非零整數(shù)都為true;0為 false帮辟。判斷條件也可以是字符串或列表等序列速址;所有長度不為零的為true ,空序列為false由驹。示例中的測試是一個簡單的比較芍锚。標(biāo)準(zhǔn)比較操作符與C相同: <(小于), >(大于)蔓榄, ==(等于)并炮,<=(小于等于),>=(大于等于)和!=(不等于)甥郑。
循環(huán)體需要縮進(jìn):縮進(jìn)是Python組織語句的方法逃魄。在命令行下,縮進(jìn)行需要插入空格或者tab澜搅。建議使用文本編輯 或者IDE伍俘,一般都提供自動縮進(jìn)。命令行輸入復(fù)合語句時勉躺,必須用空行來標(biāo)識結(jié)束(因為解釋器沒辦法猜識別最后一行)癌瘾,注意同一級的語句需要縮進(jìn)同樣數(shù)量的空白。建議使用空格而不是tab縮進(jìn)饵溅。
print語句輸出表達(dá)式的值妨退。字符串打印時沒有引號,每兩個項目之間有空格。
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
逗號結(jié)尾就可以避免輸出換行:
>>> 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,
定義函數(shù)
菲波那契數(shù)列的函數(shù):
>>> 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
關(guān)鍵字def引入函數(shù)定義咬荷,其后有函數(shù)名和包含在圓括號中的形式參數(shù)冠句。函數(shù)體語句從下一行開始,必須縮進(jìn)的萍丐。
函數(shù)體的第一行語句可以是可選的字符串文本轩端,即文檔字符串。有些工具通過docstrings 自動生成文檔逝变,或者讓用戶通過代碼交互瀏覽;添加文檔字符串是個很好的習(xí)慣奋构。
函數(shù)執(zhí)行時生成符號表用來存儲局部變量壳影。 確切地說,所有函數(shù)的變量賦值都存儲在局部符號表弥臼。 變量查找的順序宴咧,先局部,然后逐級向上径缅,再到全局變量掺栅,最后內(nèi)置名。全局變量可在局部直接引用纳猪,但不能直接賦值(除非用global聲明)氧卧,盡管他們可以被引用, 因為python在局部賦值會重新定義一個本地變量。
函數(shù)的實際參數(shù)在調(diào)用時引入局部符號表氏堤,也就是說是傳值調(diào)用(值總是對象引用, 而不是該對象的值)沙绝。
函數(shù)定義會在當(dāng)前符號表內(nèi)引入函數(shù)名。 函數(shù)名的值為用戶自定義函數(shù)的類型,這個值可以賦值給其他變量當(dāng)做函數(shù)別名使用鼠锈。
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
沒有return語句的函數(shù)也會返回None闪檬。 解釋器一般不會顯示None,除非用print打印购笆。
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
從函數(shù)中返回
>>> 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語句從函數(shù)中返回值粗悯,不帶表達(dá)式的return返回None。過程結(jié)束后也會返回 None 同欠。
語句result.append(b)稱為調(diào)用了列表的方法样傍。方法是屬于對象的函數(shù),如obj.methodename行您,obj 是個對象(可能是一個表達(dá)式)铭乾,methodname是對象的方法名。不同類型有不同的方法娃循。不同類型可能有同名的方法炕檩。append()向鏈表尾部附加元素,等同于 result = result + [b] ,不過更有效笛质。
調(diào)用turtle庫的函數(shù)
代碼:
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術(shù)支持 釘釘群:21745728(可以加釘釘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) | 將筆繪制的線的粗細(xì)設(shè)置為width或返回當(dāng)前值妇押。 |
pencolor(color) | 將筆顏色設(shè)置為color或返回當(dāng)前值跷究。 |
fillcolor(color) | 將填充顏色設(shè)置為color或返回當(dāng)前值。 |
color(color) | 將筆和填充顏色設(shè)置為color或返回當(dāng)前值敲霍。 |
begin_fill() | 開始填充 |
end_fill() | 結(jié)束填充 |
turtlesize(factor) | 以factor拉伸俊马。 |
showturtle() | 開始顯示。 |
hideturtle() | 停止顯示 |
自己寫畫圓的函數(shù)
代碼:
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術(shù)支持 釘釘群:21745728(可以加釘釘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函數(shù)定義
python的函數(shù)參數(shù)有三種方式肩杈。
默認(rèn)參數(shù)
最常用的方式是給參數(shù)指定默認(rèn)值柴我,調(diào)用時就可以少傳參數(shù):
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)
調(diào)用方式:
只給出必選參數(shù): ask_ok('Do you really want to quit?') 給出一個可選的參數(shù): ask_ok('OK to overwrite the file?', 2)
給出所有的參數(shù): ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
in關(guān)鍵字測定序列是否包含指定值。
默認(rèn)值在函數(shù)定義時傳入扩然,如下所示:
i = 5
def f(arg=i):
print(arg)
i = 6
f()
上例顯示5艘儒。
注意: 默認(rèn)值只賦值一次。當(dāng)默認(rèn)值是可變對象(比如列表夫偶、字典或者大多數(shù)類的實例)時結(jié)果會不同界睁。實例:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
# 執(zhí)行結(jié)果:
[1]
[1, 2]
[1, 2, 3]
規(guī)避方式:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
關(guān)鍵字參數(shù)
關(guān)鍵字參數(shù) 的形式: 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, "!")
有效調(diào)用:
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
無效調(diào)用
parrot() # 沒有必選參數(shù)
parrot(voltage=5.0, 'dead') # 關(guān)鍵參數(shù)后面有非關(guān)鍵字參數(shù)
parrot(110, voltage=220) # 同一參數(shù)重復(fù)指定值
parrot(actor='John Cleese') # 不正確的關(guān)鍵字參數(shù)名
關(guān)鍵字參數(shù)在位置參數(shù)之后兵拢,多個關(guān)鍵字參數(shù)的順序先后無關(guān)翻斟,一個參數(shù)只能指定一次值,報錯實例:
>>> 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)接收一個字典卵佛,存儲形式參數(shù)沒有定義的參數(shù)名和值杨赤。類似的單個星號比如*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])
調(diào)用
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")
執(zhí)行:
-- 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
注意參數(shù)順序是隨機(jī)的截汪,可以使用sort排序疾牲。
任意參數(shù)列表
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
參數(shù)列表解包
把列表或元組拆分成多個并列的參數(shù)。
>>> 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表達(dá)式
lambda關(guān)鍵字可創(chuàng)建短小的匿名函數(shù)衙解,函數(shù)體只有一行阳柔,創(chuàng)建時就可使用。比如求和:lambda a, b: a+b蚓峦。通常不建議使用,不過在pandas等數(shù)據(jù)分析庫廣泛使用舌剂。
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
除了返回表達(dá)式,lambda還可以用作函數(shù)參數(shù)暑椰。
>>> 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)
文檔字符串
文檔字符串的內(nèi)容和格式建議如下霍转。
第一簡短介紹對象的目的。不能描述對象名和類型等其他地方能找到的信息一汽,首字母要大寫避消。
如果文檔字符串有多行低滩,第二行為空行以分隔概述和其他描述。描述介紹調(diào)用約定岩喷、邊界效應(yīng)等恕沫。
Python解釋器不會從多行文檔字符串中去除縮進(jìn),要用工具來處理纱意。約定如下:第一行后的第一個非空行決定了整個文檔的縮進(jìn)婶溯。實例:
>>> 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.
繪制人臉
代碼:
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術(shù)支持 釘釘群:21745728(可以加釘釘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()
執(zhí)行結(jié)果
$ 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:
參考資料
- 討論qq群144081101 591302926 567351477 釘釘免費(fèi)群21745728
- 本文最新版本地址
- 本文涉及的python測試開發(fā)庫 謝謝點贊!
- 本文相關(guān)海量書籍下載
- 本文源碼地址
習(xí)題
1偷霉,畫出如下圖形: