This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
怎麼與我們期待的結果不同?我們希望它落入age < 6 區段的陳述子句,卻落到 age < 18區段了。
主要的原因前面有說過,ELIF陳述句的順序非常重要,由於該陳述句中,一旦找到符合條件的子句,其他剩下的子句都會跳過。目前的狀況就是它找到 age < 18符合條件之後,就跳過後面所有的陳述子句了。因此,我們必須調整上面程式的順序:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Python的主要迴圈指令有二,分別是For迴圈與While迴圈。兩者的差別在於while迴圈不會預設重複的次數,也就是說如果使用while迴圈時,可以無限次的重複。如果預先知道需要重複多少次的話,使用For迴圈會比較恰當。 For迴圈(For loops) 如果預先知道需要重複多少次的話,採用for迴圈是比較洽當的。他的語法如下: for 變數 in 串列: 程式區塊 例如下面的例子。其中i是變數,mylist是串列 ,而程式區塊的內容則是 print(i)。 mylist = [1,2,3,4,5] for i in mylist: print(i) 上面的程式碼執行後,電腦會陸續的將mylist串列的內容印出來,就像下面一樣。 當一切元素都處理完畢後,就會結束for迴圈。 另外,也可以使用range()來設定迴圈的執行次數,其語法如下: for 變數名稱 in range(重複次數): 重複執行的程式 巢狀迴圈 for迴圈也可以放在另外一個for迴圈裡面,這樣就成為所謂的巢狀迴圈。巢狀迴圈的執行次數是各層迴圈的乗績。 利用這個特性,我們可以透過巢狀迴圈製作九九乘法表。 for x in range ( 1 , 10 ): for y in range ( 1 , 10 ): product = x * y print ( "%d x %d =%d" %(x , y , product) , end = "" ) print () While 迴圈(While Loops) 如果條件符合的話,程式區塊就會被執行。反之,若條件不符合時,就結束迴圈繼續執行迴圈後面的程式碼。也就是說while迴圈會在條件為True的狀況下,重複執行內部的程式區塊內容。while迴圈通常沒有固定執行的次數,語法如下: while 條件: 程式區塊 下面的例子。條件是 n <3 ,程式區塊的內容是:print("name") n = 0 while n < 3 print ( "name" ) 需要特別注意...
留言
張貼留言