1、for循環(huán) 遍歷序列,如一個列表或一個字符 for x in 'abcd': 或[a.b.c.d] print "hello word!" 會輸出四次 2、使用迭代 range函數(shù) range(i,j,[,步進值]) 如果創(chuàng)建的對象為整數(shù),可以使用range >>>range(10) 輸出0到9 for x in range(100): print "hello word" 輸出100次 給range賦值 for x in range(1,11): 不包含11 print x 輸出1到10 for x in range(1,10,2) print x 輸出1,3,5,7,9 例子: num=0 for x in range(1,101): num+=x print num 3、遍歷 直接遍歷:字符串、列表、元組 for x in "hello": print x 迭代:range函數(shù) s=“hello” fox x in range(len(s)): print s[x] 遍歷字典 d={1:111,2:222,5:555,3:333} for x in d: print x #只能獲取key無法獲得value print d[x] #取出value print d.items() #返回一個key-value的元組 拆分字典然后遍歷,將key和value分開取出 for k,v in id.tems(): print k print v 4、循環(huán)控制 for for x in range(200): print x time.sleep(1) else: print "ending" 如果for循環(huán)正常執(zhí)行,else語句也會執(zhí)行,當for循環(huán)意外終止或breake時,else不會執(zhí)行 break結(jié)束循環(huán) for x in range(1,5): print x if x == 2: print "hello 22222" break print "#"*20 輸出:結(jié)束循環(huán) 1 #################### 2 hello 22222 continux本次循環(huán) for x in range(1,4): print x if x == 2: print "hello 22222" continue print "#"*20 輸出:會結(jié)束本次循環(huán)而進行下次循環(huán) 1 #################### 2 hello 22222 3 #################### pass起到占位的作用:代碼樁 5、循環(huán)控制 while while循環(huán),直到表達式變?yōu)榧?防止死循環(huán)(要有結(jié)束條件) while 1: print "hello" x = raw_input("please input somethig,q for quit:") #使用輸入條件和break來結(jié)束 if x == "q": break x = "" while x != "q": #通過while的循環(huán)條件結(jié)束循環(huán) print "hello" x = raw_input("please input somethig,q for quit:") while也可以使用else語句 x = 0 while x != "q": print "hello" x = raw_input("please input somethig,q for quit:") #使用q來退出 if not x: #空值也結(jié)束 break else: print "ending...." 6、一些迭代工具 打印名字和年齡的對應關系 names = ['jason','herry','jack',] ages = [25,26,43] for i in range(len(names)): print names[i], 'is' , ages[i], 'years old' zip行數(shù)的并列迭代 zip(names, ages) for names, ages in zip(names,ages): print naem, 'is', age, 'years old' 7、輕量級循環(huán) X的平方 >>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 能被3整除的平方數(shù) >>> [x*x for x in range(10) if x % 3 == 0] [0, 9, 36, 81] 8、三人行 pass、del、exec >>> if name == 'jason jack': ... print '1' ... elif name == 'tom': ... pass ... 起到占位符的作用,在python中空的代碼塊是非法的,可以使用pass代替。 >>> scoundrel = {'age':28,'first name':'jason','last name':'of lost'} >>> robin = scoundrel >>> scoundrel {'last name': 'of lost', 'first name': 'jason', 'age': 28} >>> robin {'last name': 'of lost', 'first name': 'jason', 'age': 28} >>> scoundrel = none >>> scoundrel >>> >>> robin {'last name': 'of lost', 'first name': 'jason', 'age': 28} >>> del robin >>> robin Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'robin' is not defined del和None都可以直接將字典刪除,del將對象的引用和名字本身都移除。 exec、eval執(zhí)行和求值字符串 |
|
來自: jas0n_liu > 《python學習筆記》