1. _表示最后一個表達式的值。
2. print 語句
a) %修飾符用來進行字符串的構(gòu)造。
例如 "This is My %d program named %s" % (1, "test")
b) print >> xxx, 'string' 用來重定向
xxx可以是:
a) import sys; print >>sys.stderr
b) logfile = open('filename', 'a'); print >> logfile; logfile.close()
c) print默認會加上換行符,如果不想要,可以加上逗號
eg:
for x in range(10):
print x,
print
3. 讀入:raw_input("prompt")
從stdin讀入一個字符串,并自動去掉尾部的換行字符
如果讀入一個EOF字符則引發(fā)EOFError
4. 注釋
# one line
def foo():
"doc string"
5 操作符
數(shù)學(xué)運算:
+ - * / // % **
+= *= -= ...
注: 不支持++ , --
比較運算:
> < >= <= != <>(deprecated)
可以變成 a < b < 3 ==> a<b and b<c
邏輯運算:
and or not
6 變量
區(qū)分大小寫
字母或下劃線開頭,字母、數(shù)字或下劃線組成
7 if語句
格式:
if expression :
if_statement
(optional)
elif expression:
elif_statement
else :
else_statement
暫時貌似不支持switch
8 while循環(huán)
while expression:
while statements
9 for循環(huán)
python中的for不同于C/Java中的for循環(huán),類似于foreach循環(huán)
for item in ['a', 'b', 'c']:
print item,
print
為了達到類似for(0~10)的效果,可以用
for item in range (10):
另外,字符串也可以被迭代
for ch in 'abc':
print ch,
print
或者
foo = 'abc'
for i in range(len(foo)):
print "%s (%d); " % (foo[i], i) ,
print
或者
for i, ch in enumerate(foo):
print "%s (%d); " %(ch, i),
print
注:enumerate迭代下標(biāo)和值。
10 文件
打開:
handle = open(filename, access_mode = 'r')
讀寫:
a) handle.readlines()
b) for line in handle:
c) print >> handle
關(guān)閉:
handle.close()
11 函數(shù)
def fun_name([arguments]):
"optional doc string"
function_statement
12 類&模塊(略)
有用的函數(shù)摘錄:
函數(shù) 描述
dir([obj]) 顯示對象的屬性,如果沒有提供參數(shù), 則顯示全局變量的名字
help([obj]) 以一種整齊美觀的形式 顯示對象的文檔字符串, 如果沒有提供任何參數(shù), 則會進入交互式幫助。
int(obj) 將一個對象轉(zhuǎn)換為整數(shù)
len(obj) 返回對象的長度
open(fn, mode) 以 mode('r' = 讀, 'w'= 寫)方式打開一個文件名為 fn 的文件
range([[start,]stop[,step])
返回一個整數(shù)列表。起始值為 start, 結(jié)束值為 stop - 1; start默認值為 0, step默認值為1。
raw_input(str) 等待用戶輸入一個字符串, 可以提供一個可選的參數(shù) str 用作提示信息。
str(obj) 將一個對象轉(zhuǎn)換為字符串
type(obj) 返回對象的類型(返回值本身是一個type 對象?。?nbsp;
相關(guān)練習(xí):
Chp2Exe Chp2Exe