Built-in Data Types
Python has several built-in data types for storing different kinds of information. Understanding these types is fundamental to Python programming.
🔢 Numeric Types
# Integer (int) - whole numbers
age = 25
count = -10
big_number = 1_000_000 # Underscores for readability
# Float - decimal numbers
price = 19.99
temperature = -5.5
scientific = 1.5e-4 # 0.00015
# Complex numbers
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
# Type conversion
x = int(3.8) # 3
y = float(5) # 5.0
z = str(42) # "42"
# Arithmetic
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.333...
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (modulo)
print(10 ** 3) # 1000 (power)
📝 Strings (str)
# String creation
name = "Alice"
message = 'Hello World'
multi_line = """This is
a multi-line
string"""
# String operations
greeting = "Hello"
full = greeting + " " + name # Concatenation
repeat = "Ha" * 3 # "HaHaHa"
# String methods
text = " Python Programming "
print(text.upper()) # " PYTHON PROGRAMMING "
print(text.lower()) # " python programming "
print(text.strip()) # "Python Programming"
print(text.replace("Python", "Java"))
print(text.split()) # ['Python', 'Programming']
# String indexing & slicing
word = "Python"
print(word[0]) # 'P' (first character)
print(word[-1]) # 'n' (last character)
print(word[0:3]) # 'Pyt' (slice)
print(word[:3]) # 'Pyt'
print(word[3:]) # 'hon'
print(word[::-1]) # 'nohtyP' (reverse)
# String formatting
name = "Bob"
age = 25
print(f"{name} is {age} years old") # f-strings (Python 3.6+)
print("{} is {} years old".format(name, age))
print("%s is %d years old" % (name, age))
✅ Boolean (bool)
# Boolean values
is_active = True
is_logged_in = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# Comparisons return boolean
print(5 > 3) # True
print(5 == 5) # True
print(5 != 3) # True
# Truthy and Falsy values
# Falsy: False, None, 0, 0.0, "", [], {}, ()
# Everything else is Truthy
if "":
print("This won't print")
if "Hello":
print("This will print")
📋 Lists (Mutable, Ordered)
# List creation
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# List methods
fruits.append("orange") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
# List operations
print(len(fruits)) # Length
print(fruits[0]) # First item
print(fruits[-1]) # Last item
print(fruits[1:3]) # Slice
print("apple" in fruits) # Check membership
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
📦 Tuples (Immutable, Ordered)
# Tuple creation
coordinates = (10, 20)
rgb = (255, 0, 128)
single = (42,) # Single element tuple needs comma
# Tuple unpacking
x, y = coordinates
print(x) # 10
# Tuples are immutable
# coordinates[0] = 15 # Error!
# Use tuples for fixed data
point = (3, 4)
person = ("Alice", 30, "Engineer")
📖 Dictionaries (Key-Value Pairs)
# Dictionary creation
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"]) # "Alice"
print(person.get("age")) # 30
print(person.get("job", "N/A")) # Default if key doesn't exist
# Modifying
person["age"] = 31 # Update
person["job"] = "Engineer" # Add new key
# Dictionary methods
print(person.keys()) # All keys
print(person.values()) # All values
print(person.items()) # Key-value pairs
# Loop through dictionary
for key, value in person.items():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, ...}
🎲 Sets (Unique Elements)
# Set creation
numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4} - duplicates removed
fruits = set(["apple", "banana", "apple"]) # {'apple', 'banana'}
# Set operations
numbers.add(5) # Add element
numbers.remove(3) # Remove element
numbers.discard(10) # Remove if exists (no error)
# Set math
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
⭕ None Type
# None represents absence of value
result = None
# Check for None
if result is None:
print("No result yet")
# Functions return None by default
def do_nothing():
pass
value = do_nothing()
print(value) # None
🎯 Key Takeaways
- int, float, complex: Numeric types
- str: Text/string data (immutable)
- bool: True or False values
- list: Ordered, mutable collection [1, 2, 3]
- tuple: Ordered, immutable collection (1, 2, 3)
- dict: Key-value pairs {"name": "Alice"}
- set: Unique elements {1, 2, 3}
- None: Represents null/no value