通常,一個程式都會有輸入/輸出,這樣可以與使用者進行互動。使用者輸入一些資訊,你會對他輸入的內容進行一些適當的操作,然後再輸出給使用者想要的結果。Python的輸入/輸出,我們可以用input進行輸入,print進行輸出,這些都是簡單的控制台輸入/輸出,複雜的有處理檔案等。
1. input和print
name = input("Please input your name:\n")print("Hello,", name)
運行結果:
Please input your name:
known
Hello, known
2. 處理檔案
poem = '''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''f = open('poem.txt', 'w') #open for 'w'ritingf.write(poem) #write text to filef.close() #close the filef = open('poem.txt')#if no mode is specified, 'r'ead mode is assumed by defaultwhile True: line = f.readline() if len(line) == 0:#Zero length indicates EOF break print(line), #Notice comma to avoid automatic newline added by Pythonf.close()#close the file
運行結果:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
open一個檔案模式可以為讀模式('r')、寫入模式('w')或追加模式('a'),還有其他模式,你可以用help(open)來查看。