Python中表達式和語句及for、while循環練習
1)表達式
常用的表達式操作符:x + y, x - yx * y, x / y, x // y, x % y邏輯運算:x or y, x and y, not x成員關系運算:x in y, x not in y對象實例測試:x is y, x not is y比較運算:x < y, x > y, x <= y, x >= y, x == y, x != y位運算:x | y, x & y, x ^ y, x << y, x >> y一元運算:-x, +x, ~x:冪運算:x ** y索引和分片:x[i], x[i:j], x[i:j:stride]調用:x(...)取屬性:  x.attribute元組:(...)序列:[...]字典:{...}三元選擇表達式:x if y else z匿名函數:lambda args: expression生成器函數發送協議:yield x 運算優先級:(...), [...], {...}s[i], s[i:j]s.attributes(...)+x, -x, ~xx ** y*, /, //, %+, -<<, >> &^|<, <=, >, >=, ==, !=is, not isin, not innotandorlambda 2)語句:
賦值語句 調用 print: 打印對象 if/elif/else: 條件判斷 for/else: 序列迭代 while/else: 普通循環 pass: 占位符 break: continue def return yield global: 命名空間 raise: 觸發異常 import: from: 模塊屬性訪問 class: 類 try/except/finally: 捕捉異常 del: 刪除引用 assert: 調試檢查 with/as: 環境管理器 賦值語句: 隱式賦值:import, from, def, class, for, 函數參數 元組和列表分解賦值:當賦值符號(=)的左側為元組或列表時,Python會按照位置把右邊的對象和左邊的目標自左而右逐一進行配對兒;個數不同時會觸發異常,此時可以切片的方式進行; 多重目標賦值 增強賦值: +=, -=, *=, /=, //=, %=,
3)for循環練習
練習1:逐一分開顯示指定字典d1中的所有元素,類似如下k1 v1k2 v2...    >>> d1 = { 'x':1,'y':2,'z':3,'m':4 }  >>> for (k,v) in d1.items():  print k,v   y 2  x 1  z 3  m 4    練習2:逐一顯示列表中l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]中的索引為奇數的元素;    >>> l1 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]  >>> for i in range(1,len(l1),2):  print l1[i]    Mon  Wed  Fri    練習3:將屬于列表l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],但不屬于列表l2=["Sun","Mon","Tue","Thu","Sat"]的所有元素定義為一個新列表l3;     >>> l1 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]  >>> l2 = ["Sun","Mon","Tue","Thu","Sat"]  >>> l3 = [ ]  >>> for i in l1:  if i not in l2:l3.append(i)  >>> l3  ['Wed', 'Fri']     練習4:已知列表namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'],刪除列表removelist=['stu3', 'stu7', 'stu9'];請將屬于removelist列表中的每個元素從namelist中移除(屬于removelist,但不屬于namelist的忽略即可);     >>> namelist= ['stu1','stu2','stu3','stu4','stu5','stu6','stu7']  >>> removelist = ['stu3', 'stu7', 'stu9']    >>> for i in namelist:  if i in removelist :namelist.remove(i)  >>> namelist  ['stu1', 'stu2', 'stu4', 'stu5', 'stu6']            
新聞熱點
疑難解答