Python學習心路歷程-day3

學習內容html

1.集合及其操做python

2.文件操做linux

3.字符轉編碼操做c++

4.函數介紹express

5.遞歸windows

6.返回值數據結構

7.高階函數app

8.內置參數less

1.集合及其操做                                                                                  dom

集合是一個無序的,不重複的數據組合,它的主要做用以下:

  • 去重,把一個列表變成集合,就自動去重了
  • 關係測試,測試兩組數據以前的交集、差集、並集等關係

經常使用操做

s = set([3,5,9,10])      #建立一個數值集合  

t = set("Hello")         #建立一個惟一字符的集合  


a = t | s          # t 和 s的並集  

b = t & s          # t 和 s的交集  

c = t – s          # 求差集(項在t中,但不在s中)  

d = t ^ s          # 對稱差集(項在t或s中,但不會同時出如今兩者中)  



基本操做:

t.add('x')            # 添加一項  

s.update([10,37,42])  # 在s中添加多項  



使用remove()能夠刪除一項:

t.remove('H')


len(s)
set 的長度

x in s
測試 x 是不是 s 的成員

x not in s
測試 x 是否不是 s 的成員

s.issubset(t)
s <= t
測試是否 s 中的每個元素都在 t 中

s.issuperset(t)
s >= t
測試是否 t 中的每個元素都在 s 中

s.union(t)
s | t
返回一個新的 set 包含 s 和 t 中的每個元素

s.intersection(t)
s & t
返回一個新的 set 包含 s 和 t 中的公共元素

s.difference(t)
s - t
返回一個新的 set 包含 s 中有可是 t 中沒有的元素

s.symmetric_difference(t)
s ^ t
返回一個新的 set 包含 s 和 t 中不重複的元素

s.copy()
返回 set 「s」的一個淺複製
View Code

2.文件操做                                                                                        

對文件操做流程

  1. 打開文件,獲得文件句柄並賦值給一個變量
  2. 經過句柄對文件進行操做
  3. 關閉文件

現有文件以下 :

Somehow, it seems the love I knew was always the most destructive kind
不知爲什麼,我經歷的愛情老是最具毀滅性的的那種
Yesterday when I was young
昨日當我年少輕狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戲弄生命 視其爲愚蠢的遊戲
The way the evening breeze
就如夜晚的微風
May tease the candle flame
逗弄蠟燭的火苗
The thousand dreams I dreamed
我曾千萬次夢見
The splendid things I planned
那些我計劃的絢麗藍圖
I always built to last on weak and shifting sand
但我老是將之建築在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白晝赤裸的陽光
And only now I see how the time ran away
事到現在我纔看清歲月是如何匆匆流逝
Yesterday when I was young
昨日當我年少輕狂
So many lovely songs were waiting to be sung
有那麼多甜美的曲兒等我歌唱
So many wild pleasures lay in store for me
有那麼多肆意的快樂等我享受
And so much pain my eyes refused to see
還有那麼多痛苦 個人雙眼卻視而不見
I ran so fast that time and youth at last ran out
我飛快地奔走 最終時光與青春消逝殆盡
I never stopped to think what life was all about
我從未停下腳步去思考生命的意義
And every conversation that I can now recall
現在回想起的全部對話
Concerned itself with me and nothing else at all
除了和我相關的 什麼都記不得了
The game of love I played with arrogance and pride
我用自負和傲慢玩着愛情的遊戲
And every flame I lit too quickly, quickly died
全部我點燃的火焰都熄滅得太快
The friends I made all somehow seemed to slip away
全部我交的朋友彷佛都不知不覺地離開了
And only now I'm left alone to end the play, yeah
只剩我一我的在臺上來結束這場鬧劇
Oh, yesterday when I was young
噢 昨日當我年少輕狂
So many, many songs were waiting to be sung
有那麼那麼多甜美的曲兒等我歌唱
So many wild pleasures lay in store for me
有那麼多肆意的快樂等我享受
And so much pain my eyes refused to see
還有那麼多痛苦 個人雙眼卻視而不見
There are so many songs in me that won't be sung
我有太多歌曲永遠不會被唱起
I feel the bitter taste of tears upon my tongue
我嚐到了舌尖淚水的苦澀滋味
The time has come for me to pay for yesterday
終於到了付出代價的時間 爲了昨日
When I was young
當我年少輕狂
View Code

基本操做

f = open('lyrics') #打開文件
first_line = f.readline()
print('first line:',first_line) #讀一行
print('我是分隔線'.center(50,'-'))
data = f.read()# 讀取剩下的全部內容,文件大時不要用
print(data) #打印文件
f.close() #關閉文件
View Code

讀取鍵盤輸入

Python提供了兩個內置函數從標準輸入讀入一行文本,默認的標準輸入是鍵盤。以下:

  • raw_input(python 2.x)
  • input (python 3.x)
raw_input函數

raw_input([prompt]) 函數從標準輸入讀取一個行,並返回一個字符串(去掉結尾的換行符):

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

str = raw_input("請輸入:");
print "你輸入的內容是: ", str
View Code

這將提示你輸入任意字符串,而後在屏幕上顯示相同的字符串。當我輸入"Hello Python!",它的輸出以下:

請輸入:Hello Python!
你輸入的內容是:  Hello Python!
View Code
input函數

input([prompt]) 函數和 raw_input([prompt]) 函數基本相似,可是 input 能夠接收一個Python表達式做爲輸入,並將運算結果返回。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

str = input("請輸入:");
print "你輸入的內容是: ", str
View Code

這會產生以下的對應着輸入的結果:

請輸入:[x*5 for x in range(2,10,2)]
你輸入的內容是:  [10, 20, 30, 40]
View Code

打開和關閉文件

如今,您已經能夠向標準輸入和輸出進行讀寫。如今,來看看怎麼讀寫實際的數據文件。

Python 提供了必要的函數和方法進行默認狀況下的文件基本操做。你能夠用 file 對象作大部分的文件操做。

open 函數

你必須先用Python內置的open()函數打開一個文件,建立一個file對象,相關的方法才能夠調用它進行讀寫。

語法:

file object = open(file_name [, access_mode][, buffering])
View Code

各個參數的細節以下:

  • file_name:file_name變量是一個包含了你要訪問的文件名稱的字符串值。
  • access_mode:access_mode決定了打開文件的模式:只讀,寫入,追加等。全部可取值見以下的徹底列表。這個參數是非強制的,默認文件訪問模式爲只讀(r)。
  • buffering:若是buffering的值被設爲0,就不會有寄存。若是buffering的值取1,訪問文件時會寄存行。若是將buffering的值設爲大於1的整數,代表了這就是的寄存區的緩衝大小。若是取負值,寄存區的緩衝大小則爲系統默認。

不一樣模式打開文件的徹底列表:

File對象的屬性

一個文件被打開後,你有一個file對象,你能夠獲得有關該文件的各類信息。

如下是和file對象相關的全部屬性的列表:

以下實例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 打開一個文件
  5 fo = open("foo.txt", "wb")
  6 print "文件名: ", fo.name
  7 print "是否已關閉 : ", fo.closed
  8 print "訪問模式 : ", fo.mode
  9 print "末尾是否強制加空格 : ", fo.softspace
View Code

以上實例輸出結果:

  1 文件名:  foo.txt
  2 是否已關閉 :  False
  3 訪問模式 :  wb
  4 末尾是否強制加空格 :  0
View Code
close()方法

File 對象的 close()方法刷新緩衝區裏任何還沒寫入的信息,並關閉該文件,這以後便不能再進行寫入。

當一個文件對象的引用被從新指定給另外一個文件時,Python 會關閉以前的文件。用 close()方法關閉文件是一個很好的習慣。

語法:

fileObject.close();
View Code

例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打開一個文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name

# 關閉打開的文件
fo.close()
View Code

以上實例輸出結果:

文件名:  foo.txt
View Code

讀寫文件:

file對象提供了一系列方法,能讓咱們的文件訪問更輕鬆。來看看如何使用read()和write()方法來讀取和寫入文件。

write()方法

write()方法可將任何字符串寫入一個打開的文件。須要重點注意的是,Python字符串能夠是二進制數據,而不是僅僅是文字。

write()方法不會在字符串的結尾添加換行符('\n'):

語法:

fileObject.write(string);
View Code

在這裏,被傳遞的參數是要寫入到已打開文件的內容。

例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打開一個文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");

# 關閉打開的文件
fo.close()
View Code

上述方法會建立foo.txt文件,並將收到的內容寫入該文件,並最終關閉文件。若是你打開這個文件,將看到如下內容:

$ cat foo.txt
www.runoob.com!
Very good site!
View Code
read()方法

read()方法從一個打開的文件中讀取一個字符串。須要重點注意的是,Python字符串能夠是二進制數據,而不是僅僅是文字。

語法:

fileObject.read([count]);
View Code

在這裏,被傳遞的參數是要從已打開文件中讀取的字節計數。該方法從文件的開頭開始讀入,若是沒有傳入count,它會嘗試儘量多地讀取更多的內容,極可能是直到文件的末尾。

例子:

這裏咱們用到以上建立的 foo.txt 文件。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打開一個文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "讀取的字符串是 : ", str
# 關閉打開的文件
fo.close()
View Code

以上實例輸出結果:

讀取的字符串是 :  www.runoob
View Code

文件位置:

文件定位

tell()方法告訴你文件內的當前位置;換句話說,下一次的讀寫會發生在文件開頭這麼多字節以後。

seek(offset [,from])方法改變當前文件的位置。Offset變量表示要移動的字節數。From變量指定開始移動字節的參考位置。

若是from被設爲0,這意味着將文件的開頭做爲移動字節的參考位置。若是設爲1,則使用當前的位置做爲參考位置。若是它被設爲2,那麼該文件的末尾將做爲參考位置。

例子:

就用咱們上面建立的文件foo.txt。

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 打開一個文件
  5 fo = open("foo.txt", "r+")
  6 str = fo.read(10);
  7 print "讀取的字符串是 : ", str
  8 
  9 # 查找當前位置
 10 position = fo.tell();
 11 print "當前文件位置 : ", position
 12 
 13 # 把指針再次從新定位到文件開頭
 14 position = fo.seek(0, 0);
 15 str = fo.read(10);
 16 print "從新讀取字符串 : ", str
 17 # 關閉打開的文件
 18 fo.close()
View Code

以上實例輸出結果:

讀取的字符串是 :  www.runoob
當前文件位置 :  10
從新讀取字符串 :  www.runoob
View Code

打開文件的模式有:

  • r,只讀模式(默認)。
  • w,只寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

"+" 表示能夠同時讀寫某個文件

  • r+,可讀寫文件。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

"U"表示在讀取時,能夠將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)

  • rb
  • wb
  • ab

其它語法

def close(self): # real signature unknown; restored from __doc__
        """
        Close the file.

        A closed file cannot be used for further I/O operations.  close() may be
        called more than once without error.
        """
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        """ Return the underlying file descriptor (an integer). """
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        """ True if the file is connected to a TTY device. """
        pass

    def read(self, size=-1): # known case of _io.FileIO.read
        """
        注意,不必定能全讀回來
        Read at most size bytes, returned as bytes.

        Only makes one system call, so less data may be returned than requested.
        In non-blocking mode, returns None if no data is available.
        Return an empty bytes object at EOF.
        """
        return ""

    def readable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a read mode. """
        pass

    def readall(self, *args, **kwargs): # real signature unknown
        """
        Read all data from the file, returned as bytes.

        In non-blocking mode, returns as much as is immediately available,
        or None if no data is available.  Return an empty bytes object at EOF.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        """ Same as RawIOBase.readinto(). """
        pass #不要用,沒人知道它是幹嗎用的

    def seek(self, *args, **kwargs): # real signature unknown
        """
        Move to new file position and return the file position.

        Argument offset is a byte count.  Optional argument whence defaults to
        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
        are SEEK_CUR or 1 (move relative to current position, positive or negative),
        and SEEK_END or 2 (move relative to end of file, usually negative, although
        many platforms allow seeking beyond the end of a file).

        Note that not all file objects are seekable.
        """
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        """ True if file supports random-access. """
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        """
        Current file position.

        Can raise OSError for non seekable files.
        """
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        """
        Truncate the file to at most size bytes and return the truncated size.

        Size defaults to the current file position, as returned by tell().
        The current file position is changed to the value of size.
        """
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a write mode. """
        pass

    def write(self, *args, **kwargs): # real signature unknown
        """
        Write bytes b to file, return number written.

        Only makes one system call, so not all of the data may be written.
        The number of bytes actually written is returned.  In non-blocking mode,
        returns None if the write would block.
        """
        pass
View Code

with語句

爲了不打開文件後忘記關閉,能夠經過管理上下文,即:

  1 with open('log','r') as f:
  2 
  3     ...
View Code

如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:

  1 with open('log1') as obj1, open('log2') as obj2:
  2 
  3     pass
View Code
3. 字符編碼與轉碼                                                                             

詳細文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

需知:

1.在python2默認編碼是ASCII, python3裏默認是unicode

2.unicode 分爲 utf-32(佔4個字節),utf-16(佔兩個字節),utf-8(佔1-4個字節), so utf-16就是如今最經常使用的unicode版本, 不過在文件裏存的仍是utf-8,由於utf8省空間

3.在py3中encode,在轉碼的同時還會把string 變成bytes類型,decode在解碼的同時還會把bytes變回string

上圖僅適用於py2

  1 #!/user/bin/env python
  2 # -*- coding: UTF-8 -*-
  3 # Author: cs
  4 import sys
  5 print(sys.getdefaultencoding())
  6 
  7 
  8 msg = "我愛北京天安門"
  9 msg_gb2312 = msg.decode("utf-8").encode("gb2312")
 10 gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk")
 11 
 12 print(msg)
 13 print(msg_gb2312)
 14 print(gb2312_to_gbk)
 15 
 16 in python2
View Code
  1 # Author: cs
  2 import sys
  3 print(sys.getdefaultencoding())
  4 
  5 
  6 msg = "我愛北京天安門"
  7 #msg_gb2312 = msg.decode("utf-8").encode("gb2312")
  8 msg_gb2312 = msg.encode("gb2312") #默認就是unicode,不用再decode
  9 gb2312_to_unicode = msg_gb2312.decode("gb2312")
 10 gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")
 11 
 12 print(msg)
 13 print(msg_gb2312)
 14 print(gb2312_to_unicode)
 15 print(gb2312_to_utf8)
View Code

4.函數介紹                                                                                        

函數是組織好的,可重複使用的,用來實現單一,或相關聯功能的代碼段。

函數能提升應用的模塊性,和代碼的重複利用率。你已經知道Python提供了許多內建函數,好比print()。但你也能夠本身建立函數,這被叫作用戶自定義函數。

定義一個函數

你能夠定義一個由本身想要功能的函數,如下是簡單的規則:

  • 函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號()
  • 任何傳入參數和自變量必須放在圓括號中間。圓括號之間能夠用於定義參數。
  • 函數的第一行語句能夠選擇性地使用文檔字符串—用於存放函數說明。
  • 函數內容以冒號起始,而且縮進。
  • return [表達式] 結束函數,選擇性地返回一個值給調用方。不帶表達式的return至關於返回 None。
語法
def functionname( parameters ):
   "函數_文檔字符串"
   function_suite
   return [expression]
View Code

默認狀況下,參數值和參數名稱是按函數聲明中定義的的順序匹配起來的。

例子:

def printme( str ):
   "打印傳入的字符串到標準顯示設備上"
   print str
   return
View Code

函數調用

定義一個函數只給了函數一個名稱,指定了函數裏包含的參數,和代碼塊結構。

這個函數的基本結構完成之後,你能夠經過另外一個函數調用執行,也能夠直接從Python提示符執行。

以下實例調用了printme()函數:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 定義函數
  5 def printme( str ):
  6    "打印任何傳入的字符串"
  7    print str;
  8    return;
  9 
 10 # 調用函數
 11 printme("我要調用用戶自定義函數!");
 12 printme("再次調用同一函數");
View Code

以上實例輸出結果:

我要調用用戶自定義函數!
再次調用同一函數
View Code

參數傳遞

在 python 中,類型屬於對象,變量是沒有類型的:

a=[1,2,3]
a="Runoob"
View Code

以上代碼中,[1,2,3] 是 List 類型,"Runoob" 是 String 類型,而變量 a 是沒有類型,她僅僅是一個對象的引用(一個指針),能夠是 List 類型對象,也能夠指向 String 類型對象。

可更改(mutable)與不可更改(immutable)對象

在 python 中,strings, tuples, 和 numbers 是不可更改的對象,而 list,dict 等則是能夠修改的對象。

  • 不可變類型:變量賦值 a=5 後再賦值 a=10,這裏實際是新生成一個 int 值對象 10,再讓 a 指向它,而 5 被丟棄,不是改變a的值,至關於新生成了a。

  • 可變類型:變量賦值 la=[1,2,3,4] 後再賦值 la[2]=5 則是將 list la 的第三個元素值更改,自己la沒有動,只是其內部的一部分值被修改了。

python 函數的參數傳遞:

  • 不可變類型:相似 c++ 的值傳遞,如 整數、字符串、元組。如fun(a),傳遞的只是a的值,沒有影響a對象自己。好比在 fun(a)內部修改 a 的值,只是修改另外一個複製的對象,不會影響 a 自己。

  • 可變類型:相似 c++ 的引用傳遞,如 列表,字典。如 fun(la),則是將 la 真正的傳過去,修改後fun外部的la也會受影響

python 中一切都是對象,嚴格意義咱們不能說值傳遞仍是引用傳遞,咱們應該說傳不可變對象和傳可變對象。

python 傳不可變對象實例
#!/usr/bin/python
# -*- coding: UTF-8 -*-

def ChangeInt( a ):
    a = 10

b = 2
ChangeInt(b)
print b # 結果是 2
View Code

實例中有 int 對象 2,指向它的變量是 b,在傳遞給 ChangeInt 函數時,按傳值的方式複製了變量 b,a 和 b 都指向了同一個 Int 對象,在 a=10 時,則新生成一個 int 值對象 10,並讓 a 指向它。

傳可變對象實例
  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 可寫函數說明
  5 def changeme( mylist ):
  6    "修改傳入的列表"
  7    mylist.append([1,2,3,4]);
  8    print "函數內取值: ", mylist
  9    return
 10 
 11 # 調用changeme函數
 12 mylist = [10,20,30];
 13 changeme( mylist );
 14 print "函數外取值: ", mylist
View Code

實例中傳入函數的和在末尾添加新內容的對象用的是同一個引用,故輸出結果以下:

函數內取值:  [10, 20, 30, [1, 2, 3, 4]]
函數外取值:  [10, 20, 30, [1, 2, 3, 4]]
View Code

參數

如下是調用函數時可以使用的正式參數類型:

  • 必備參數
  • 關鍵字參數
  • 默認參數
  • 不定長參數
必備參數

必備參數須以正確的順序傳入函數。調用時的數量必須和聲明時的同樣。

調用printme()函數,你必須傳入一個參數,否則會出現語法錯誤:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可寫函數說明
  5 def printme( str ):
  6    "打印任何傳入的字符串"
  7    print str;
  8    return;
  9 
 10 #調用printme函數
 11 printme();
View Code

以上實例輸出結果:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();
TypeError: printme() takes exactly 1 argument (0 given)
View Code
關鍵字參數

關鍵字參數和函數調用關係緊密,函數調用使用關鍵字參數來肯定傳入的參數值。

使用關鍵字參數容許函數調用時參數的順序與聲明時不一致,由於 Python 解釋器可以用參數名匹配參數值。

如下實例在函數 printme() 調用時使用參數名:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可寫函數說明
  5 def printme( str ):
  6    "打印任何傳入的字符串"
  7    print str;
  8    return;
  9 
 10 #調用printme函數
 11 printme( str = "My string");
View Code

以上實例輸出結果:

My string
View Code

下例能將關鍵字參數順序不重要展現得更清楚:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#可寫函數說明
def printinfo( name, age ):
   "打印任何傳入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;

#調用printinfo函數
printinfo( age=50, name="miki" );
View Code

以上實例輸出結果:

Name:  miki
Age  50
View Code
缺省參數

調用函數時,缺省參數的值若是沒有傳入,則被認爲是默認值。下例會打印默認的age,若是age沒有被傳入:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可寫函數說明
  5 def printinfo( name, age = 35 ):
  6    "打印任何傳入的字符串"
  7    print "Name: ", name;
  8    print "Age ", age;
  9    return;
 10 
 11 #調用printinfo函數
 12 printinfo( age=50, name="miki" );
 13 printinfo( name="miki" );
View Code

以上實例輸出結果:

Name:  miki
Age  50
Name:  miki
Age  35
View Code
不定長參數

你可能須要一個函數能處理比當初聲明時更多的參數。這些參數叫作不定長參數,和上述2種參數不一樣,聲明時不會命名。基本語法以下:

def functionname([formal_args,] *var_args_tuple ):
   "函數_文檔字符串"
   function_suite
   return [expression]
View Code

加了星號(*)的變量名會存放全部未命名的變量參數。選擇很少傳參數也可。以下實例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 可寫函數說明
  5 def printinfo( arg1, *vartuple ):
  6    "打印任何傳入的參數"
  7    print "輸出: "
  8    print arg1
  9    for var in vartuple:
 10       print var
 11    return;
 12 
 13 # 調用printinfo 函數
 14 printinfo( 10 );
 15 printinfo( 70, 60, 50 );
View Code

以上實例輸出結果:

輸出:
10
輸出:
70
60
50
View Code

變量做用域

一個程序的全部的變量並非在哪一個位置均可以訪問的。訪問權限決定於這個變量是在哪裏賦值的。

變量的做用域決定了在哪一部分程序你能夠訪問哪一個特定的變量名稱。兩種最基本的變量做用域以下:

  • 全局變量
  • 局部變量

全局變量和局部變量

定義在函數內部的變量擁有一個局部做用域,定義在函數外的擁有全局做用域。

局部變量只能在其被聲明的函數內部訪問,而全局變量能夠在整個程序範圍內訪問。調用函數時,全部在函數內聲明的變量名稱都將被加入到做用域中。以下實例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 total = 0; # 這是一個全局變量
  5 # 可寫函數說明
  6 def sum( arg1, arg2 ):
  7    #返回2個參數的和."
  8    total = arg1 + arg2; # total在這裏是局部變量.
  9    print "函數內是局部變量 : ", total
 10    return total;
 11 
 12 #調用sum函數
 13 sum( 10, 20 );
 14 print "函數外是全局變量 : ", total
View Code

以上實例輸出結果:

函數內是局部變量 :  30
函數外是全局變量 :  0
View Code

5.遞歸                                                                                              

在函數內部,能夠調用其餘函數。若是一個函數在內部調用自身自己,這個函數就是遞歸函數。

def calc(n):
    print(n)
    if int(n/2) ==0:
        return n
    return calc(int(n/2))

calc(10)

輸出:
10
5
2
1
View Code

遞歸特性:

1. 必須有一個明確的結束條件

2. 每次進入更深一層遞歸時,問題規模相比上次遞歸都應有所減小

3. 遞歸效率不高,遞歸層次過多會致使棧溢出(在計算機中,函數調用是經過棧(stack)這種數據結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。因爲棧的大小不是無限的,因此,遞歸調用的次數過多,會致使棧溢出)

堆棧掃盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html 

 

遞歸函數實際應用案例,二分查找

  1 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
  2 def binary_search(dataset,find_num):
  3     print(dataset)
  4     if len(dataset) >1:
  5         mid = int(len(dataset)/2)
  6         if dataset[mid] == find_num:  #find it
  7             print("找到數字",dataset[mid])
  8         elif dataset[mid] > find_num :# 找的數在mid左面
  9             print("\033[31;1m找的數在mid[%s]左面\033[0m" % dataset[mid])
 10             return binary_search(dataset[0:mid], find_num)
 11         else:# 找的數在mid右面
 12             print("\033[32;1m找的數在mid[%s]右面\033[0m" % dataset[mid])
 13             return binary_search(dataset[mid+1:],find_num)
 14     else:
 15         if dataset[0] == find_num:  #find it
 16             print("找到數字啦",dataset[0])
 17         else:
 18             print("沒的分了,要找的數字[%s]不在列表裏" % find_num)
 19 binary_search(data,66)
View Code
6.返回值                                                                                             

要想獲取函數的執行結果,就能夠用return語句把結果返回

注意:

  1. 函數在執行過程當中只要遇到return語句,就會中止執行並返回結果,so 也能夠理解爲 return 語句表明着函數的結束
  2. 若是未在函數中指定return,那這個函數的返回值爲None
7.高階函數                                                                                        

變量能夠指向函數,函數的參數能接收變量,那麼一個函數就能夠接收另外一個函數做爲參數,這種函數就稱之爲高階函數。

  1 def add(x,y,f):
  2     return f(x) + f(y)
  3 res = add(3,-6,abs)
  4 print(res)
View Code

8. 內置參數                                                                                        

內置參數詳解 https://docs.python.org/3/library/functions.html?highlight=built#ascii 

  1 #compile
  2 f = open("函數遞歸.py")
  3 data =compile(f.read(),'','exec')
  4 exec(data)
  5 
  6 
  7 #print
  8 msg = "又回到最初的起點"
  9 f = open("tofile","w")
 10 print(msg,"記憶中你青澀的臉",sep="|",end="",file=f)
 11 
 12 
 13 # #slice
 14 # a = range(20)
 15 # pattern = slice(3,8,2)
 16 # for i in a[pattern]: #等於a[3:8:2]
 17 #     print(i)
 18 #
 19 #
 20 
 21 
 22 #memoryview
 23 #usage:
 24 #>>> memoryview(b'abcd')
 25 #<memory at 0x104069648>
 26 #在進行切片並賦值數據時,不須要從新copy原列表數據,能夠直接映射原數據內存,
 27 import time
 28 for n in (100000, 200000, 300000, 400000):
 29     data = b'x'*n
 30     start = time.time()
 31     b = data
 32     while b:
 33         b = b[1:]
 34     print('bytes', n, time.time()-start)
 35 
 36 for n in (100000, 200000, 300000, 400000):
 37     data = b'x'*n
 38     start = time.time()
 39     b = memoryview(data)
 40     while b:
 41         b = b[1:]
 42     print('memoryview', n, time.time()-start)
幾個內置方法用法提醒
相關文章
相關標籤/搜索