This code demonstrates how to convert between different data types in Python.
a = int(5)
b = float(5.5)
c = complex(1j)
d = str("hello")
e = bool(True)
f = list((1, 2, 3))
g = tuple((1, 2, 3))
h = set((1, 2, 3))
i = dict(val1 = 2, val2 = 3)
j = frozenset(("first", "second", "third"))
k = bytes(b"Hello")
l = bytearray(2)
m = memoryview(bytes(2))
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
print(type(i))
print(type(j))
print(type(k))
print(type(l))
print(type(m))
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
<class 'frozenset'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
a
is assigned the value 5
cast as an integer data type using int(5)
.b
is assigned the value 5.5
cast as a floating-point data type using float(5.5)
.c
is assigned the value 1j
cast as a complex data type using complex(1j)
.d
is assigned the value "hello"
cast as a string data type using str("hello")
.e
is assigned the value True
cast as a boolean data type using bool(True)
.f
is assigned the value (1, 2, 3)
cast as a list data type using list((1, 2, 3))
.g
is assigned the value (1, 2, 3)
cast as a tuple data type using tuple((1, 2, 3))
.h
is assigned the value (1, 2, 3)
cast as a set data type using set((1, 2, 3))
.i
is assigned the value {1: 2, 2: 3}
cast as a dictionary data type using dict(val1 = 2, val2 = 3)
.j
is assigned the value {"first", "second", "third"}
cast as a frozen set data type using frozenset(("first", "second", "third"))
.k
is assigned the value b"Hello"
cast as a byte data type using bytes(b"Hello")
.l
is assigned the value 2
cast as a bytearray data type using bytearray(2)
.m
is assigned the value 2
cast as a memoryview data type using memoryview(bytes(2))
.Finally, for each variable, the type
function is used to print the data type of the value stored in the variable.