今天要來介紹資料類型,大致上可分成數字、字串、容器型態,以下會依序個型態介紹用法。
數字Number
:
數字在 Python 中可以算是數一數二常見的資料類型,主要可分成int
、float
、complex
。
int
:整數,正整數、負整數、零都包含在整數
中。float
:浮點數,有小數點的數字都視為浮點數
。complex
:複數,用來表示實
與虛
組成的數。整數:1、-1、0
number = 10
print(number) # 10
print(type(number)) # <class 'int'>
浮點數:1.1、-1.1
number = 10.7
print(number) # 10.7
print(type(number)) # <class 'float'>
複數:1 + j
complex_num = 1 + 2j
print(complex_num) # (1+2j)
print(type(complex_num)) # <class 'complex'>
字串String
:
字串在 Python 中算是挺常見的資料類型,使用方式為''
或是""
包起來的內容都算是字串,但切記!單引號和雙引號要一同使用也是有限制的,這部分待會會提到。
# 單引號
'我是字串'
# 雙引號
"我是字串"
# 錯誤範例
'我不是字串"
仔細點可以看出上述範例錯誤的部分,使用了單引號和雙引號在開頭及結尾,這在 Python 中是不允許的,如果需要單引號和雙引號一同使用的話可以像是這樣。
profession = "I'm software engineer."
布林值Boolean
:
布林值的資料類型為True
或是False
,切記!T
和F
必為大寫。
此外,Python 也會把0
、""
、[]
視為False
,其餘非空值或非零值的都視為True
。
由此可知 Python 會把True
表示為1
,False
表示為0
,讓我們來驗證一下
x = True + 1
y = False + 1
print(x) # 2
print(y) # 1
仔細看會發現在Number
範例中有使用到type()
方法,這對於了解資料型態非常重要,因為在 Python 中不同的型態會有不同的方法和行為,可以使用該方法檢查目前的型態是什麼,以下根據目前學習到的型態作為範例。
number = 10
print(type(number)) # <class 'int'>
number_float = 1.1
print(type(number_float)) # <class 'float'>
string = "hello"
print(type(string)) # <class 'str'>
bol = True
print(type(bol)) # <class 'bool'>
那麼今天就介紹到這,明天見ㄅㄅ!