Variables in Python

First of all, variables in Python don’t denote a specific type and therefore you don’t need a type declaration in Python. So, unlike other programming languages such as C++ or Java, variables do not need to be declared.

In Python, as already mentioned, a variable can be used immediately without a declaration of the data type. Nevertheless, Python assigns a data type, i.e. depending on the data type, the variable is created differently, i.e. as integer, float, string, and so on.

The data type in Python is not bound to the variable, but to the value, which implies that the type can change at runtime.

Code Explanation

This code creates and initializes variables of various built-in data types in Python:

  1. a is of type int, representing a signed integer.
  2. b is of type float, representing a floating-point number.
  3. c is of type complex, representing a complex number.
  4. d is of type str, representing a string of characters.
  5. e is of type bool, representing a boolean value (True or False).
  6. f is of type list, representing a mutable ordered collection of elements.
  7. g is of type tuple, representing an immutable ordered collection of elements.
  8. h is of type set, representing an unordered collection of unique elements.
  9. i is of type dict, representing an unordered collection of key-value pairs.
  10. j is of type frozenset, representing an immutable unordered collection of unique elements.
  11. k is of type bytes, representing an immutable sequence of bytes.
  12. l is of type bytearray, representing a mutable sequence of bytes.
  13. m is of type memoryview, representing a shared memory area that can be used to access the bytes of an object.

After the variables have been created and initialized, the code uses the print() function and the type() function to display the type of each variable.

a = 5
b = 5.5
c = 1j
d = "hello"
e = True
f = [1, 2, 3]
g = (1, 2, 3)
h = {1, 2, 3}
i = {1: 2, 2: 3}
j = frozenset({"first", "second", "third"})
k = 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))
Output
<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'>