Python入門教程04——基本輸入輸出

基本輸入

Python使用

input()

函式輸入資料,其基本語法如下:

a = input(“請輸入資料:”) print(a)

input()

函式將使用者輸入的內容作為字串返回。使用者按【Enter】鍵結束輸入,【Enter】鍵之前的全部字元均作為輸入內容。指定變數時,變數將儲存輸入的字串。

如果需要輸入整數或小數,則應使用i

nt()

float()

函式轉換資料型別,例如:

a=input(‘請輸入一個整數:’) # 請輸入一個整數:5 print(type(a)) # 輸出a的型別 a+1 # 因為a中是一個字串,試圖執行加法運算,所以出錯 ‘’‘ 結果: 請輸入一個整數:1 Traceback (most recent call last): File “/home/lyujch/mu_code/py/run。py”, line 3, in ’‘’int(a) + 1 # 使用int()函式將a轉化為整數型別

eval()

函式可返回字串運算後的內容,例如:

a = eval(‘123’) # 等同於a=123 print(a) # 123 print(type(a)) # x = 10 a=eval(‘x+20’) # 等同於a=x+20 print(a) # 30 a = eval(input(‘請輸入一個整數或小數:’)) # 請輸入一個整數或小數:12 print(a) # 12 print(type(a)) # a=eval(input(‘請輸入一個整數或小數:’)) # 請輸入一個整數或小數:12。34 print(a) # 12。34 print(type(a)) #

基本輸出

Python使用

print()

函式進行輸出,其語法格式如下:

print([obj1, 。。。][, sep=‘’] [, end=‘\n’][, file=sys。stdout])

print()

函式的所有引數均可省略。無引數時,

print()

函式輸出一個空行。

print()

函式可同時輸出一個或多個數據,預設使用空格分隔,例如:

print(123) # 輸出一個數據 123print(123, ‘abc’, 45, ‘book’) # 輸出多個數據 123 abc 45 book

print()

函式可用

sep

引數指定分隔符號,例如:

print(123, ‘abc’, 45, ‘book’, sep=‘#’) # 指定符號‘#’作為輸出分隔符 123#abc#45#book

print()

函式可用

end

引數指定輸出結尾符號,預設為換行符,例如:

print(‘price’);print(100) # 預設輸出結尾,兩個資料輸出在兩行‘’‘結果:price100’‘’print(‘price’,end=‘_’);print(100) # 指定下劃線為輸出結尾符號,兩個資料輸出在一行‘’‘結果:price_100’‘’

print()

函式可用

file

引數指定輸出到檔案,預設是標準輸出流

sys。stdout

,即命令列。例如:

datafile = open(r‘d:\data。txt’, ‘w’) # 開啟檔案print(123, ‘abc’, 45, ‘book’, file=datafile) # 用file引數指定輸出檔案data。txtdatafile。close() # 關閉檔案

上述程式碼建立了一個data。txt檔案,

print()

函式將資料輸出到該檔案。可用記事本開啟data。txt檔案檢視其內容。

如果覺得我寫的還不錯,就請關注我吧,我主頁會更新Python系列完整課程。您的鼓勵和支援是我創作的最大動力。