Data types
Info:
Variables can store data of different types. In Python, you have the following data types by default:
- Text Type:
- String - for text
- Strings are text.
- They are written in
""
double coma.
- String - for text
- Number Types:
- Mapping Type:
Dict
- Set Types:
set
frozenset
- Boolean Type:
bool
- read Boolean for more info.
- Binary Types:
bytes
bytearray
memoryview
- None Type:
NoneType
Getting the Data Type:
You can get the data type of any object by using thetype()
function:
x = 5
print(type(x))
This should give an output that gives information about the data type of the variable x:
<class 'int'>
So as you see above, the output tells us that the data type of the x variable's value is an integer.
Setting the Data Type:
In Python, the data type is set when you assing a value to a variable:
Examples:
x = "Hello World"
= strx = 20
= intx = 20.5
= floatx = 1j
= complexx = ["apple", "banana", "cherry"]
= listx = ("apple", "banana", "cherry")
= tuplex = range(6)
= rangex = {"name" : "John", "age" : 36}
= dictx = {"apple", "banana", "cherry"}
= setx = frozenset({"apple", "banana", "cherry"})
= setx = True
= boolx = b"Hello"
= bytesx = bytearray(5)
= bytearrayx = memoryview(bytes(5))
= memoryviewx = None
= None
You can also set a specific data type:
x = str("Hello World!")
= strx = int(20)
= intx = float(20.5)
= floatx = complex(1j)
= complexx = list(("apple", "banana", "cherry"))
= listx = tuple(("apple", "banana", "cherry"))
= tuplex = range(6)
= rangex = dict("name" : "John", "age" : 36)
= dictx = set(("apple", "banana", "cherry"))
= setx = frozenset(("apple", "banana", "cherry"))
= frozensetx = bool(5)
= boolx = bytes(5)
= bytesx = bytearray(5)
= bytearrayx = memoryview(bytes(5))
= memoryview
Note
Note how the syntax changes from brackets..etc to paranthesis when you set a specific type.