Python Data Types
Type Groups
In Python, there are several built-in data types that you can use to store data in your programs. These data types include:
Numeric types: Python has several numeric types, including integers (int), floating-point numbers (float), and complex numbers (complex).
x = 5 # integer y = 3.14 # floating-point number z = 1 + 2j # complex number
Sequence types: Python has several types that represent sequences of values, including lists (list), tuples (tuple), and range objects (range).
lst = [1, 2, 3] # list t = (4, 5, 6) # tuple r = range(7, 10) # range object
Mapping type: The dict type represents a mapping, or dictionary, of keys to values.
d = {'a': 1, 'b': 2, 'c': 3} # dictionary
Set types: Python has a set type that represents a collection of unique elements. There is also a frozenset type, which is an immutable version of set.
s = {1, 2, 3} # set fs = frozenset({4, 5, 6}) # frozenset
Boolean type: The bool type represents Boolean values (True and False).
b1 = True b2 = False
Text type: The str type represents sequences of Unicode characters.
txt = "hello" # string
Binary types: Python has a bytes type for representing sequences of bytes, and a bytearray type for representing mutable sequences of bytes.
b = b'hello' # bytes ba = bytearray(b'hello') # bytearray
These are the most commonly used data types in Python, but there are several other types available as well.
Variable Data Type Assignment
In Python, you can assign a value to a variable by using the assignment operator =. For example:
x = 5
This will create a variable x and assign it the value 5. The data type of the value will be automatically determined by Python. For example, the value 5 is an integer, so the variable x will be of type int.
You can also assign a value to a variable and specify the data type explicitly using type casting. For example:
x = int(5)
This will create a variable x and assign it the value 5, explicitly specifying that the value should be of type int.
You can also assign a value of one data type to a variable of a different data type using type casting. For example:
x = int(5.5)
This will create a variable x and assign it the value 5, casting the value 5.5 (a floating-point number) to the integer value 5.
It's important to note that type casting can sometimes result in data loss if the value being cast is not compatible with the target data type. For example, casting the string "hello" to an integer will raise a ValueError, because the string cannot be represented as an integer.