指令互動環境


你可以至 Python 的官方網站 下載安裝Python,初學Python,可以執行Python安裝目錄中的python指令,啟動指令互動環境來作些簡單的程式練習,可以自行進入文字模式,設定PATH中包括Python安裝目錄,再執行python指令,或者是直接在Windows中點選python可執行檔以進入指令互動環境:
Type "help", "copyright", "credits" or "license" for more information.
>>>


這是Python的指令互動環境,可以讓你很快地撰寫一些小指令進行測試(經常的,你只是要看看某個指令這麼用對不對,或會有什麼結果),先 來看看幾個簡單的互動:
>>> 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 do_some():
...     print('Hi')
...
>>> do_some()
Hi
>>> class Test:
...
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>

你 可以在互動中直接觀察程式碼的執行結果,如果程式碼定義需要超過一行,例如for語句(Statement),則必須使用冒號 : 並按下Enter,會有個...表示你可以繼續撰寫程式碼,直到程式 碼定義完成。

在Python中縮排是程式碼的一部份,而且縮排的空白數必須相同,這強迫程式設計人員必須有良好的縮排習慣。如果你在定義程式碼的過程中輸入錯誤了,儘管直接按兩次Enter,兩個空白行後,這會因為縮排錯誤,而使得Python回到>>>提示 字元狀態。

以下有個程式執行錯誤的畫面:
>>> x = 10
>>> print x
  File "<stdin>", line 1
    print x
          ^
SyntaxError: invalid syntax
>>> print(x)
10
>>> x = 'text'
>>> print(x)
text
>>>

在Python3中,print不再是個語句,而是個函式,必須使用括號並傳入要顯示的值。Python是個動態語言,變數不需宣告就可以直接使用,變數本身也沒有型態,同一個變數可以指定不同的資料型態。

若要取得協助訊息,可以輸入help(),例如:
>>> help()

Welcome to Python 3.1!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/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, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

這會進入help()說明頁面,注意提示符號變成了help>,接下來你可以輸入想要查詢的函式、模組或物件名稱:s
help> print
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    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.

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 elif                import              return
as                  else                in                  try
assert              except              is                  while
break               finally             lambda              with
class               for                 not                 yield
continue            from                or
def                 global              pass
del                 if                  raise

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(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    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.

>>>

以上示範了幾個說明頁面的使用方式,輸入quit可以離開help頁面,help()中也可以直接指定要查詢的對象,例如help(print)就可以查詢print函式的相關說明。

如果只是要執行個小程式片段,又不想麻煩地進入指令互動模式,則可以在使用python指令時加上-c引數,之後接上你的程式。例如:
> python -c "print('Hello! Python!')"
Hello! Python!

這可以應用在取用說明文件時:
> python -c "help(print)"
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    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.

在指令互動環境中,有個小小的彩蛋,輸入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取得可使用的啟動選項。