{%hackmd @dzif24x25/yRBnguqQQl-2ylH1j5h0cg %} # 基本資料型態 --- ## 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 ''' 《離騷》 作者:屈原 原文: 帝高陽之苗裔兮,朕皇考曰伯庸。 攝提貞於孟陬兮,惟庚寅吾以降。 皇覽揆餘初度兮,肇錫餘以嘉名: 名餘曰正則兮,字餘曰靈均。 ...以下省略... 僕伕悲餘馬懷兮,蜷局顧而不行。 亂曰:已矣哉! 國無人莫我知兮,又何懷乎故都! 既莫足與爲美政兮,吾將從彭咸之所居! ''' ``` --- ## 序列型態(Sequence Type) --- * 串列(list) 例如:「['one', 2, True]」 * 串列(tuple) 例如:「('one', 2, True)」 --- ## 對映型態(Mapping Type) --- * 字典(dict) 例如:「{'Hello': '你好', 'World': '世界'}」 --- ## 集合型態(Set Type) --- * 集合(set) 例如:「{1, 3, 5, 7, 9}」
{"metaMigratedAt":"2023-06-17T21:51:20.670Z","metaMigratedFrom":"YAML","title":"基本資料型態","breaks":true,"contributors":"[{\"id\":\"b1b336d5-b75d-4c19-b4f6-fccd69a2a9f2\",\"add\":1630,\"del\":86}]"}
    91 views
   Owned this note