1)Statements and Syntax Hash mark (#)表示Python注释 NEWLINE(/n)是标准行操作符 Backslash(/)表示一行继续 Semicolon(;)在同一行连接两个语句 Colon(:)从suite中分隔首行 Suites通过缩进进行限制 Python文件以模块进行组织
2)Variable Assignment 等号(=)是赋值操作符 >>> anInt = -12 >>> String = 'cart' >>> aFloat = -3.1415*(5.0**2) >>> anotherString = 'shop'+'ping' >>> aList = [3.14e10, '2nd elmt of a list', 8.82-4.371j] 多个赋值 >>> x,y,z = 1,2,'a string' >>> x 1 >>> y 2 >>> z 'a string'
例子: 交换x和y的值 >>> (x,y) = (5,6) >>> x 5 >>> y 6 >>> (x,y) = (y,x) >>> x 6 >>> y 5
3)Identifiers 有效的Python标识符: - 第一个字符必须是字母或下划线 - 其后的字符可以是字母、数字或下划线 - 大小写敏感 关键字:目前有28个关键字 and elif global or assert else if pass break except import print class exec in raise continue finally is return def for lambda try del from not while
# does all the work def filefind(word, filename): #reset word count count = 0 # can we open file? if so, return file handle try: fh = open(filename, 'r') # if not, exit except: print filename, ":", sys.exc_info()[1] usage() # read all file lines into list and close allLines = fh.readlines() fh.close() # iterate over all lines of file for eachLine in allLines: # search each line for the word if string.find(eachLine, word)>-1: count = count+1; print eachLine, # when complete, display line count print count #validates arguments and calls filefind() def checkargs(): # check args; 'argv' comes from 'sys' module argc = len(sys.argv) if argc != 3: usage() # call fgrepwc.filefind() with args filefind(sys.argv[1], sys.argv[2]) #execute as application if __name__ == '__main__': checkargs()