您好,登錄后才能下訂單哦!
今天小編就為大家帶來一篇有關while語法示例的文章。小編覺得挺實用的,為此分享給大家做個參考。一起跟隨小編過來看看吧。
練習一,逐一顯示指定列表中的所有元素;
//方法一 In [25]: l1 Out[25]: [1, 2, 3, 4] In [26]: while l1: ....: print l1[0] ....: l1.pop(0) ....: 1 2 3 4 //方法二 In [66]: count = 0 In [67]: count Out[67]: 0 In [68]: while count < len(l1): ....: print l1[count] ....: count += 1 ....: 1 2 3 4
練習二,求100以內所有偶數之和;
In [215]: sum = 0; i = 0 In [216]: while i <= 100: .....: i+=1 .....: if i % 2 == 0: .....: sum = sum +i .....: In [217]: print sum 2550
練習三,逐一顯示指定字典的所有值,并于顯示結果結束后說明總鍵數;
In [91]: print d1 {'y': 45, 'x': 2, 'z': 90} In [95]: while keylist: ....: print keylist[0] ....: keylist.pop(0) ....: else: ....: print len(d1) ....: y x z 3
練習四,創建一個包含了100以內所有奇數的列表;
In [96]: l1 = [] In [97]: x = 1 In [98]: while x < 100: ....: l1.append(x) ....: x += 2 ....: In [99]: print l1 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
練習五,逆序逐一顯示一個列表的所有元素;
In [34]: l1 = [1,2,3,4] In [35]: while l1: ....: print l1[-1] ....: l1.pop() ....: 4 3 2 1
練習六,列表l1=[0,1,2,3,4,5,6],列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] ,以第一個列表中的元素為鍵,以第二個列表中的元素為值生成字典d1;
In [120]: d1={} In [121]: x=0 In [122]: l1=[0,1,2,3,4,5,6] In [123]: l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] In [130]: while x < len(l1): d1[l1[x]] = l2[x] x += 1 .....: In [131]: print d1 {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'}
關于while語法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果喜歡這篇文章,不如把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。