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
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" ) 需要特別注意...
請問如果使用者可以先選擇溫度轉換方式,然後再輸入一個溫度,可以轉換成另一溫度,請問你會怎麼寫呢?謝謝!
回覆刪除您好,
刪除請看下面原始碼。
https://gist.github.com/seaniap/5f1c0e4b8d46dfdc342aae5bbb4c8db0
歡迎討論
Sean Yeh您好,
刪除謝謝回覆。
真的很感謝您提供的解答。
但有兩個地方有些疑問,
1.請問第7行,whatConvert = "1",這裡寫這個的用意?
2.如果12行與16行不加上.strip()),是否也可以?
謝謝!
謝謝您的提醒。
刪除本來我想設定一個預設的狀態,所以第7行預先指定了1的選項。不過,似乎不寫也不影響。
另外,12行與16行加上.strip()的目的是為了防呆,避免使用者輸入不必要的空白,如果確定不會的話,不寫.strip()程式也是可以跑的。