Hello, Python
April 8, 2022你可以至 Python 的官方網站下載安裝 Python:
Python 官方網站下載的是 CPython,也就是以 C 撰寫的實作品,提供 Python 套件(Package)與 C 擴充模組的最高相容性。
REPL 環境
初學 Python,可以執行 Python 安裝目錄的 python
指令,啟動 REPL(read–eval–print loop)環境來做些簡單的程式練習,可以自行進入文字模式,設定 PATH
包括 Python 安裝目錄,再執行 python
指令(Windows 版本的安裝程式,預設就會設定 PATH
):
Type "help", "copyright", "credits" or "license" for more information.
>>>
這是個指令互動環境,可以讓你很快地撰寫一些小指令進行測試(經常地,你只是想看看某指令這麼用對不對,或會有什麼結果),先來看看幾個簡單的互動:
>>> 1 + 2
3
>>> _
3
>>> 1 + _
4
>>> _
4
>>>
這執行了 1 + 2
,顯示結果為 3,在指令互動環境中,_
代表了上一次運算結果,方便於下一次運算直接取用;在指令互動環境下按 Home 可以將游標移至行首,按 End 可以將游標移至行尾。
再來看看其他的一些互動:
>>> print('Hello, Python')
Hello! Python!
>>> for i in range(1, 4):
... print(i)
...
1
2
3
>>> def some():
... print('Hello')
...
>>> some()
Hello
>>> class Test:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block after class definition on line 1
>>>
可以在互動中直接觀察程式碼的執行結果,如果程式碼定義需要超過一行,例如 for
語句(Statement),必須使用冒號 :
並按下 Enter,互動環境會使用…」提示可以繼續撰寫程式碼,直到程式碼定義完成。
在 Python 中縮排是程式碼的一部份,而且縮排的空白數必須相同,這強迫程式設計人員必須有良好的縮排習慣。如果你在定義程式碼的過程中輸入錯誤了,可直接按兩次 Enter,輸入兩個空白行後會因為縮排錯誤,而回到 »> 提示字元狀態。
以下是一個程式執行錯誤的畫面,因為 print
是個函式,必須使用括號並傳入要顯示的值:
>>> x = 10
>>> print x
File "<stdin>", line 1
print x
^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Python是個動態語言,變數不需宣告就可以直接使用,變數本身也沒有型態,同一個變數可以指定不同的資料型態:
>>> x = 10
>>> print(x)
10
>>> x = 'text'
>>> print(x)
text
>>>
help 查詢頁面
若要取得協助訊息,可以輸入 help()
:
>>> help()
Welcome to Python 3.10's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.10/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help>
help> 表示目前是在說明頁面模式,接下來可以輸入想查詢的函式、模組或物件名稱,例如查詢 print
說明:
help> print
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
help>
或者是查詢關鍵字:
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help>
輸入 quit
可以離開 help 頁面:
help> quit
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>
help()
也可以直接指定要查詢的對象,例如 help(print)
就可以查詢 print
函式的相關說明:
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>>
The Zen of Python
在指令互動環境中,有個小小的彩蛋,輸入 import this
,會顯示出 Python 的設計哲學:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>>
如果要結束指令互動環境,可以鍵入 quit()
或 exit()
。在執行 python
指令之前,可以鍵入 -h
取得可使用的啟動選項。
第一個 .py 檔案
你可以撰寫一個純文字檔案,建議副檔名為 .py,例如 hello.py,在當中撰寫 Python 程式碼:
print('Hello, Python')
接著如下執行指令載入指令稿直譯並執行:
> python hello.py
Hello, Python
Python 是直譯式語言,不過並非每次都從原始碼直譯後執行,CPython 會將原始碼編譯為中介位元碼(Bytecode),之後再由虛擬機器載入執行,每次執行同一程式時,若原始碼檔案偵測到沒有變更,就不會對原始碼進行語法剖析等動作,而可以從位元碼開始直譯,以加快直譯速度。
在 Python 中,一個 .py 檔案就是一個模組,這部份的說明就留待下一篇文件了…