標籤:python指令碼 iss linu effect 快捷文法 set 基礎文法 tab fixed
第一個Python程式 互動式編程
互動式編程不需要建立指令碼檔案,是通過 Python 解譯器的互動模式進來編寫代碼。
linux上你只需要在命令列中輸入 Python 命令即可啟動互動式編程,提示視窗如下:
Window上在安裝Python時已經已經安裝了預設的互動式編程用戶端,提示視窗如下:
在Python提示符中輸入一下文本,然後按斷行符號查看運行結果:
print ‘hello world‘;
輸出:
hello world
指令碼式編程
讓我們來寫一個簡單的Python指令碼,所有的Python指令碼都要以.py為副檔名,以下是hello.py的內容:
print ‘hello python!‘;
使用以下命令運行hello.py:
python hello.py
輸出結果:
hello python
Python標識符
在python裡,標識符有字母、數字、底線組成。
在python中,所有標識符可以包括英文、數字以及底線(_),但不能以數字開頭。
python中的標識符是區分大小寫。
以底線開頭的標識符是有特殊意義的。以單底線開頭(_foo)的代表不能直接存取的類屬性,需通過類提供的介面進行訪問,不能用"from xxx import *"而匯入;
以雙底線開頭的(__foo)代表類的私人成員;以雙底線開頭和結尾的(__foo__)代表python裡特殊方法專用的標識,如__init__()代表類的建構函式。
行和縮排
學習Python和其他語言最大的區別在於,Python的代碼塊不使用({})來控制類、函數以及其他邏輯判斷。Python最具特色的就是用縮排來寫模組。
縮排的空白數量是可變的,但是所有的代碼塊語句必須包含相同的縮排空白數量,這個必須嚴格執行。
多行語句
Python語句中一般以新行作為語句的結束符。
但是我們可以使用(\)將一行的語句分成多行顯示,如下:
total = item_one + item_two + item_three
語句中包含[],{},()的就不需要使用多行串連符,如下:
number = [‘one‘, ‘two‘, ‘three‘]
Python引號
Python接受單引號(‘),雙引號("),三引號(‘‘‘ """)來表示字串,引號的開始與結束必須是相同類型。
其中三引號可以由多行組成,編寫多行文本的快捷文法,常用語文檔字串,在檔案的特定地點,被當做注釋。
word = ‘word‘sentence = "這是一個句子。"paragraph = """這是一個段落。包含了多個語句"""
Python注釋
Python中單行注釋必須以#開頭。
#第一個注釋print "hello Python!" # 第二個注釋
注釋可以在語句或運算式行末
user_name = "Tommy" #這是一個注釋
Python中多行注釋使用三個單引號(‘‘‘),或三個雙引號(""")。
‘‘‘這是多行注釋,使用單引號。這是多行注釋,使用單引號。‘‘‘"""這是多行注釋,使用雙引號。這是多行注釋,使用雙引號。"""
Python空格
函數之間或類的方法之間用空行分隔,表示一段新的代碼的開始。類和函數入口之間也用一行空行分隔,以突出函數入口的開始。
空行與代碼縮排不同,空行並不是Python文法的一部分。書寫時不插入空行,Python解譯器運行也不會出錯。但是空行的作用在於分隔兩段不同功能或含義的代碼,便於日後代碼的維護或重構。
記住:空行也是程式碼的一部分。
多個語句構成程式碼群組
縮排相同的一組語句構成一個代碼塊,我們稱之程式碼群組。
像if、while、def和class這樣的複合陳述式,首行以關鍵字開始,以冒號( : )結束,該行之後的一行或多行代碼構成程式碼群組。
我們將首行及後面的程式碼群組稱為一個子句(clause)。
如下:
if expression : suite elif expression : suite else : suite
命令列參數
很多程式可以執行一些操作來查看一些基本資料,Python可以使用-h參數查看各參數協助資訊:
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...Options and arguments (and corresponding environment variables):-B : don‘t write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x-c cmd : program passed in as string (terminates option list)-d : debug output from parser; also PYTHONDEBUG=x-E : ignore PYTHON* environment variables (such as PYTHONPATH)-h : print this help message and exit (also --help)-i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x-m mod : run library module as a script (terminates option list)-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x-OO : remove doc-strings in addition to the -O optimizations-R : use a pseudo-random salt to make hash() values of various types be unpredictable between separate invocations of the interpreter, as a defense against denial-of-service attacks-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew-s : don‘t add user site directory to sys.path; also PYTHONNOUSERSITE-S : don‘t imply ‘import site‘ on initialization-t : issue warnings about inconsistent tab usage (-tt: issue errors)-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to ‘-u‘-v : verbose (trace import statements); also PYTHONVERBOSE=x can be supplied multiple times to increase verbosity-V : print the Python version number and exit (also --version)-W arg : warning control; arg is action:message:category:module:lineno also PYTHONWARNINGS=arg-x : skip first line of source, allowing use of non-Unix forms of #!cmd-3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fixfile : program read from script file- : program read from stdin (default; interactive mode if a tty)arg ...: arguments passed to program in sys.argv[1:]Other environment variables:PYTHONSTARTUP: file executed on interactive startup (no default)PYTHONPATH : ‘;‘-separated list of directories prefixed to the default module search path. The result is sys.path.PYTHONHOME : alternate <prefix> directory (or <prefix>;<exec_prefix>). The default module search path uses <prefix>\lib.PYTHONCASEOK : ignore case in ‘import‘ statements (Windows).PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.PYTHONHASHSEED: if this variable is set to ‘random‘, the effect is the same as specifying the -R option: a random value is used to seed the hashes of str, bytes and datetime objects. It can also be set to an integer in the range [0,4294967295] to get hash values with a predictable seed.
我們在使用指令碼形式執行 Python 時,可以接收命令列輸入的參數。
Python學習--Python基礎文法