第一關:print()函數 - 0入門到進階(附練習題) | Python基礎語法

在python裏面,print()函數是我們最先接觸到的,它是一個輸出函數。你可以用它來輸出你想要的東西。

下面小編就整理了在編程中,比較常用的print()函數入門到進階的用法。

Python基礎語法 - 專欄鏈接

1.  print() 函數

無引號print(): 讓計算機讀懂括號裏的內容,打印最終的結果。

單引號print(' '): 讓計算機無需理解,原樣打印引號中間的內容。

雙引號print(" "): 讓計算機無需理解,原樣打印引號中間的內容。

三引號print(''' '''): 讓計算機無需理解,原樣打印引號中間的分段內容。

轉義字符 \ +轉義內容英文縮寫首字母:

切記:符號和標點要使用英文輸入法!

2.  print() 函數語法

print(*objects, sep=' ', end='\n', file=sys.stdout,flush=False)

參數的具體含義如下:

2.1  objects --表示輸出的對象。輸出多個對象時,需要用 , (逗號)分隔。

print('hello')
print('hello','world')
#hello
#hello world

2.2  sep -- 用來間隔多個對象。

print("www", "baidu", "com", sep=".")
#www.baidu.com

2.3  end -- 用來設定以什麼結尾。默認值是換行符 \n,我們可以換成其他字符。

print('hello',end='~')
#hello~

2.4  file -- 要寫入的文件對象。

f = open(r"test.txt","w")
# 打開test.txt文件,w爲寫入模式    
print('hello word',file = f)
# 輸出hello word數據到test.txt文件中
f.close()
# 關閉文件

2.5  flush--參數用於控制輸出緩存,一般爲了可以獲得較好的性能,保持爲False即可,爲True則刷新數據。

import time
f = open(r"test.txt","w")
# 打開test.txt文件,w爲寫入模式  
for i in range(1,6):    # 循環1-5
    # flush=True 此時終端數據會每秒打印數據 False則一起打印所有數據
    print(i,file = f,flush=True)    # 把1-5數據寫入到文件
    time.sleep(1)   # 延遲一秒執行
    f1 = open(r"test.txt","r")  # 讀取寫入過數據的test.txt文件 
print(f1.read())    # 打印數據

3.  print() 函數變量的輸出

無論什麼類型的數據,包括但不侷限於:數值型,布爾型,列表變量,字典變量...都可以直接輸出。

num = 1
print(num) 
#1 輸出數值型變量

str = 'Hello World'
print(str) 
# Hello World 輸出字符串變量

list = [1,2,'a']
print(list) 
#[1, 2, 'a'] 輸出列表變量

tuple = (1,2,'a')
print(tuple) 
#(1, 2, 'a') 輸出元組變量

dict = {'a':1, 'b':2}
print(dict) 
# {'a': 1, 'b': 2} 輸出字典變量

4.  數據的格式化輸出

# 字符串格式化輸出  %s
s = 'hi'
print('%s hello world' % s)
# hi hello world

# 整型數字格式化輸出  %s
age = 18
print('我今年%d歲了' % age)
# 我今年18歲了

# 浮點型小數格式化輸出  %f 默認保留6位四捨五入小數,%.3f代表保留3位小數
f = 3.1415926535
print('π約等於%f' % f)
# π約等於3.141593

5.  format用法

相對基本格式化輸出採用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號‘{}’作爲特殊字符代替‘%’

5.1  位置匹配

  (1)不帶編號,即”{}”

  (2)帶數字編號,可調換順序,即”{1}”、”{2}”

  (3)帶關鍵字,即”{a}”、”{b}”

print('{} {}'.format('hello','world'))  # 不帶字段
# hello world
print('{0} {1}'.format('hello','world'))  # 帶數字編號
# hello world
print('{0} {1} {0}'.format('hello','world'))  # 打亂順序 0和1爲 format的參數位置,該位置從索引0開始
# hello world hello
print('{2}, {1}, {0}'.format(*'abc'))  # 可打亂順序
# 'c, b, a'
print('{a} {b} {a}'.format(b='hello',a='world'))  # 帶關鍵字
# world hello world

5.2  進階用法

左中右對齊及位數補全

(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用於數字)在小數點後進行補齊

(2)取位數“{:4s}”、"{:.2f}"等

print('{} and {}'.format('hello','world'))  # 默認左對齊
# hello and world
print('{:10s} and {:>10s}'.format('hello','world'))  # 取10位左對齊,取10位右對齊
# hello      and      world
print('{:^10s} and {:^10s}'.format('hello','world'))  # 取10位中間對齊
#   hello    and   world
print('{} is {:.2f}'.format(1.123,1.1234))  # 取2位小數
# 1.123 is 1.12
print('{0} is {0:>10.2f}'.format(1.123))  # 取2位小數,右對齊,取10位
# 1.123 is       1.12
print('{:<20}'.format('left align'))  # 左對齊
# left align
print('{:>20}'.format('right align'))  # 右對齊
#          right align
print('{:^20}'.format('centered'))  # 中間對齊
#      centered
print('{:*^20}'.format('center'))  # 使用*填充
# ******center******

練習題

同學們,先自覺練習,答案在公衆號,公衆號回覆暗號【答案】即可。

1. 下列哪個選項可以打印出下列數據(多選):

# this's an apple.
# Yes.

A. print('this\'s an apple.\tYes.')
B. print("this\\'s an apple.Yes.")
C. print("this's an apple.\nYes.")
D. print('this\'s an apple.\nYes.')

2. 下列哪個選項可以打印出下列數據(單選):

# www.csdn.net-專業IT技術社區

A. print('www','csdn','net',sep='.',end='-專業IT技術社區')
B. print('www','csdn',sep='.','net',end='-專業IT技術社區')
C. print('www','csdn','net',end='-專業IT技術社區')

3. 下列哪個選項可以打印出下列數據(單選):

# 媽媽給了5歲的小明6.5塊錢去買一瓶醬油。

A. print('%s給了%d歲的小明%.1f塊錢去買一瓶醬油。' % ('媽媽',5,6.52))
B. print('%d給了%d歲的小明%.1f塊錢去買一瓶醬油。' % ('媽媽',5,6.5))
C. print('%s給了%d歲的小明%f塊錢去買一瓶醬油。' % ('媽媽',5,6.5))
D. print('%s給了%d歲的小明%.1f塊錢去買一瓶醬油。'  ('媽媽',5,6.5))

 

4. 打印出以下"口"字形。(提示:使用< (默認)左對齊、> 右對齊、^ 中間對齊,以及*填充)

*******
*     *
*     *
*******

5. 打印99乘法表。(提示:先觀察每一行數據變化的規律,每一行的數據都會多一項,並且數據依次遞增)

1 * 1 = 1
1 * 2 = 2   2 * 2 = 4
1 * 3 = 3   2 * 3 = 6   3 * 3 = 9
1 * 4 = 4   2 * 4 = 8   3 * 4 = 12   4 * 4 = 16
1 * 5 = 5   2 * 5 = 10   3 * 5 = 15   4 * 5 = 20   5 * 5 = 25
1 * 6 = 6   2 * 6 = 12   3 * 6 = 18   4 * 6 = 24   5 * 6 = 30   6 * 6 = 36
1 * 7 = 7   2 * 7 = 14   3 * 7 = 21   4 * 7 = 28   5 * 7 = 35   6 * 7 = 42   7 * 7 = 49
1 * 8 = 8   2 * 8 = 16   3 * 8 = 24   4 * 8 = 32   5 * 8 = 40   6 * 8 = 48   7 * 8 = 56   8 * 8 = 64
1 * 9 = 9   2 * 9 = 18   3 * 9 = 27   4 * 9 = 36   5 * 9 = 45   6 * 9 = 54   7 * 9 = 63   8 * 9 = 72   9 * 9 = 81

 

每週每日,分享Python實戰代碼,入門資料,進階資料,基礎語法,爬蟲,數據分析,web網站,機器學習,深度學習等等。


​微信羣(關注「Python家庭」一起輕鬆學Python吧)

​QQ 羣(983031854

發佈了10 篇原創文章 · 獲贊 72 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章