A Primer on Python

Mastering the essentials: Basics, Data Structures, OOP, and Exception Handling.

Python is a high-level, interpreted programming language known for its elegance and readability. Whether you are building simple scripts or complex machine learning models, Python’s intuitive syntax allows you to express concepts clearly and concisely.

In this guide, we will explore the core pillars of Python programming, from fundamental statements to advanced object-oriented paradigms.


1. Python Basics & Statements

Python relies on indentation (whitespace) to define scope, rather than curly braces. This enforces clean, readable code by default.

Variables & Types

Variables are dynamically typed, meaning you don't need to declare their type explicitly.

name = "Alice"     # String
age = 30           # Integer
height = 5.6       # Float
is_student = True  # Boolean

Control Flow

Conditional statements (if, elif, else) and loops (for, while) govern the flow of your program.

# If Statement
if age >= 18:
    print("Adult")
elif age > 12:
    print("Teenager")
else:
    print("Child")

# For Loop (iterating over a sequence)
for i in range(3):
    print(f"Iteration {i}")

2. Strings & Methods

Strings are sequences of characters used to store and manipulate text. Python provides a rich set of built-in methods for strings.

text = " Python Programming "

# Common String Methods
print(text.strip())           # "Python Programming" (Removes leading/trailing whitespace)
print(text.lower())           # " python programming "
print(text.upper())           # " PYTHON PROGRAMMING "
print(text.replace("P", "J")) # " Jython Jrogramming "

# Splitting and Joining
words = text.split()          # ['Python', 'Programming']
joined = "-".join(words)      # "Python-Programming"
print(joined)

3. Built-in Data Structures

Python provides several versatile built-in data structures. Choosing the right one is crucial for writing efficient code.

List

Lists are ordered, mutable (changeable) sequences. They can hold elements of different types.

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

# Methods
fruits.append("date")        # Add to end
fruits.insert(1, "mango")    # Insert at index
fruits.pop()                 # Remove last item
fruits.remove("banana")      # Remove specific value

print(fruits[0])             # Get item at index 0

Array

Unlike lists, standard arrays in Python (via the array module) must contain elements of the same type. They are more memory efficient for large numeric datasets.

import array

# 'i' denotes integer type
numbers = array.array('i', [1, 2, 3, 4])
numbers.append(5)
print(numbers[0])

Tuple

Tuples are ordered but immutable. Once created, you cannot change their elements. They are faster than lists and serve as reliable dictionary keys.

coordinates = (10.0, 20.0)

# Methods are limited since it's immutable
print(coordinates.count(10.0))  # Counts occurrences
print(coordinates.index(20.0))  # Finds index

# coordinates[0] = 15.0  # TypeError: does not support item assignment

Set

Sets are unordered collections of unique elements. They are highly optimized for membership testing (checking if an item exists).

unique_ids = {101, 102, 103, 103} # Duplicates are ignored

unique_ids.add(104)
unique_ids.remove(101)

# Set operations
evens = {2, 4, 6}
primes = {2, 3, 5}
print(evens.intersection(primes))  # {2}

Dictionary

Dictionaries store data in key-value pairs. Keys must be immutable (like strings or tuples) and unique.

user = {
    "name": "Bob",
    "role": "Admin"
}

# Methods
user["age"] = 28                 # Add / Update
role = user.get("role", "Guest") # Safe Get
del user["age"]                  # Delete key

for key, value in user.items():
    print(f"{key}: {value}")

4. File Operations

Python makes interacting with the file system straightforward. The best practice is using the with statement, which automatically closes the file when done, preventing memory leaks.

Writing and Reading

# Writing to a file
with open("data.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Learning Python is fun.")

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

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

5. Object-Oriented Programming (OOP)

Python is a multi-paradigm language, heavily supporting OOP. The core concepts of OOP allow for structured, reusable, and modular code.

1. Class & Object

A Class is a blueprint, while an Object is an instance of that blueprint.

class Car:
    def __init__(self, brand):
        self.brand = brand  # Attribute

my_car = Car("Toyota")  # Object creation
print(my_car.brand)

2. Encapsulation

Bundling data and methods within a class, and restricting direct access to some of the object's components.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def get_balance(self):
        return self.__balance

account = BankAccount(100)
print(account.get_balance())
# print(account.__balance) # AttributeError: Cannot access private member

3. Inheritance

Creating a new class based on an existing class to promote code reusability.

class Animal:
    def speak(self):
        return "Animal sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

dog = Dog()
print(dog.speak())

4. Polymorphism

The ability of different objects to respond to the same method call in their own specific way.

class Cat(Animal):
    def speak(self):
        return "Meow!"

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak()) # Outputs "Woof!" then "Meow!"

5. Abstraction

Hiding complex implementation details and showing only the essential features using abstract classes.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side * self.side

sq = Square(4)
print(sq.area())

6. Exception Handling

Errors are inevitable. Python uses a try-except block to gracefully handle exceptions without crashing the program.

Basic Try-Except

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Error: Cannot divide by zero.")
finally:
    print("This block always executes.")

Custom Exceptions

You can define your own exception classes by inheriting from Python's built-in Exception class.

class NegativeValueError(Exception):
    """Raised when a value is negative"""
    pass

def set_age(age):
    if age < 0:
        raise NegativeValueError("Age cannot be negative.")
    return age

try:
    set_age(-5)
except NegativeValueError as e:
    print(f"Validation Failed: {e}")