###### tags: `chapter 3` `Python` # 3-1 型別相關操作 # 上一章介紹到,程式語言裡有很多種不同的資料型態,有整數(int)、浮點數(float)、字串(string)等,就像螺絲釘有十字一字,本章節要帶大家認識python裡常用的資料型態以及常用操作。 ## `type()`函數 ## `type()`函數的功能是讓我們得知這個變數的型態,是一個非常非常重要且好用的函式,其操作方法為將變數放入`()`內。 ```python= x = 10 print(type(x)) # <class 'int'> ``` ```python= name = "Louis" print(type(name)) # <class 'str'> ``` ```python= f = 10.222 print(type(f)) # <class 'float'> ``` ![](https://i.imgur.com/fAFDxTE.png) ![](https://i.imgur.com/Tjvc4B4.png) 型態在python裡面非常的重要,接觸python一段時間之後通常會使用一些非內建的`package`例如:`numpy`、`matplotlib`、`pandas`、`pytorch`。每個`package`裡面可能會有自己定義的型態,有時候A型態和B型態是不相容的,一定要經過一定程序的轉換,因此大家要記得`type()`函式哦! ![](https://i.imgur.com/Yjjdwyx.png) ## 強制轉型 ## 在設計程式時,可以將資料做強行轉換的動作,比如說:今天讀到一個溫度是攝氏37.547863度,如果覺得太麻煩了,只想要取其整數部分,那可以把37.547863從浮點數轉換為整數,他會自動捨棄小數部分。 ```python= temp = 37.547863 print(type(temp)) print(temp) temp = int(temp) print(type(temp)) print(temp) ``` ```python= temp = 37.321 temp = str(temp) print(temp) print(type(temp)) ``` 強制轉型通常是為了因應上面提到的,避免型態不相同的操作,像是做機器學習一定會知道的外部套件`pytorch`裡,就有一個函式叫做`from_numpy()`,就是為了讓`numpy`類型的變數能夠轉換成`pytorch`能夠接受的模樣,因此也非常的重要!