目錄:
函數
1、爲什麼要使用函數
2、什麼是函數
3、函數的返回值
4、文檔化函數
5、函數傳參數
文件操作(二)
1、文件操作的步驟
2、文件的內置方法
函數:
一、爲什麼要使用函數
在日常寫代碼中,我們會發現有很多代碼是重複利用的,這樣會使我們的代碼變得異常臃腫,比如說:
我們要寫一個驗證碼的功能
例子:
比如說我們要進行一些操作,而這些操作需要填寫驗證碼
驗證碼代碼:
1 import random 2 number_check = '' 3 for i in range(0,6): 4 number_curr = random.randrange(0,5) 5 if number_curr != i: 6 number_temp = chr(random.randint(97,122)) 7 else: 8 number_temp = random.randint(0,9) 9 number_check += str(number_temp) 10 先不用管這段代碼什麼意思,後續會提到驗證碼實現代碼
例子代碼: 驗證碼代碼 驗證碼代碼 驗證碼代碼 這段文字呢就表示沒寫一個功能,加入這個功能需要驗證碼,就需要在這個功能上加判斷這樣大大增加了代碼量所以呢就產生了函數
二、什麼是函數
函數準確的來說就是實現某個功能的代碼的集合
那麼我們接着上面的例子來寫把驗證碼模塊變成一個函數
1 import random 2 3 def code():#其實這傢伙是個僞函數,因爲沒有返回值 4 5 number_check = '' 6 for i in range(0,6): 7 number_curr = random.randrange(0,5) 8 if number_curr != i: 9 number_temp = chr(random.randint(97,122))10 else:11 number_temp = random.randint(0,9)12 number_check += str(number_temp)那麼我們功能來去調用函數的時候只需要這樣import random code(): 功能1 code(): 功能2 code(): 功能3代碼如下: 1 import random 2 def code(): 3 number_check = '' 4 for i in range(0,6): 5 number_curr = random.randrange(0,5) 6 if number_curr != i: 7 number_temp = chr(random.randint(97,122)) 8 else: 9 number_temp = random.randint(0,9) 10 number_check += str(number_temp) 11 print(number_check) 12 code()#這樣我們每次運行就能看到一個隨機的字符,那麼我們怎麼拿到這個隨機的字符呢
三、函數的返回值(return)
上一小節我們學習了怎麼來創建一個函數和怎麼調用一個函數那麼我們來看看怎麼拿到函數的返回值
接着我們上面的例子:
1 import random#別忘了我!
2 def code():
3 number_check = ''#設置一個空變量
4 for i in range(0,6): #循環0到6也就是6次
5 number_curr = random.randrange(0,5)#生成一個隨機數
6 if number_curr != i: #判斷當前循環次數與隨機生成的數是否一樣
7 number_temp = chr(random.randint(97,122))#如果不一樣則生成隨機數97-122並轉化成字母
8 else:#否則
9 number_temp = random.randint(0,9)#生成0到9的任意數字
10 number_check += str(number_temp)#最後添加到變量中
11 return number_check#原來加個這貨就好了啊
12 #那麼如何調用和取到返回值呢
13
14 a_code = code()
15 print(a_code)返回值函數
四、文檔化函數
什麼叫做文檔化函數,其實就是丫的註釋!,只不過這貨寫在了函數裏面在def關鍵字下面0.0,他的目的呢只是爲了更好的註釋這個函數的功能
def code(): 'This is a function of generated random authentication code' pass pass
五、函數傳參數
有的小夥伴思考來思考去發現我沒辦法往裏面傳入參數啊,這怎麼可以那麼下面我們就講解傳參
函數分爲三種:
普通參數
默認參數
動態參數
1、普通參數
啥是普通參數,就是很普通的意思哈哈我們來看看普通參數
還是以生成隨機數爲例:假如我們想自己規定這個隨機驗證碼的長度
1 import random 2 def code(frequency): 3 frequency = int(frequency) 4 number_check = '' 5 for i in range(0,frequency): 6 number_curr = random.randrange(0,frequency) 7 if number_curr != i: 8 number_temp = chr(random.randint(97,122)) 9 else: 10 number_temp = random.randint(0,9)11 number_check += str(number_temp)12 return number_check13 in_frequency = input("請輸入次數長度:")14 a_code = code(in_frequency)15 print(a_code)隨機數傳參
!!!發生了什麼,原來def code(frequency)多了個參數下圖詳解,frequency在這裏有個別名叫做形參(形式參數),而in_frequency叫做實參(實際參數),形式參數的值由實際參數提供2、默認參數
如果說我們想給frequency來個默認值怎麼辦?def code(frequency = 3):其實就是加個等於號就好了這樣在調用的時候就不需要加上實參了a_code = code()
3、動態參數一問題來了,普通參數只能傳一個值那麼我想傳多個值就需要寫多個普通參數,就想這樣def code(frequency,frequency1,frequency2):那麼有沒有進化的方法呢?其實我們可以這樣:def code(*frequency):
例子:
1 def code(*frequency):
2 print(frequency)
3 in_frequency = [1,2,3,"dsa"]
4 code(in_frequency)
5 ([1, 2, 3, 'dsa'],)
6 或者這麼調用
7 code(1,2,3,"dsa")這樣我們就可以傳入多個參數了,注意的是傳入的值之後會變成一個元組,元組是不可修改的哦。改動態參數的方法咳咳事情不是絕對的其實這個參數還是可以修改的不過我們就要用些小技巧,藉助列表嘍,原理就是改不了元組我改列表就是了 def code(*frequency): frequency[0][0] = int(frequency[0][0])+1 print(frequency) a = [10] code(a) ([11],)
4、動態參數二
某某小夥伴說那麼那個字典能不能傳進去。啪啪啪,答案是可以:例子:
def code(**frequency): print(frequency) code(times=10) {'times': 10}最後我們來總結一下函數的幾大特點:
def:表示函數的關鍵字
函數名:表示函數的名稱,並根據函數名調用函數
函數體:這裏也就是指得邏輯運算和註釋
參數:爲函數傳入數據
返回值:經過函數執行完畢給調用者返回的結果
文件操作(二):
一.文件操作的步驟
在成長之路第一篇的第五章曾將講過了文件的一些操作,在這裏呢我們既然瞭解到了函數那我們就一起來深入的看看文件操作
首先來整理一下文件操作的幾個步驟
1、打開文件
2、操作文件
3、關閉文件
打開文件
對於打開文件來說python有兩種方式:open()和file()本質上前者會調用後者,所以推薦用open,其次如果打開的文件要做跨平臺操作的話我們就要使用二進制的方法來去打開,爲什麼呢?因爲在windows和linux上的換行符不一樣,在使用二進制來去操作文件python默認的機制會把在linux打開windows的文件會把windows下的換行符\r\n轉換成\n,同樣windows打開linux的文件也是如此,如果非要用文本模式去讀的話我們可以使用“U”來把換行符整理成\n
打開文件的模式有:
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
有人總好忘記關閉文件釋放資源,爲了方便在python2.5中增加了with語句(2.5中需要導入如下模塊才能使用'from_future_import with_statement'),並且在python2.7後with支持同時打開多個文件進行處理,並且不用再寫討厭的關閉文件語句了
with:
with
open
(
'l1'
) as A1,
open
(
'l2'
) as A2:
pass
這樣我們就可以操作A1就是操作l1文件,操作A2就是操作l2文件
文件操作源碼:
1 class file(object):
2
3 def close(self): # real signature unknown; restored from __doc__
4 關閉文件
5 """
6 close() -> None or (perhaps) an integer. Close the file.
7
8 Sets data attribute .closed to True. A closed file cannot be used for
9 further I/O operations. close() may be called more than once without
10 error. Some kinds of file objects (for example, opened by popen())
11 may return an exit status upon closing.
12 """
13
14 def fileno(self): # real signature unknown; restored from __doc__
15 文件描述符
16 """
17 fileno() -> integer "file descriptor".
18
19 This is needed for lower-level file interfaces, such os.read().
20 """
21 return 0
22
23 def flush(self): # real signature unknown; restored from __doc__
24 刷新文件內部緩衝區
25 """ flush() -> None. Flush the internal I/O buffer."""
26 pass
27
28
29 def isatty(self): # real signature unknown; restored from __doc__
30 判斷文件是否是同意tty設備
31 """ isatty() -> true or false. True if the file is connected to a tty device."""
32 return False
33
34
35 def next(self): # real signature unknown; restored from __doc__
36 獲取下一行數據,不存在,則報錯
37 """ x.next() -> the next value, or raise StopIteration"""
38 pass
39
40 def read(self, size=None): # real signature unknown; restored from __doc__
41 讀取指定字節數據
42 """
43 read([size]) -> read at most size bytes, returned as a string.
44
45 If the size argument is negative or omitted, read until EOF is reached. 46 Notice that when in non-blocking mode, less data than what was requested 47 may be returned, even if no size parameter was given.
48 """
49 pass
50
51 def readinto(self): # real signature unknown; restored from __doc__
52 讀取到緩衝區,不要用,將被遺棄
53 """ readinto() -> Undocumented. Don't use this; it may go away."""
54 pass
55
56 def readline(self, size=None): # real signature unknown; restored from __doc__
57 僅讀取一行數據
58 """
59 readline([size]) -> next line from the file, as a string.
60
61 Retain newline. A non-negative size argument limits the maximum
62 number of bytes to return (an incomplete line may be returned then).
63 Return an empty string at EOF.
64 """
65 pass
66
67 def readlines(self, size=None): # real signature unknown; restored from __doc__
68 讀取所有數據,並根據換行保存值列表
69 """
70 readlines([size]) -> list of strings, each a line from the file.
71
72 Call readline() repeatedly and return a list of the lines so read.
73 The optional size argument, if given, is an approximate bound on the
74 total number of bytes in the lines returned.
75 """
76 return []
77
78 def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
79 指定文件中指針位置
80 """
81 seek(offset[, whence]) -> None. Move to new file position.
82
83 Argument offset is a byte count. Optional argument whence defaults to
84 0 (offset from start of file, offset should be >= 0); other values are 1
85 (move relative to current position, positive or negative), and 2 (move
86 relative to end of file, usually negative, although many platforms allow
87 seeking beyond the end of a file). If the file is opened in text mode,
88 only offsets returned by tell() are legal. Use of other offsets causes
89 undefined behavior.
90 Note that not all file objects are seekable.
91 """
92 pass
93
94 def tell(self): # real signature unknown; restored from __doc__
95 獲取當前指針位置
96 """ tell() -> current file position, an integer (may be a long integer)."""
97 pass
98
99 def truncate(self, size=None): # real signature unknown; restored from __doc__
100 截斷數據,僅保留指定之前數據
101 """
102 truncate([size]) -> None. Truncate the file to at most size bytes.
103
104 Size defaults to the current file position, as returned by tell().
105 """
106 pass
107
108 def write(self, p_str): # real signature unknown; restored from __doc__
109 寫內容
110 """
111 write(str) -> None. Write string str to file.
112
113 Note that due to buffering, flush() or close() may be needed before
114 the file on disk reflects the data written.
115 """
116 pass
117
118 def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
119 將一個字符串列表寫入文件
120 """
121 writelines(sequence_of_strings) -> None. Write the strings to the file.
122
123 Note that newlines are not added. The sequence can be any iterable object
124 producing strings. This is equivalent to calling write() for each string.
125 """
126 pass
127
128 def xreadlines(self): # real signature unknown; restored from __doc__
129 可用於逐行讀取文件,非全部
130 """
131 xreadlines() -> returns self.
132
133 For backward compatibility. File objects now include the performance
134 optimizations previously implemented in the xreadlines module.
135 """
136 passView Code