在這篇中提到,電腦不知道該如何混和不同的資料類型,舉例來說:
>>> print(7 + "8")
會輸出:
Traceback (most recent call last):
File "<stdin>" , line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
然而,下面這段 code 卻可以正常作業:
>>> print(7 + 8.5)
會輸出: 15.5
整數 7 與 浮點數 8.5,理論上是無法相加的;這裡之所以可以相加,是因為 Python 對整數 7 做了 implicit conversion (隱性轉換),即指編譯器自動地將資料類型轉換為另一種類型 (interpreter automatically converts one data type into another)。
在這裡,整數 7 自動地被 Python 轉換為浮點數 7,然後再與浮點數 8.5 做運算,當然,輸出的結果也是浮點數。
Python 對於浮點數跟整數的運算較寬鬆,但如果是要做字串與數字的連接,那就需要使用 explicit conversion (顯性轉換) 了。在下面例子中,使用 str() 函式將資料格式轉換為字串:
base = 6
height = 3
height = 3
area = base * height / 2
print("The area of this triangle is: " + str(area))
print("The area of this triangle is: " + str(area))
原本透過除法運算得到的 area 本應是浮點數,但透過 str() 就強制轉為字串了,最後使用 加法 表達式 (expression) 來將字串結合,得到:
The area of this triangle is: 9.0

留言
張貼留言