In our previous discussion, we explored variables—how they store different types of values in Python. Now, let's dive into data types, which define the kind of data stored in a variable.
Unlike languages such as Java, C, or C++, where you must explicitly declare a variable’s type, Python handles data types dynamically. This means you can directly assign a value to a variable without specifying its type.
What Are Data Types?
A data type not only defines the type of data stored in a variable but also determines the amount of memory allocated for that variable.
Common Data Types in Python
Python provides several built-in data types:
Integer (int) – Whole numbers, both positive and negative.
num1 = 23
num2 = -232
*Floating-point (float) *– Numbers with decimals.
num3 = 23.232
num4 = -23.232
String (str) – Text enclosed in single or double quotes.
name = "Brian"
blood_group = 'B'
Character (char) – Python doesn’t have a separate char type like C or Java. Instead, a single-character string (e.g., 'A', 'B') is still a string.
Boolean (bool) – Represents True or False, often used in conditions.
is_greater = 10 > 3 # True
is_adult = age >= 18 # True
Complex Numbers (complex)
Python has a built-in complex type, which is not commonly found in some languages.
num = 3 + 4j # Complex number
print(type(num)) # Output: <class 'complex'>
Checking Data Types and Memory Usage
Python provides the** type()** function to check the type of any variable:
print(type(232)) # Output: <class 'int'>
print(type(23.232)) # Output: <class 'float'>
print(type("Brian")) # Output: <class 'str'>
print(type(True)) # Output: <class 'bool'>
To check the memory size of a variable, use sys.getsizeof():
import sys
print(sys.getsizeof(232)) # Output: Memory size of int
print(sys.getsizeof(23.232)) # Output: Memory size of float
print(sys.getsizeof("Brian")) # Output: Memory size of string
Memory Usage of Data Types
Different data types occupy different amounts of memory in Python.
Key Observations:
Integers (int) – Generally take 28 bytes, but the size can increase with larger numbers.
Floating-point numbers (float) – Usually 24 bytes, independent of the value.
Strings (str) – Memory depends on the length of the string. Each character takes extra space.
*Boolean (bool) *– Takes 28 bytes, same as an integer.
Note: Unlike C or Java, where int and float have fixed sizes (e.g., 4 bytes, 8 bytes), Python’s data types are dynamically sized. The actual memory usage can vary depending on the system and Python implementation.
Key Takeaways:
✔ Data types define both the type and memory usage of variables.
✔ Strings generally require more memory than integers or booleans.
✔ Use type() to check the data type and sys.getsizeof() to check memory allocation.
✔ Python dynamically assigns types without explicit declarations.
This flexibility makes Python beginner-friendly while keeping it powerful for complex applications. 🚀
Top comments (0)