{%hackmd @dzif24x25/IBXIWNXgTju0h2AKtSaLkA %} ###### tags: `Python` `資料型態` # 基本資料型態 ## type()函數 在Python中,可以使用`type()`來確定一個變數的資料型態 範例: ```python= x = 123 y = x / 17 print(x) print(type(x)) print(y) print(type(y)) ``` 輸出結果: ```bash 123 <class 'int'> 7.235294117647059 <class 'float'> ``` ## 數值資料型態(Numeric Type) * 整數(int) 例如:「-51」、「234」 * 浮點數(float) 例如:「-51.3」、「234.0」 * 布林值(bool) 例如:「1」、「0」、「True」、「False」 * 複數(complex number) 例如:「3+5j」 :::info 不同於C/C++,Python的int、float自Python 3開始,空間大小沒有上限。 ::: 範例1: ```python= x = 10000000000000000 y = 3.141592653589793238462643383279 print(x + y) print(type(x + y)) ``` 輸出結果: ```bash 1.0000000000000004e+16 <class 'float'> ``` 範例2: ```python= x = 123 y = True print(x + y) print(type(x + y)) ``` 輸出結果: ```bash 124 <class 'int'> ``` :::info 可以使用函式轉換變數的型別 e.g. int()、float()、bool() ```python int(n) float(n) bool(n) ``` ::: ## 字串型態(String) * 字串(str) 例如:「"Hello, World"」、「'ABCD'」 :::info 註:在Python中,單引號「'」和雙引號「"」皆可做為字串,當字串中包含「'」時,則該用「"」作為字串,反之以此類推。 ::: 如果需要紀錄的字串有多行,可以使用多行字串,例如: ```python ''' 《離騷》 作者:屈原 原文: 帝高陽之苗裔兮,朕皇考曰伯庸。 攝提貞於孟陬兮,惟庚寅吾以降。 皇覽揆餘初度兮,肇錫餘以嘉名: 名餘曰正則兮,字餘曰靈均。 ...以下省略... 僕伕悲餘馬懷兮,蜷局顧而不行。 亂曰:已矣哉! 國無人莫我知兮,又何懷乎故都! 既莫足與爲美政兮,吾將從彭咸之所居! ''' ``` 詳見:[字串(String)](/s/S6lbBRBXTsWkMEBVSnmrsg) ## 序列型態(Sequence Type) * 串列(list) 例如:「['one', 2, True]」 詳見:[串列(List)](/s/o_u9lSEdRV-WBGgS7okoxA) * 元組(tuple) 例如:「('one', 2, True)」 詳見:[元組(Tuple)](/s/5Um0gFtCTYqHZeBgPwbviQ) ## 對映型態(Mapping Type) * 字典(dict) 例如:「{'Hello': '你好', 'World': '世界'}」 詳見:[字典(Dict)](/s/5QOZrkP-QM6VN3AucchfDw) ## 集合型態(Set Type) * 集合(set) 例如:「{1, 3, 5, 7, 9}」 詳見:[集合(Set)](/s/kVMMwTndSkeT1t2CEqf9Yg) :::info 點此前往簡報版: https://hackmd.io/@dzif24x25/HypqE0SCi :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up