超人氣的Python控制結構:函數

 

最多人想學的Python有新文章啦!! 這篇要和大家分享函數

在Python教學中的 List 串列【基本的List串列說明,請參考:Python控制結構6.List串列】中,我們不僅可以隨意替換、索引 List 中的物件【請參考:Python控制結構7.List串列與其他運算子的應用】我們可以使用「append」來增加串列中的物件。如下例所示:

 

GearList = ["BCD", "調節器", "蛙鞋"]
GearList.append("潛水面罩")
print(GearList)

上述範例結果為:

['BCD', '調節器', '蛙鞋', '潛水面罩']

我們可以使用「len」來計算 List 串列中有多少物件:

GearList = ["BCD", "調節器", "蛙鞋"]
print(len(GearList))

上述例子結果為「3」。

「len」可與「append」合用,Python 語法範例如下:

GearList = ["BCD", "調節器", "蛙鞋"]
GearList.append("潛水面罩")
print(len(GearList))

上述例子結果為「4」。

剛剛提到,在 Python 中我們可以使用「append」來增加串列中的物件。但是「append」都是把物件增加在串列的最後面。若希望物件增加到串列的中間,就用「insert」:

GearList = ["BCD", "調節器", "蛙鞋"]
index=1
GearList.insert(index,"潛水面罩")
print(GearList)

結果為:

['BCD', '潛水面罩', '調節器', '蛙鞋']

以上範例,我們在 List 串列那一行的後方,加入了「index=1」,指定索引號碼為「1」。所以,"潛水面罩"這物件就被安插在索引序號為「1」的位置。

Python 的 List 串列用法可說是多樣化。我們甚至可以使用「index」來查看指定物件的索引序號如下:

GearList = ["BCD", "調節器", "蛙鞋"]
index=2
GearList.insert(index,"潛水面罩")
print(GearList.index("BCD"))
print(GearList.index("蛙鞋"))
print(GearList.index("調節器"))
print(GearList.index("潛水面罩"))

結果為:

0
3
1
2

List串列尚可搭配 for 迴圈,讓 List串列中的所有物件都可以被 Python 程式執行!【請參考:Python控制結構10.for迴圈

 

還想了解更多Python教學相關文章嗎?快到部落格首頁找找吧!!

 

 

 

其他閱讀

Python控制結構1.布林值Boolean-True or False?

 

Python控制結構2.if else條件判斷(1)

 

Python控制結構2.if else條件判斷(2)

 

Python控制結構3.布林邏輯:and,or,not

 

Python控制結構4.運算子優先順序(Operator precedence)一覽

 

Python控制結構5.while 迴圈

 

Python控制結構7.List串列與其他運算子的應用

 

Python控制結構8.List-append,insert,index,len函數

 

Python控制結構9.Range數列生成

 

Python控制結構10.for迴圈

 

Python控制結構11.實作簡單的計算機

arrow
arrow

    Java瑪奇朵 發表在 痞客邦 留言(0) 人氣()