安裝 Python

不管你用的 Linux/FreeBSD/MacOS/Windows..etc,目前 Python 均有實作品,請至 http://python.org/getit/ 找到適合的平台並下載安裝。

不過,我不得小小抱怨一下,Python 在 Windows 上實在是不怎麼友善,包括我們之後要講的 Django,原本也有給 Windows 的懶人安裝包(Instant Django),但專案似乎也斷頭了。不過也不是沒有解決方法,如果只是要在 Windows 做練習的話,可參考下一章

如果你安裝完成,請打開你的終端機視窗,輸入python就可以進入 interactive shell 來試玩一下:

$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "hello python"
'hello python'
>>> 1 + 2
3

在這個 shell 裡面,你可以很容易的就測試一些簡單的程式碼,看看執行結果是不是跟你想像的是一樣的。有趣的是,如果你在 shell 裡輸入 import this 的話:

>>> 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!

你可以看到 Tim Peters 寫的 The Zen of Python,內文大概說明了 Python 世界的設計哲學。至於 import 是做什麼用的,我們在後面的單元會再做說明。

除了 shell 之外,我們更常把程式碼儲存成一個檔案,附檔名是 .py,例如我們把下面這段很簡單的程式碼:

#!/usr/bin/python
print "Hello, Python"

用任何文字編輯器打完之後,存檔為 hello.py,然後回到終端機視窗,輸入 python hello.py

$ python test.py
Hello, Python

每種程式語言一定都要不免俗的來一下 Hello World 打個招呼的,如果在 Java,你可能為了要輸出一行簡單的字,還得寫個類別或方法才行,在 Python,只要一行 print 就搞定了,相當簡單吧 :)

其實老是 Hello World 也沒什麼意義,接下來我們來看一點稍微複雜一點的..