高見龍

iOS app/Ruby/Rails Developer & Instructor, 喜愛非主流的新玩具 :)

安裝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,例如我們把下面這段很簡單的程式碼:

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

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

> python test.py
Hello, Python

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

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

Comments