大爽Python入門公開課教案 點擊查看教程總目錄
以
學習讀懂函數的過程。
1 內置函數
現在,讓我們再來詳細認識下print這個函數。
print屬於內置函數,built-in functions。
內置函數的官方文檔為 Built-in Functions
如下圖所示

在其中,點擊print函數鏈接,跳轉到print對應的說明。
截圖如下

2 試讀print官方文檔
先嘗試讀下官方文檔。
這里我們一句一句來讀。
首先是函數聲明,
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
先初步解讀下這些形參
*objects: 接受不定數量的參數。sep=' ':sep默認值為' 'end='\n':end默認值為'\n'file=sys.stdout:sep默認值為sys.stdoutflush=False:flush默認值為False
然后繼續往下
objectsto the text streamfile, separated bysepand followed byend.
sep, end, file and flush, if present, must be given as keyword arguments.
將objects打印到文本流file中,使用sep來分割,最后接end。
如果存在sep、end、file或flush, 必須使用關鍵字參數來傳參。
All non-keyword arguments are converted to strings like
str()`` does and written to the stream, separated bysepand followed byend. Bothsepandendmust be strings; they can also beNone, which means to use the default values. If noobjectsare given,print()will just writeend`.
所有非關鍵字參數(即位置參數),都會使用str()方法轉換為字符串並寫入流,使用sep來分割,最后接end。
sep和end都必須是字符串;它們也可以是None,這意味着使用默認值。
如果沒有傳入objects,print() 將只輸出end。
The
fileargument must be an object with awrite(string)method; if it is not present orNone,sys.stdoutwill be used.
Since printed arguments are converted to text strings,print()cannot be used with binary mode file objects.
For these, usefile.write(...)instead.
file參數必須是具有 write(string)方法的對象; 如果它不存在或無,將使用 sys.stdout。
由於打印的參數被轉換為文本字符串,print()不能用於二進制模式文件對象。
對於這些,請改用file.write(...)。
Whether output is buffered is usually determined by
file, but if theflushkeyword argument is true, the stream is forcibly flushed.
輸出是否緩沖通常由file決定,但如果flush關鍵字參數為真,則流被強制刷新。
Changed in version 3.3: Added the
flushkeyword argument.
在 3.3 版更改: 添加了 flush 關鍵字參數。
說實話,我也沒太讀懂
flush。
file也只是大概懂了。。。
3 大概總結
再回來看下函數頭print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
file和flush太高級了,就不去理解了。
說下這三個
*objects: 接受所有的位置參數(非關鍵詞參數),輸出這些sep: 輸出時,用sep作為分隔符,不指定則使用空格end: 輸出時,用end來結尾,不指定則使用換行\n
4 代碼示例
print("a", end=" ")
print("b", end=" ")
print("c", end=" ")
print()
print("-"*20)
print(1, 2, 3, 4, sep="-")
print("-"*20)
words = list("abcdefg")
for word in words:
print(word, end=",")
輸出如下
a b c
--------------------
1-2-3-4
--------------------
a,b,c,d,e,f,g,
