Module 2: Python Refresher

Learning Objectives

By the end of this module, you will be able to:

  • Declare variables and use Python’s core data types

  • Write conditional statements and loops

  • Work with lists, tuples, dictionaries, and sets

  • Define and call functions

  • Read and write files

  • Understand list comprehensions and generators


Variables and Data Types

Python is dynamically typed — variables do not require explicit type declarations.

# Basic data types
name = "Alice"          # str
age = 30                # int
height = 5.7            # float
is_student = False      # bool
grades = [85, 92, 78]   # list
coordinates = (10, 20)  # tuple
person = {"name": "Alice", "age": 30}  # dict

# Type checking
print(type(name))       # <class 'str'>
print(type(age))        # <class 'int'>

Tip

Use type() during development to verify variable types. Pandas relies heavily on NumPy dtypes like int64, float64, and object.

Operators

# Arithmetic
print(10 + 3)    # 13
print(10 / 3)    # 3.333...
print(10 // 3)   # 3 (floor division)
print(10 ** 3)   # 1000 (exponent)

# Comparison
print(5 > 3)     # True
print(5 == 5)    # True

# Logical
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# Membership
print("a" in ["a", "b", "c"])  # True
print(5 not in range(10))      # False

Functions

def calculate_bmi(weight_kg: float, height_m: float) -> float:
    """Calculate Body Mass Index."""
    return weight_kg / (height_m ** 2)

# Default arguments
def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"

# Lambda (anonymous) functions
square = lambda x: x ** 2
print(square(5))  # 25

print(calculate_bmi(70, 1.75))   # 22.86
print(greet("Alice"))            # Hello, Alice!
print(greet("Bob", "Hi"))        # Hi, Bob!

Note

Type hints (: float, -> float) are optional but recommended for readability and tooling support.

Conditional Statements

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")  # Grade: B

# Ternary expression
status = "Pass" if score >= 50 else "Fail"

Loops

for loop

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit.upper())

# Enumerate for index + value
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

while loop

count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

List comprehensions (essential for Pandas)

# Traditional loop
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension
squares = [x ** 2 for x in range(10)]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

Tip

List comprehensions are faster than explicit loops and are the idiomatic way to transform data in Python. Pandas .apply() often replaces the need for explicit loops entirely.

Lists

# Creation and indexing
items = [10, 20, 30, 40, 50]
print(items[0])     # 10
print(items[-1])    # 50
print(items[1:3])   # [20, 30]

# Methods
items.append(60)               # [10, 20, 30, 40, 50, 60]
items.insert(0, 5)             # [5, 10, 20, 30, 40, 50, 60]
items.remove(30)               # [5, 10, 20, 40, 50, 60]
popped = items.pop()           # 60

Tuples (immutable sequences)

point = (3, 4)
x, y = point                  # Tuple unpacking
print(x, y)                   # 3 4

# Tuples as dictionary keys (lists cannot be)
locations = {
    (40.7128, -74.0060): "New York",
    (51.5074, -0.1278): "London",
}

Dictionaries

student = {
    "name": "Alice",
    "age": 25,
    "courses": ["Math", "Physics"],
}

# Access
print(student["name"])              # Alice
print(student.get("grade", "N/A"))  # N/A (safe access)

# Modification
student["grade"] = "A"
student.update({"age": 26, "city": "Boston"})

# Iteration
for key, value in student.items():
    print(f"{key}: {value}")

Sets

# Unique elements
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)   # Union:     {1, 2, 3, 4, 5, 6, 7, 8}
print(a & b)   # Intersection: {4, 5}
print(a - b)   # Difference:   {1, 2, 3}

# Remove duplicates from a list
unique = list(set([1, 2, 2, 3, 3, 4]))
print(unique)  # [1, 2, 3, 4]

File Handling

# Writing to a file
with open("data.txt", "w") as f:
    f.write("Name,Age,City\n")
    f.write("Alice,25,New York\n")
    f.write("Bob,30,Paris\n")

# Reading from a file
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# Reading line by line
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip().split(","))

Warning

Always use the with statement for file operations. It ensures the file is properly closed even if an exception occurs.

Common Built-in Functions for Data Work

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

print(len(numbers))       # 8
print(sum(numbers))       # 31
print(min(numbers))       # 1
print(max(numbers))       # 9
print(sorted(numbers))    # [1, 1, 2, 3, 4, 5, 6, 9]
print(list(reversed(numbers)))  # [6, 2, 9, 5, 1, 4, 1, 3]

# zip - combine iterables
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
pairs = list(zip(names, ages))
print(pairs)  # [("Alice", 25), ("Bob", 30), ("Charlie", 35)]

Summary

  • Python’s core data types (int, float, str, bool, list, tuple, dict, set) are the building blocks

  • List comprehensions provide concise, fast data transformations

  • Functions with type hints improve code readability

  • File I/O with with ensures proper resource management

  • These fundamentals map directly to Pandas operations

Exercises

  1. Write a function that takes a list of numbers and returns a dictionary with mean, median, and std keys

  2. Use a list comprehension to generate all even numbers from 1 to 50

  3. Read a CSV file line by line and build a list of dictionaries (one per row)

  4. Create a set of unique words from the sentence: "the quick brown fox jumps over the lazy dog"

Further Reading