Python Data Types
Master the fundamental data types in Python programming
🎯 Understanding Data Types
Data types specify the kind of data that can be stored and manipulated within a program. Python has several built-in data types that are essential for programming.
# Basic Python data types
number = 42 # Integer
decimal = 3.14 # Float
text = "Hello" # String
is_valid = True # Boolean
Python Built-in Data Types
Python has several categories of built-in data types. Let's explore each category:
Numeric Types
Store numerical values for calculations
Text Type
Handle text and character data
Boolean Type
Represent True/False values
Sequence Types
Store ordered collections of items
Mapping Type
Store key-value pairs
Set Types
Store unique elements
🔹 Numeric Types
Python has three numeric data types: int, float, and complex
# Example of numeric types
x = 5 # int
y = 3.14 # float
z = 2 + 3j # complex
# Basic operations
sum = x + y # Addition
diff = x - y # Subtraction
prod = x * y # Multiplication
div = x / y # Division
print(f"x = {x}, type: {type(x)}")
print(f"y = {y}, type: {type(y)}")
print(f"z = {z}, type: {type(z)}")
print(f"Sum: {sum}")
print(f"Difference: {diff}")
print(f"Product: {prod}")
print(f"Division: {div}")
🔹 Text Type (String)
Strings store text data and are enclosed in quotes
# String creation
s = 'Hi'
name = "Python"
text = """Multi
line"""
# Basic operations
a = "Hello"
b = "World"
c = a + " " + b
d = "Hi! " * 2
print(f"{c}")
print(f"{d}")
print(f"{len(a)}")
print(f"{a.upper()}")
# Access chars
x = "Code"
print(f"{x[0]}") # C
print(f"{x[-1]}") # e
print(f"{x[1:3]}") # od
🔹 Boolean Type
Booleans represent True or False values
# Boolean values
is_student = True
is_graduated = False
has_job = True
# Boolean from comparisons
x, y = 10, 5
print(f"{x} > {y} = {x > y}") # True
print(f"{x} == {y} = {x == y}") # False
# Boolean operations
print(f"True and False = {True and False}") # False
print(f"True or False = {True or False}") # True
print(f"not True = {not True}") # False
# Truthiness examples
print(f"bool(1) = {bool(1)}") # True
print(f"bool(0) = {bool(0)}") # False
print(f"bool('hello') = {bool('hello')}") # True
print(f"bool('') = {bool('')}") # False
🔹 Collection Types
Store multiple items in a single variable
# List example
colors = ["red", "blue"]
print(colors)
# Tuple example
point = (1, 2)
print(point)
# Dict example
person = {"name": "Bob", "age": 25}
print(person)
# Set example
numbers = {1, 2, 3}
print(numbers)
# Range example
print(list(range(3)))
🔹 Type Checking and Conversion
Check and convert data types
# Type checking
x = "Hello"
y = 10
print(f"Type of x: {type(x)}") # str
print(f"Type of y: {type(y)}") # int
# Convert types
num = "123"
print(f"String to int: {int(num)}") # 123
print(f"Int to string: {str(y)}") # "10"
# Safe conversion
def convert_to_int(val):
try:
return int(val)
except ValueError:
return f"Can't convert {val}"
print(convert_to_int("123")) # 123
print(convert_to_int("abc")) # Can't convert abc
🔹 Mutable vs Immutable
Understanding which types can be changed after creation
🔒 Immutable Types (cannot be changed):
-
int,float,complex -
str,bool -
tuple,frozenset
🔓 Mutable Types (can be changed):
-
list,dict,set
# Immutable example - strings
text = "Hello"
print(f"Original: {text}, ID: {id(text)}")
text = text + " World" # Creates new string object
print(f"Modified: {text}, ID: {id(text)}") # Different ID
# Mutable example - lists
fruits = ["apple", "banana"]
print(f"Original: {fruits}, ID: {id(fruits)}")
fruits.append("cherry") # Modifies same object
print(f"Modified: {fruits}, ID: {id(fruits)}") # Same ID
# Practical implications
def modify_list(lst):
lst.append("modified") # Changes original list
return lst
def modify_string(s):
s = s + " modified" # Creates new string
return s
original_list = ["a", "b", "c"]
original_string = "hello"
result_list = modify_list(original_list)
result_string = modify_string(original_string)
print(f"Original list after function: {original_list}") # Changed!
print(f"Original string after function: {original_string}") # Unchanged!