萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 程式設計入門基礎知識:互動模式、腳本模式、識別字、保留字、縮排、多行陳述式

本文整理 Python 入門必備基礎知識,包含互動模式與腳本模式執行方式、識別字命名規則、保留字清單、縮排規則、多行陳述式撰寫方式,適合初學者快速建立正確觀念。

第一個 Python 程式

互動模式

$ python
>>> print "Hello, Python!"
Hello, Python!

腳本模式

# test.py
print "Hello, Python!"

$ python test.py
Hello, Python!

# 加入 shebang 直接執行
#!/usr/bin/python
print "Hello, Python!"
$ chmod +x test.py
$ ./test.py

識別字命名規則

  • 以字母(A-Z, a-z)或底線 _ 開頭,後接字母、底線、數字(0-9)。
  • 區分大小寫(Manpower ≠ manpower)。
  • 不可使用標點符號(@, $, % 等)。

命名慣例

  • 類別名:大寫開頭(MyClass)。
  • 變數/函數/模組:小寫開頭(my_function)。
  • 單底線開頭 _private:慣例為私有。
  • 雙底線開頭 __strong_private:名稱修飾(name mangling)。
  • 雙底線開頭結尾 __special__:語言內建特殊名稱。

保留字(關鍵字)

Python 保留字表

完整清單:and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield 等(Python 2.x)。

縮排規則

  • 使用縮排(空白鍵)表示程式區塊,不使用大括號。
  • 同一區塊縮排層級必須一致。
  • 建議使用 4 空白縮排,勿混合 Tab 與空白。

多行陳述式

  • 反斜線 \ 續行:total = item_one + \ item_two + \ item_three
  • 括號 () [] {} 內隱含續行:days = ['Mon', 'Tue', 'Wed']

註解

  • 單行:# 這是註解
  • 多行:使用三引號字串 """ 多行註解 """(實為字串常數)。
copyright © 萬盛學電腦網 all rights reserved