- hello.py
import sys
print('Hello!' + sys.argv[1] + '!')如下執行指令載入指令稿直譯並執行:
| > python hello.py caterpillar Hello!caterpillar! |
在程式執行的過程中,可以使用input()函式取得使用者的輸入,input()可以指定提示文字,使用者輸入的文字則以字串傳回。例如:
- hello.py
name = input('請輸入你的名稱:')
print('歡迎 ', name)如下執行指令載入指令稿直譯並執行:
| > python hello.py 請輸入你的名稱:良葛格 歡迎 良葛格 |
到目前為止,輸出都是使用print()函式,使用help查詢其說明:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
可以看到,除了指定值輸出之外,還可以使用sep指定每個輸出值之間的分隔字元,預設值為一個空白,可以使用end指定輸出後最後一個字元,預設值是'\n'。例如:
| >>> print(1, 2, 3)1 2 3 >>> print(1, 2, 3, sep='')123 >>> print(1, 2, 3, sep='', end='\n\n')123 >>> |
預設的輸出是系統標準輸出,可以使用file指定至其它的輸出。例如以下會將指定的值輸出至data.txt:
| >>> print(1, 2, 3, file = open('data.txt', 'w')) >>> |
open()函式會開啟檔案,並傳回一個_io.TextIOWrapper物件,上例將之指定給print()作為輸出目標。
你可以格式化字串,例如:
| >>> text = '%d %.2f %s' % (1, 99.3, 'Justin') >>> print(text)1 99.30 Justin >>> print('%d %.2f %s' % (1, 99.3, 'Justin'))1 99.30 Justin >>> |
格式化字串時,所使用的%d、%f、%s等與C語言類似,之後使用%接上一個tuple,也就是範例中以()包括的實字表示部份。如果你要將使用者的輸入字串轉換為整數、浮點數、布林值等型態,可以使用int、float、bool等類別來建構對應物件。例如:
| >>> int('1')1 >>> float('3.14')3.14 >>> bool('true')True >>> |
如果你要將資料寫入檔案或從檔案讀出,可以使用open()函式:
open(file,mode="r",buffering=None,encoding=None,
errors=None,newline=None,closefd=True)
errors=None,newline=None,closefd=True)
例如,若要讀取檔案:
- show.py
name = input('請輸入檔名:')
file = open(name, 'r', encoding='UTF-8')
content = file.read()
print(content)read()方法會一次讀取所有的檔案內容,如果要逐行讀取,則可以使用readline()方法。例如:
- show.py
name = input('請輸入檔名:')
file = open(name, 'r', encoding='UTF-8')
while True:
line = file.readline()
if not line: break
print(line, end='')如果資料讀取完畢,readline()會傳回空字串,這在布林判斷式中會是false。另一個比較簡潔的方式是使用for迴圈。例如:
- show.py
name = input('請輸入檔名:')
for line in open(name, 'r', encoding='UTF-8').readlines():
print(line, end='')readlines()方法會用一個字串陣列收集讀取的每一行,for迴圈每次取出字串陣列中的一個字串元素,並使用print()函式顯示。事實上,更有效率的方式,是呼叫檔案物件的next()方法,next()方法每次傳回下一行,並在沒有資料可讀取時丟出StopIteration。可以使用for迴圈自動呼叫next()方法,並在捕捉到StopIteration時離開迴圈。例如:
- show.py
name = input('請輸入檔名:')
for line in open(name, 'r', encoding='UTF-8'):
print(line, end='')這個程式牽涉到更多的技術細節,現階段你只要記得有這種用法,技術細節在之後的文件還會介紹。
如果要寫資料至檔案,則在使用open()函式時,指定模式為'w',並使用write()方法進行資料寫入。例如:
name = input('請輸入檔名:')
file = open(name, 'w', encoding = 'UTF-8')
file.write('test')在不使用檔案時,可以使用close()將檔案關閉以節省資源。若需要了解更多open()函式的細節,記得使用help進行查詢。
沒有留言:
張貼留言