大爽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.stdout
flush=False
:flush
默認值為False
然后繼續往下
objects
to the text streamfile
, separated bysep
and 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 by
sepand followed by
end. Both
sepand
endmust be strings; they can also be
None, which means to use the default values. If no
objectsare given,
print()will just write
end`.
所有非關鍵字參數(即位置參數),都會使用str()
方法轉換為字符串並寫入流,使用sep
來分割,最后接end
。
sep
和end
都必須是字符串;它們也可以是None
,這意味着使用默認值。
如果沒有傳入objects
,print()
將只輸出end
。
The
file
argument must be an object with awrite(string)
method; if it is not present orNone
,sys.stdout
will 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 theflush
keyword argument is true, the stream is forcibly flushed.
輸出是否緩沖通常由file
決定,但如果flush
關鍵字參數為真,則流被強制刷新。
Changed in version 3.3: Added the
flush
keyword 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,