欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

習(xí)題 33: While 循環(huán)?

接下來是一個(gè)更在你意料之外的概念: while-loop``(while 循環(huán))。``while-loop 會(huì)一直執(zhí)行它下面的代碼片段,直到它對(duì)應(yīng)的布爾表達(dá)式為 False 時(shí)才會(huì)停下來。

等等,你還能跟得上這些術(shù)語吧?如果你的某一行是以 : (冒號(hào), colon)結(jié)尾,那就意味著接下來的內(nèi)容是一個(gè)新的代碼片段,新的代碼片段是需要被縮進(jìn)的。只有將代碼用這樣的方式格式化,Python 才能知道你的目的。如果你不太明白這一點(diǎn),就回去看看“if 語句”和“函數(shù)”的章節(jié),直到你明白為止。

接下來的練習(xí)將訓(xùn)練你的大腦去閱讀這些結(jié)構(gòu)化的代碼。這和我們將布爾表達(dá)式燒錄到你的大腦中的過程有點(diǎn)類似。

回到 while 循環(huán),它所作的和 if 語句類似,也是去檢查一個(gè)布爾表達(dá)式的真假,不一樣的是它下面的代碼片段不是只被執(zhí)行一次,而是執(zhí)行完后再調(diào)回到 while 所在的位置,如此重復(fù)進(jìn)行,直到 while 表達(dá)式為 False 為止。

While 循環(huán)有一個(gè)問題,那就是有時(shí)它會(huì)永不結(jié)束。如果你的目的是循環(huán)到宇宙毀滅為止,那這樣也挺好的,不過其他的情況下你的循環(huán)總需要有一個(gè)結(jié)束點(diǎn)。

為了避免這樣的問題,你需要遵循下面的規(guī)定:

  1. 盡量少用 while-loop,大部分時(shí)候 for-loop 是更好的選擇。
  2. 重復(fù)檢查你的 while 語句,確定你測試的布爾表達(dá)式最終會(huì)變成 False
  3. 如果不確定,就在 while-loop 的結(jié)尾打印出你要測試的值??纯此淖兓?。

在這節(jié)練習(xí)中,你將通過上面的三樣事情學(xué)會(huì) while-loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
i = 0
numbers = []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i


print "The numbers: "

for num in numbers:
    print num

你應(yīng)該看到的結(jié)果?

$ python ex33.py
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers: 
0
1
2
3
4
5

加分習(xí)題?

  1. 將這個(gè) while 循環(huán)改成一個(gè)函數(shù),將測試條件(i < 6)中的 6 換成一個(gè)變量。
  2. 使用這個(gè)函數(shù)重寫你的腳本,并用不同的數(shù)字進(jìn)行測試。
  3. 為函數(shù)添加另外一個(gè)參數(shù),這個(gè)參數(shù)用來定義第 8 行的加值 + 1 ,這樣你就可以讓它任意加值了。
  4. 再使用該函數(shù)重寫一遍這個(gè)腳本??纯葱Ч绾巍?/li>
  5. 接下來使用 for-looprange 把這個(gè)腳本再寫一遍。你還需要中間的加值操作嗎?如果你不去掉它,會(huì)有什么樣的結(jié)果?

很有可能你會(huì)碰到程序跑著停不下來了,這時(shí)你只要按著 CTRL 再敲 c (CTRL-c),這樣程序就會(huì)中斷下來了。

Project Versions

Table Of Contents

Previous topic

習(xí)題 32: 循環(huán)和列表

Next topic

習(xí)題 34: 訪問列表的元素

This Page