引言:
在上一週內我作爲助教,有幸能免費聽Alex老師的直播一對一教學,課程的主題是python基礎,但對我這個已經熟悉過python語法(但使用方面很生疏)的人來說,也是有不少乾貨的,這個系列博客就上課過程中,一些對我有幫助的內容進行復述總結,算是基於我消化吸收後的再創作吧。而原課程的錄像以及ppt和代碼則作爲csdn的付費課程發佈,有興趣的同學可以自行購買課程,這裏附上鍊接:https://edu.csdn.net/course/detail/20599
print()函數
學習過c語言的朋友們一定一眼就看的出print()函數大概是做什麼用的。c語言中與其相似的printf()函數及大致用法如下
#include<stdio.h>
int main(void){
printf("這是一串字符");
return 0;
}
使用printf()很麻煩,以上所有代碼一起出現,才能使終端出現“這是一串字符”,而且也很功能單一。
那麼我們來看看python中的print()函數。
print()
我們首先在pycharm中輸入一個 ‘print()’ ,然後按住鍵盤上的ctrl鍵同時鼠標左擊輸入的 ‘print()’ ,這樣就打開所有庫函數的源代碼 如下圖:
找到print()
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
英語學的還不錯的同學一目瞭然,不過我還是一一解釋,來給大家看
- print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
這是print函數的調用格式,括號裏面是其參數。 - Prints the values to a stream, or to sys.stdout by default. 在流中或默認的終端輸出值,
- Optional keyword arguments:可選擇的參數解析。
- file: a file-like object (stream); defaults to the current sys.stdout.輸出對象(流)比如一個文件,默認爲終端。
- sep: string inserted between values, default a space.在值之間插入字符,默認爲一個空格。
- end: string appended after the last value, default a newline.在最後一個值後添加字符,默認爲一個換行符。
- flush: whether to forcibly flush the stream.是否釋放流。
具體例子可以在視頻課程中找到,此處贈上b站免費版課程(無ppt和代碼):https://t.bilibili.com/400013329599284093?tab=2
其中有一個比較有趣的例子是:
用python實現打印機功能
import time
def printer(content,delay):
for char in content:
print(char, end='', flush=True)
time.sleep(delay)
printer('有內鬼,終止交易!',0.3)
針對這個例題留下的作業是:完成一個 轉動加載圖案。完成代碼如下:
import time
def printer(content,delay):
for char in content:
print(char, end='', flush=True)
time.sleep(delay)
print('\b',end='',flush=True)
for i in range (100000000):
printer('/——\\——', 0.00000000000001)
結語: 更詳細的講解見視頻課程哦:https://www.bilibili.com/video/BV1Qg4y1i7xT