🐍Python - intermediate

Abheeshta PAbheeshta P
3 min read

🧱 Core Data Types

βœ… Tuples

  • Ordered, immutable collection.

  • Syntax: my_tuple = (1, 2, 3)

  • Can contain mixed data types.

  • Use case: when data shouldn't change (like coordinates, RGB values).

βœ… Sets

  • Unordered, mutable collection of unique elements.

  • Syntax: my_set = {1, 2, 3}

  • No duplicates, useful for membership tests and removing duplicates.

βœ… Strings

  • Immutable sequence of characters.

  • Syntax: s = "hello"

  • Supports slicing, iteration, and various methods: .upper(), .find(), etc.

βœ… Dictionaries

  • Key-value pairs (like JSON objects).

  • Syntax: my_dict = {'name': 'Alice', 'age': 25}

  • Access using: my_dict['name'] or .get('name')

  • Mutable, can add/update with [].


πŸ› οΈ Error Handling

try:
    risky_code()
except ValueError as e:
    print("Caught!", e)
else:
    print("No error occurred.")
finally:
    print("Always runs.")
  • try: Place the code that may raise an error.

  • except: Catch specific or generic exceptions.

  • else: Runs only if no exception occurs.

  • finally: Runs no matter what (used for cleanup, closing files etc).


🧬 Functional Programming

βœ… Higher-Order Functions

  • Functions that take or return other functions.
def greet(fn): return fn("world")

βœ… Lambda Functions

  • One-liner anonymous function:
square = lambda x: x*x

βœ… Map & Filter

map(func, iterable)    β†’ Applies `func` to every item
filter(func, iterable) β†’ Returns items where `func(item)` is True

Example:

list(map(lambda x: x*2, [1,2,3]))       # [2, 4, 6]
list(filter(lambda x: x%2==0, [1,2,3])) # [2]

βœ… *args and **kwargs

def func(a, *args, **kwargs):
    print(args)   # Tuple of extra positional args
    print(kwargs) # Dict of extra keyword args

Order: regular β†’ *args β†’ **kwargs

βœ… Decorators

  • Functions that wrap other functions to add extra behavior.
def decorator(fn):
    def wrapper():
        print("Before")
        fn()
        print("After")
    return wrapper

@decorator
def say_hi(): print("Hi")

🧱 Object-Oriented Programming (OOP)

βœ… Class & Object

class Dog:
    def __init__(self, name):  # constructor
        self.name = name
    def bark(self): 
        print(f"{self.name} barks!")

dog1 = Dog("Tommy")
dog1.bark()

βœ… 3 Pillars of OOP

1. Abstraction

  • Hides internal implementation and shows only relevant data.

  • Example: Using .append() without knowing list internals.

2. Inheritance

  • Deriving a new class from an existing one.
class Animal:
    def speak(self): print("Animal sound")
class Dog(Animal):
    def speak(self): print("Bark!")  # Overriding
  • Use super().__init__() to call parent’s constructor.

3. Polymorphism

  • Same method name behaves differently depending on object.
for animal in [Dog(), Cat()]:
    animal.speak()  # Different outputs for each

βœ… Data Hiding

  • Protected: _var β†’ meant for internal use, but still accessible.

  • Private: __var β†’ truly private, name-mangled internally.

class A:
    def __init__(self):
        self._protected = "Protected"
        self.__private = "Private"

βœ… @classmethod vs @staticmethod

class MyClass:
    count = 0

    @classmethod
    def increment(cls):  # Works on the class itself
        cls.count += 1

    @staticmethod
    def greet():  # Utility method, no access to class or instance
        print("Hello!")
  • Classmethod β†’ used to manipulate class-level data.

  • Staticmethod β†’ like a regular function, but grouped inside class for utility.

Thanks for reading!

0
Subscribe to my newsletter

Read articles from Abheeshta P directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abheeshta P
Abheeshta P

I am a Full-stack dev turning ideas into sleek, functional experiences πŸš€. I am passionate about AI, intuitive UI/UX, and crafting user-friendly platforms . I am always curious – from building websites to diving into machine learning and under the hood workings ✨. Next.js, Node.js, MongoDB, and Tailwind are my daily tools. I am here to share dev experiments, lessons learned, and the occasional late-night code breakthroughs. Always evolving, always building.