Data Type
A data type determines which values are allowed and which operations have meaning. In Python every object has a type, and that type is a class: type(2) is int, type(2.5) is float, and type("2") is str. Other common built-in types include bool for True and False, list, dict, and NoneType for the value None.
The same symbol can mean different operations for different types. 2 + 3 is 5, but "2" + "3" joins text to make "23". 7 + "8" raises TypeError because Python does not guess whether you meant arithmetic or joining text. The error message names the types involved, which is the first clue for a fix.
Python converts between some numeric types automatically. In 1 + 2.5, the integer is converted and the result is the float 3.5. Text is not converted to a number implicitly. Explicit conversion, also called casting, calls the target type: int("42"), float("2.5"), str(34). These conversions return a result without rebinding the input name. They need not allocate a new object when the input already has the requested type.
Conversion rules are easy to misread. int("2.5") raises ValueError, while int(2.9) truncates toward zero and returns 2. bool("False") is True because every non-empty string counts as true. A float stores a binary approximation, so 0.1 + 0.2 == 0.3 is False. Values read from files often arrive as text, including "1,200" or an empty string; decide how each should be converted or rejected instead of relying on whichever conversion happens to succeed.
References: Python built-in types, Python built-in functions. See it in use in Python Foundations: Variables, Types, and the Notebook.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
