Programming 20 Apr 2025 12 mins read

Sprint 1: Python Fundamentals Review

By James Nguyen

Introduction

A comprehensive review of fundamental Python concepts covered in Sprint 1 of the TripleTen bootcamp. This deep dive covers essential Python data types, data structures, control flow, functions, and data manipulation with Pandas.

String Operations and Methods

Detailed look at string manipulation:

  • String Creation and Formatting:
    # String creation
    single_quotes = 'Hello'
    double_quotes = "World"
    multi_line = '''This is a
    multi-line string'''
    
    # String formatting
    name = "Alice"
    age = 25
    formatted = f"{name} is {age} years old"
    template = "{} is {} years old".format(name, age)
    old_style = "%s is %d years old" % (name, age)
  • String Methods:
    # Common string methods
    text = "  Hello, World!  "
    length = len(text)                # Get length
    stripped = text.strip()           # Remove whitespace
    upper = text.upper()              # Convert to uppercase
    lower = text.lower()              # Convert to lowercase
    replaced = text.replace(',', ';') # Replace characters
    split_words = text.split(',')     # Split into list
    is_digit = '123'.isdigit()       # Check if digits
    is_alpha = 'abc'.isalpha()       # Check if letters
    starts = text.startswith('Hello') # Check prefix
    ends = text.endswith('!')        # Check suffix
    position = text.find('World')    # Find substring
    count = text.count('l')          # Count occurrences
  • String Indexing and Slicing:
    text = "Python Programming"
    first_char = text[0]      # First character
    last_char = text[-1]      # Last character
    slice_1 = text[0:6]       # Characters 0 to 5
    slice_2 = text[7:]        # Characters from 7 to end
    slice_3 = text[:6]        # Characters from start to 5
    reverse = text[::-1]      # Reverse the string
    step_2 = text[::2]        # Every second character

Lists and Tuples

Comprehensive coverage of sequence types:

  • List Operations:
    # List creation and modification
    numbers = [1, 2, 3, 4, 5]
    mixed = [1, "hello", 3.14, True]
    
    # List methods
    numbers.append(6)        # Add to end
    numbers.insert(0, 0)     # Insert at position
    numbers.extend([7, 8])   # Add multiple items
    numbers.remove(3)        # Remove value
    popped = numbers.pop()   # Remove and return last item
    popped_index = numbers.pop(0)  # Remove at index
    numbers.reverse()        # Reverse in place
    numbers.sort()          # Sort in place
    sorted_copy = sorted(numbers)  # Return sorted copy
    count = numbers.count(1)      # Count occurrences
    index = numbers.index(4)      # Find position
    
    # List comprehension
    squares = [x**2 for x in range(5)]
    evens = [x for x in numbers if x % 2 == 0]
  • Tuple Operations:
    # Tuple creation
    point = (3, 4)
    singleton = (1,)    # Single item tuple needs comma
    mixed = (1, "two", 3.0)
    
    # Tuple methods (immutable, fewer methods)
    count = point.count(3)    # Count occurrences
    index = point.index(4)    # Find position
    
    # Tuple unpacking
    x, y = point
    a, *rest, b = (1, 2, 3, 4)  # Extended unpacking

Control Flow and Loops

Detailed explanation of control structures:

  • Conditional Statements:
    # If statements
    if x > 0:
        print("Positive")
    elif x < 0:
        print("Negative")
    else:
        print("Zero")
    
    # Conditional expressions (ternary)
    status = "adult" if age >= 18 else "minor"
    
    # Multiple conditions
    if age >= 18 and income > 30000:
        print("Eligible for loan")
    
    # Membership testing
    if name in approved_list:
        print("Access granted")
  • Loops and Iterations:
    # For loops
    for i in range(5):
        print(i)
    
    # Loop with enumerate
    for index, value in enumerate(items):
        print(f"{index}: {value}")
    
    # Loop with zip
    for x, y in zip(list1, list2):
        print(f"{x} matches {y}")
    
    # While loops
    count = 0
    while count < 5:
        print(count)
        count += 1
    
    # Loop control
    for item in items:
        if item.is_invalid():
            continue    # Skip to next iteration
        if item.is_last():
            break       # Exit loop
        process(item)
    
    # Nested loops
    for i in range(3):
        for j in range(3):
            print(f"({i}, {j})")
  • Loop with List/Dict Comprehension:
    # List comprehension with conditions
    numbers = [x for x in range(10) if x % 2 == 0]
    
    # Dictionary comprehension
    squares = {x: x**2 for x in range(5)}
    
    # Nested comprehension
    matrix = [[i+j for j in range(3)] for i in range(3)]

Basic Python Syntax

Essential Python syntax elements:

  • Comments:
    # Single line comment
    '''
    Multi-line
    comment
    '''
  • Print statements:
    print("Hello, World!")
    print(f"Value is {variable}")  # f-strings
    print("Score: %.2f" % score)   # % formatting
    print("Name: {}".format(name)) # .format()
  • Variables:
    x = 5           # Integer
    name = "John"    # String
    price = 19.99    # Float
    is_valid = True  # Boolean

Python Data Types and Conversion

Common data types and conversion methods:

  • String Operations:
    text = "Hello"
    length = len(text)
    upper_case = text.upper()
    lower_case = text.lower()
    split_text = "a,b,c".split(",")
    joined_text = " ".join(['Hello', 'World'])
  • Type Conversion:
    str_to_int = int("123")
    str_to_float = float("123.45")
    num_to_str = str(123)
    to_bool = bool(1)
  • Common Errors:
    try:
        int("abc")  # ValueError
        1/0         # ZeroDivisionError
    except ValueError as e:
        print("Invalid conversion:", e)
    except ZeroDivisionError as e:
        print("Division by zero:", e)

Mathematical Operations

Basic and advanced mathematical operations:

  • Basic Math:
    addition = 5 + 3
    subtraction = 10 - 4
    multiplication = 6 * 2
    division = 15 / 3
    floor_division = 15 // 4
    modulus = 15 % 4
    exponent = 2 ** 3
  • Math Module:
    import math
    
    pi_value = math.pi
    square_root = math.sqrt(16)
    ceiling = math.ceil(4.3)
    floor = math.floor(4.7)

Data Structures

Detailed look at Python's data structures:

  • Lists:
    numbers = [1, 2, 3, 4, 5]
    numbers.append(6)      # Add element
    numbers.pop()         # Remove last element
    numbers.insert(0, 0)  # Insert at index
    sliced = numbers[1:4] # Slicing
  • Dictionaries:
    person = {
        'name': 'John',
        'age': 30,
        'city': 'New York'
    }
    person['email'] = 'john@example.com'  # Add key-value
    del person['age']                     # Remove key
    keys = person.keys()                  # Get keys
    values = person.values()              # Get values

Functions and Methods

Different types of functions and their usage:

  • Basic Function:
    def greet(name):
        return f"Hello, {name}!"
  • Default Parameters:
    def calculate_total(price, tax_rate=0.1):
        return price * (1 + tax_rate)
  • Multiple Returns:
    def get_stats(numbers):
        return min(numbers), max(numbers), sum(numbers)
  • Lambda Functions:
    square = lambda x: x**2
    double = lambda x: x*2

Pandas Library

Essential Pandas operations:

  • DataFrame Creation:
    import pandas as pd
    
    df = pd.DataFrame({
        'name': ['John', 'Jane'],
        'age': [25, 30]
    })
  • Data Selection:
    # Column selection
    names = df['name']
    
    # Filtering
    adults = df[df['age'] >= 18]
    
    # Multiple conditions
    filtered = df[
        (df['age'] > 20) & 
        (df['name'].str.startswith('J'))
    ]
  • Missing Values:
    # Check missing
    null_count = df.isnull().sum()
    
    # Fill missing
    df.fillna(0)  # Fill with zero
    df.dropna()   # Remove missing
  • Grouping and Aggregation:
    # Group by and calculate mean
    grouped = df.groupby('category')['value'].mean()
    
    # Multiple aggregations
    aggs = df.groupby('category').agg({
        'value': ['mean', 'sum'],
        'count': 'max'
    })

Error Handling

Common error handling patterns:

def safe_division(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        result = None
    except TypeError:
        print("Invalid types for division")
        result = None
    else:
        print("Division successful")
    finally:
        return result

Best Practices

  • Use meaningful variable names
  • Add comments for complex logic
  • Handle errors appropriately
  • Follow PEP 8 style guide
  • Write modular, reusable code
  • Include proper documentation