###### tags: `python` # 資料型別 不同情境使用不同資料型別,可以簡化程式撰寫及錯誤發生 * 數值: * int: 整數 * float: 浮點數 * complex: 複數 * bool: 布林 * 文字: * str:字串 * 二元序列: * bytes:位元組 * bytearry:位元陣列 * memoryview: * 序列: * list:串列、清單 * tuple:序對 * range: * 集合: * set:集合 * frozenset: * 對映: * dict:字典 --- ## int(整數,沒有小數點) ```python= i = 1 + 1 print(i) ``` ## float(浮點數,有小數點) ```python= j = 1.5 + 2.6 print(j) ``` ## bool(布林,真/假) ```python= k = True l = 1 < 2 print(k, l) ``` ## str(字串) ```python= content = 'The mission of the Python' print(content) ``` ### 備註: 顯示變數的資料型態 ```python= type(100) type(-12.5) type(True) type("hello") ``` --- |資料型態|可接受多資料型態|順序|改變內容|內容重複| |--|--|--|--|--| | list | V | 有 | 可 | 可 | | tuple | V | 有| 不可 | 可 | | set | V | 無 | 可 | 不可 | | dict | V | 有 | 可 | key值不可重複 | --- ## list ```python= i = ['amos', "taipei", 44] print(i) print(i[2]) # 44 i[1] = '台北' print(i) # ['amos', "台北", 44] ``` ```python= i = [1, 100, 10, 5] print(i[1]) i.append(0.2) # 追加資料 print(i) i.insert(2, 50) # 從第2筆插入50 i.remove(1) # 移除list內第一個符合該內容的資料! print(i) i.index(1) # 取得1在list中的索引值(第幾位) print(i) i.pop(i) # 取出,採先進後出法 print(i) i.sort() # 由小到大排序 print(i) i.reverse() # 由大到小排序 print(i) print( len(i) ) # 求list筆數 print( max(i) ) # 求list中最大值 print( min(i) ) # 求list中最小值 print( sum(i) ) # 將總list內的數值 i.clear() # 清除全部內容 print(i) ``` ### 練習 :::info 請使用者輸入國文、英文、數學成績 顯示最高分數是幾分 ::: :::info 請使用者輸入想購買的水果名稱 顯示該商店是否有該水果可出售 fruit = ['香蕉', '鳳梨', '百香果', '釋迦', '梨子'] ::: ## tuple ```python= i = (1, "taipei", 2) print(i) ``` ## set ```python= i = {1, "taipei", 5} print(i) print("taipei" in i) # True i.add("高雄") print(i) # {1, 5, '高雄', 'taipei'} ``` ## dict ```python= j = { "id": "A1122", "name": "Amos Tsai", "year": 5 } j["id"] = "AAAA" member = { "number": "1020501", "name": "小傑", "age": 32, "sex": "M", "interest": [ "網頁設計", "撰寫文章" ] } member['interest'] # ["網頁設計", "撰寫文章"] member['interest'][0] # 網頁設計 ``` ```python= school = [ { "id": "A1122", "name": "Amos Tsai", "year": 5 }, { "id": "A1123", "name": "frank", "year": 3} ] a = ["amos", "frank"] print(school[1]['name']) ``` ```python= school = { "id": "A1122", "name": "Amos Tsai", "year": 5 } school = list(school.values()) print(school) print(type(school)) a = [123, 555, "abc"] print(a) print(type(a)) a = tuple(a) print(a) print(type(a)) ``` :::info ### 補充說明 可利用dir()查詢該變數擁有哪些屬性及方法 ```python= list1 = [1, "taipei", 3] tuple1 = (1, "taipei", 2) set1 = {1, "taipei", 5} dict1 = { "id": "A1122", "name": "Amos Tsai", "year": 5 } print(dir(list1)) print(dir(tuple1)) print(dir(set1)) print(dir(dict1)) ``` ::: 不同資料型別擁有哪些屬性及方法,之後會在特別介紹 :::info ### 補充說明 [中華民國電腦技能基金會 範例試卷](https://www.tqc.org.tw/user/Example/B973D99B-4C85-44B2-9133-BD34827395B4.pdf) :::