python從0到1--01.python中的輸入/輸出(基礎篇)
阿新 • • 發佈:2020-11-06
1.print()函式輸出
在python中,使用print()函式可以將結果輸出到標準控制檯上。
print()函式的基本語法:print(輸出內容);例如
a = 100 b = 5 print(9) print(a) print(a*b) print("hello")
使用print函式,不但可以將輸出內容到螢幕,還可以輸出到指定檔案。例如,將一個字串“要麼出眾,要麼出局”輸出到“d:\mr.txt",程式碼如下:
fp = open(r'd:\mr.txt','a+') print("要麼出眾,要麼出局",file=fp) fp.close
執行上面的程式碼後,將在d:\ 目錄下生成一個名稱為mr.txt檔案,該檔案的內容為文字“要麼出眾,要麼出局”。
當然 print函式還可以輸出日期,但是要先呼叫datetime模組,例如:
import datetime print('當前年份:' +str(datetime.datetime.now().year)) print("當前日期時間:" +datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
2.input()函式輸入
在python中,只用內建函式input可以接受使用者的鍵盤輸入。input()函式基本用法如下:
variable = input("提示文字")
其中variable為儲存輸入結果的變數,雙引號的文字使用者提示要輸入的內容。例如:
1 tip = input("請輸入文字:")
在python3.x中,無論輸入的是數字還是自發都將被作為字串讀取。
如果想要輸入是指,需要把接收到的字串進行型別轉換,例如:
num = int(input("請輸入您的幸運數字:"))
練習1:
根據輸入的年份計算年齡大小。
import datetime imyear = input("請輸入您的出生年份:") nowyear = datetime.datetime.now().year age = nowyear - int(imyear) print("您的年齡為:" +str(age ) + "歲")