python 3.7極速入門教程4函數(shù)

本文教程目錄

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

image

代碼:

# -*- 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ù)

image

代碼:

# -*- 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.

繪制人臉

image

代碼:

# -*- 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:

參考資料

習(xí)題

1偷霉,畫出如下圖形:

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末迄委,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子类少,更是在濱河造成了極大的恐慌跑筝,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瞒滴,死亡現(xiàn)場離奇詭異,居然都是意外死亡赞警,警方通過查閱死者的電腦和手機(jī)妓忍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來愧旦,“玉大人世剖,你說我怎么就攤上這事◇猿妫” “怎么了旁瘫?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長琼蚯。 經(jīng)常有香客問我酬凳,道長,這世上最難降的妖魔是什么遭庶? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任宁仔,我火速辦了婚禮,結(jié)果婚禮上峦睡,老公的妹妹穿的比我還像新娘翎苫。我一直安慰自己,他們只是感情好榨了,可當(dāng)我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布煎谍。 她就那樣靜靜地躺著,像睡著了一般龙屉。 火紅的嫁衣襯著肌膚如雪呐粘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機(jī)與錄音事哭,去河邊找鬼漫雷。 笑死,一個胖子當(dāng)著我的面吹牛鳍咱,可吹牛的內(nèi)容都是我干的降盹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼谤辜,長吁一口氣:“原來是場噩夢啊……” “哼蓄坏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起丑念,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤涡戳,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后脯倚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體渔彰,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年推正,在試婚紗的時候發(fā)現(xiàn)自己被綠了恍涂。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡植榕,死狀恐怖再沧,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情尊残,我是刑警寧澤炒瘸,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站寝衫,受9級特大地震影響顷扩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜竞端,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一屎即、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧事富,春花似錦技俐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至贱勃,卻和暖如春井赌,著一層夾襖步出監(jiān)牢的瞬間谤逼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工仇穗, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留流部,地道東北人。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓纹坐,卻偏偏與公主長得像枝冀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子耘子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 〇果漾、前言 本文共108張圖,流量黨請慎重谷誓! 歷時1個半月绒障,我把自己學(xué)習(xí)Python基礎(chǔ)知識的框架詳細(xì)梳理了一遍。 ...
    Raxxie閱讀 18,957評論 17 410
  • 一捍歪、快捷鍵 ctr+b 執(zhí)行ctr+/ 單行注釋ctr+c ...
    o_8319閱讀 5,820評論 2 16
  • 第2章 基本語法 2.1 概述 基本句法和變量 語句 JavaScript程序的執(zhí)行單位為行(line)户辱,也就是一...
    悟名先生閱讀 4,149評論 0 13
  • 文/羽商三少 在外面日常生活中焕妙,衣食住行是離不開的,而其中的住弓摘,對我們來說也是一個非常的關(guān)鍵,可是在普遍縣城的初高...
    羽商三少閱讀 439評論 1 3
  • 陽光下的女孩 仿佛你身上的每一個細(xì)胞 都是一座蝴蝶的小屋 春天和陽光里的事情都從那里出去 五月的天空下 你小小的心...
    小白畫畫閱讀 1,734評論 30 80