changed 5 years ago
Linked with GitHub
tags: python

資料型別

不同情境使用不同資料型別,可以簡化程式撰寫及錯誤發生

  • 數值:
    • int: 整數
    • float: 浮點數
    • complex: 複數
    • bool: 布林
  • 文字:
    • str:字串
  • 二元序列:
    • bytes:位元組
    • bytearry:位元陣列
    • memoryview:
  • 序列:
    • list:串列、清單
    • tuple:序對
    • range:
  • 集合:
    • set:集合
    • frozenset:
  • 對映:
    • dict:字典

int(整數,沒有小數點)

i = 1 + 1 print(i)

float(浮點數,有小數點)

j = 1.5 + 2.6 print(j)

bool(布林,真/假)

k = True l = 1 < 2 print(k, l)

str(字串)

name = '文山社大' car = "smart" content = '''The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to support and facilitate the growth of a diverse and international community of Python programmers.''' print(name) print(car) print(content)

備註: 顯示變數的資料型態

type(100) type(-12.5) type(True) type("hello")

資料型態 可接受多資料型態 順序 改變內容 內容重複
list V
tuple V 不可
set V 不可
dict V key值不可重複

list

i = ['amos', "taipei", 44] print(i) print(i[2]) # 44 i[1] = '台北' print(i) # ['amos', "台北", 44]
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)

練習

請使用者輸入國文、英文、數學成績
顯示最高分數是幾分

請使用者輸入想購買的水果名稱
顯示該商店是否有該水果可出售

fruit = ['香蕉', '鳳梨', '百香果', '釋迦', '梨子']

tuple

i = (1, "taipei", 2) print(i)

set

i = {1, "taipei", 5} print(i) print("taipei" in i) # True i.add("高雄") print(i) # {1, 5, '高雄', 'taipei'}

dict

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] # 網頁設計
school = [ { "id": "A1122", "name": "Amos Tsai", "year": 5 }, { "id": "A1123", "name": "frank", "year": 3} ] a = ["amos", "frank"] print(school[1]['name'])
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))

補充說明

可利用dir()查詢該變數擁有哪些屬性及方法

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))

不同資料型別擁有哪些屬性及方法,之後會在特別介紹

S20200609 來自amos老師的網站。資料型別

Select a repo