In Python, data types define what kind of value a variable can hold. Understanding data types is crucial for writing efficient and error-free code.
Let’s explore Python’s basic data types with simple examples.
Numeric Data Types
Python provides three numeric data types:
- int: Whole numbers (e.g.,
5
,-10
) - float: Decimal numbers (e.g.,
3.14
,-0.5
) - complex: Numbers with real and imaginary parts (e.g.,
3 + 4j
)
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'complex'>
String (str)
A string is a sequence of characters enclosed in single or double quotes.
Example:
name = "Python"
greeting = 'Hello'
print(type(name)) # Output: <class 'str'>
print(name + " Rocks!") # Output: Python Rocks!
Boolean (bool)
The boolean type represents True
or False
.
is_active = True
is_closed = False
print(type(is_active)) # Output: <class 'bool'>
Sequence Data Types
- list: Ordered, mutable, and allows duplicates (e.g.,
[1, 2, 3]
) - tuple: Ordered, immutable, and allows duplicates (e.g.,
(1, 2, 3)
) - range: Represents a sequence of numbers (e.g.,
range(5)
)
Example:
fruits = ['apple', 'banana', 'cherry'] # list
coordinates = (10, 20) # tuple
numbers = range(5) # range
print(type(fruits)) # Output: <class 'list'>
print(type(coordinates)) # Output: <class 'tuple'>
print(list(numbers)) # Output: [0, 1, 2, 3, 4]
Mapping Data Type
- dict: A collection of key-value pairs.
Example:
person = {"name": "Junaid Shaikh", "age": 29}
print(type(person)) # Output: <class 'dict'>
print(person['name']) # Output: Alice
Set Data Types
- set: Unordered, mutable, no duplicates (e.g.,
{1, 2, 3}
) - frozenset: Immutable version of a set.
Example:
colors = {'red', 'green', 'blue'} # set
frozen_colors = frozenset(colors) # frozenset
print(type(colors)) # Output: <class 'set'>
print(type(frozen_colors)) # Output: <class 'frozenset'>
Binary Data Types
- bytes: Immutable binary data (e.g.,
b'hello'
) - bytearray: Mutable binary data.
- memoryview: Views binary data.
Example:
binary_data = b'Python'
mutable_data = bytearray(5)
print(type(binary_data)) # Output: <class 'bytes'>
print(type(mutable_data)) # Output: <class 'bytearray'>
Checking Data Type
Use the type()
function to check a variable’s data type.
Example:
value = 42
print(type(value)) # Output: <class 'int'>
Converting Between Data Types
Python allows type conversion using functions like int()
, str()
, float()
, etc.
Example:
num = "10"
converted_num = int(num) # Converts string to integer
print(type(converted_num)) # Output: <class 'int'>
Tuple
A tuple is an immutable Python Object. Immutable Python objects mean we cannot alter the contents of a tuple once it is assigned. It is represented by () parenthesis.
Example:
tup = (66,99) Tup[0] = 3 #error will be displayed print(tup[0]) print(tup[1])
Mastering data types is a foundational step in Python programming.