Type of Variables
Python is dynamically typed, means we don’t need to declare the type of a variable in advance. In Python, variables don’t have explicitly declared types like in some other programming languages. However, the type of a variable is determined by the value it holds.
Here are the primary types of variables in Python, along with examples :
1. Numeric Types
These types deal with numbers.
int
: Integer values.x = 10 # intfloat
: Floating-point (decimal) values.y = 10.5 # floatcomplex
: Complex numbers (real + imaginary parts).z = 2 + 3j # complex
2. Sequence Types
These types hold a collection of items.
str
: Strings (text data).name = "Alice" # str
list
: Ordered, mutable collections.fruits = ["apple", "banana", "cherry"] # list
tuple
: Ordered, immutable collections.coordinates = (10, 20) # tuple
3. Set Types
Collections of unique, unordered items.
set
: Mutable, unordered collections.unique_numbers = {1, 2, 3} # set
frozenset
: Immutable version of a set.immutable_set = frozenset({1, 2, 3}) # frozenset
4. Mapping Types
Associative collections (key-value pairs).
dict
: Dictionary type.person = {"name": "Alice", "age": 30} # dict
5. Boolean Type
Represents truth values.
bool
: True or False.is_active = True # bool
6. Binary Types
Used for binary data.
bytes
: Immutable sequence of bytes.data = b"hello" # bytes
bytearray
: Mutable sequence of bytes.mutable_data = bytearray(b"hello") # bytearray
memoryview
: Memory view object.memory = memoryview(b"hello") # memoryview
7. None Type
Represents the absence of a value.
NoneType
: Special type indicating no value.value = None # NoneType
Dynamic Typing
Python is dynamically typed, where type of a variable can change during execution as below :
x = 42 # int
x = "Python" # str
Type Checking
You can use the type()
function to check the type of a variable:
x = 42
print(type(x)) # <class ‘int’>
Python also provides hints for specifying types using type annotations:
def add(a: int, b: int) -> int:
return a + b