Data Types
Python is a dynamically typed language, meaning you don't need to explicitly declare the data type of a variable before assigning a value to it. The interpreter automatically determines the data type based on the assigned value.
Python offers a variety of built-in data types to handle different kinds of data. Let's explore them in detail:
Numeric Types
- int(Integers): Represents integer values (whole numbers without decimal points).
Python
x = 10
print(type(x)) # Output: <class 'int'>
- float: Represents floating-point numbers (numbers with decimal points).
Python
y = 3.14
print(type(y)) # Output: <class 'float'>
- complex: Represents complex numbers (numbers with real and imaginary parts).
Python
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
Sequence Types
- list: An ordered collection of items, mutable (can be changed).
Python
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
- tuple: An ordered collection of items, immutable (cannot be changed).
Python
colors = ("red", "green", "blue")
print(type(colors)) # Output: <class 'tuple'>
- range: Represents a sequence of numbers.
Python
numbers = range(5) # Creates a sequence from 0 to 4
print(type(numbers)) # Output: <class 'range'>
Boolean Type
- bool: Represents logical values, either True or False.
Python
is_valid = True
print(type(is_valid)) # Output: <class 'bool'>
Set Types
- set: An unordered collection of unique items.
Python
unique_numbers = {1, 2, 3, 3, 4} # Duplicates are removed
print(type(unique_numbers)) # Output: <class 'set'>
- frozenset: An immutable version of set.
Python
immutable_set = frozenset([1, 2, 3])
print(type(immutable_set)) # Output: <class 'frozenset'>
Mapping Type
- dict: An unordered collection of key-value pairs.
Python
person = {"name": "Alice", "age": 30}
print(type(person)) # Output: <class 'dict'>
Binary Types
- bytes: Represents an immutable sequence of bytes.
Python
data = b'hello'
print(type(data)) # Output: <class 'bytes'>
- bytearray: A mutable sequence of bytes.
Python
data = bytearray(5)
print(type(data)) # Output: <class 'bytearray'>
- memoryview: A view of a memory buffer.
None Type
- None: Represents the absence of a value.
Python
result = None
print(type(result)) # Output: <class 'NoneType'>
Remember: Python is dynamically typed, so you can change the data type of a variable by assigning a different value to it.