Category: Learn Python

  • How to Create Your Own Python Package (Step-by-Step Guide)



    πŸ”Έ What is a Package?

    • A package is a folder that contains Python files (modules).
    • It helps you organize your code.
    • You can reuse the code in many projects.

    βœ… Why Use Packages?

    • Keeps your code clean and structured
    • Makes code reusable
    • Easy to share with others

    🧳 Step-by-Step: Create Your Own Python Package


    πŸ”Ή Step 1: Create Folder Structure

    Let’s say you want a package named mymath.

    mymath/
    β”‚
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ add.py
    └── multiply.py
    
    

    βœ… __init__.py makes this folder a package.


    πŸ”Ή Step 2: Write Module Files

    πŸ“„ add.py:

    def add(a, b):
        return a + b
    
    

    πŸ“„ multiply.py:

    def multiply(a, b):
        return a * b
    
    

    πŸ“„ __init__.py:

    from .add import add
    from .multiply import multiply
    
    

    πŸ”Ή Step 3: Use the Package in Your Code

    Create a new file outside the folder (for example: main.py)

    πŸ“„ main.py:

    from mymath import add, multiply
    
    print(add(2, 3))        # Output: 5
    print(multiply(2, 3))   # Output: 6
    
    

    βœ… Now your package is working!


    πŸ”Ή Step 4 (Optional): Add __all__ in __init__.py

    This helps when you use from mymath import *

    __all__ = ['add', 'multiply']
    
    

    βœ… Practice Time

    Q1: Create a package called greet with:

    • hello.py: hello(name) β†’ prints β€œHello, [name]”
    • bye.py: bye(name) β†’ prints β€œGoodbye, [name]”

    Answer:

    Folder:

    greet/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ hello.py
    └── bye.py
    
    

    πŸ“„ hello.py:

    def hello(name):
        print(f"Hello, {name}")
    
    

    πŸ“„ bye.py:

    def bye(name):
        print(f"Goodbye, {name}")
    
    

    πŸ“„ __init__.py:

    from .hello import hello
    from .bye import bye
    
    

    Use it in main.py:

    from greet import hello, bye
    
    hello("John")
    bye("John")
    
    

    πŸ“¦ Bonus: Make it Installable (Advanced)

    To share with others (like on PyPI), create a setup.py:

    from setuptools import setup, find_packages
    
    setup(
        name='mymath',
        version='0.1',
        packages=find_packages()
    )
    
    

    Then run:

    python setup.py install
    
    

    🧾 Summary

    StepWhat to Do
    1Create folder and files
    2Add __init__.py
    3Write code in modules
    4Import and use

    🧠 Final Tip:

    You can create your own Python tools using packages.
    Perfect for organizing large projects!


  • Most Used Libraries and Packages in Python | Easy Guide for Beginners



    πŸ”Ή What is a Python Library or Package?

    • A library is a group of ready-made code that helps you do tasks easily.
    • A package is a folder that contains many libraries or modules.

    βœ… You don’t need to write everything from scratch. Just import and use!


    πŸ”Έ How to Install a Library?

    pip install library_name
    
    

    Example:

    pip install numpy
    
    

    πŸ”Ή Most Popular Python Libraries by Category


    πŸ“Š 1. Data Analysis & Math

    LibraryUse
    NumPyWork with arrays, math functions
    PandasHandle tables (rows and columns)
    MatplotlibDraw charts and graphs
    SeabornMake beautiful statistical graphs

    βœ… Example:

    import numpy as np
    
    a = np.array([1, 2, 3])
    print(a * 2)  # Output: [2 4 6]
    
    

    πŸ€– 2. Machine Learning

    LibraryUse
    scikit-learnBuild ML models like classification
    TensorFlowDeep learning (Google)
    KerasEasy-to-use deep learning library

    βœ… Example:

    from sklearn.linear_model import LinearRegression
    model = LinearRegression()
    
    

    🌐 3. Web Development

    LibraryUse
    FlaskSimple web applications
    DjangoBig web applications (full framework)

    βœ… Flask Example:

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return "Hello, World!"
    
    

    πŸ§ͺ 4. Testing & Automation

    LibraryUse
    pytestTest your code
    unittestBuilt-in testing tool
    SeleniumAutomate browsers (web testing)

    βœ… Selenium Example:

    from selenium import webdriver
    driver = webdriver.Chrome()
    driver.get("https://google.com")
    
    

    🧰 5. Utilities & Tools

    LibraryUse
    osWork with files/folders in system
    datetimeWork with dates and time
    randomGenerate random numbers
    reWork with regular expressions

    βœ… Example:

    import os
    print(os.getcwd())  # Show current folder
    
    

    πŸ“š 6. Web Scraping

    LibraryUse
    BeautifulSoupGet data from web pages
    requestsSend HTTP requests
    lxmlParse HTML and XML data

    βœ… Example:

    import requests
    from bs4 import BeautifulSoup
    
    r = requests.get("https://example.com")
    soup = BeautifulSoup(r.text, 'html.parser')
    print(soup.title.text)
    
    

    πŸ–ΌοΈ 7. Image and Media

    LibraryUse
    PillowWork with images
    OpenCVImage processing & computer vision

    βœ… Example:

    from PIL import Image
    img = Image.open("image.jpg")
    img.show()
    
    

    🐍 8. GUI (Desktop Apps)

    LibraryUse
    TkinterBuilt-in GUI (create windows)
    PyQtPowerful GUI applications

    βœ… Tkinter Example:

    import tkinter as tk
    win = tk.Tk()
    win.title("Hello App")
    win.mainloop()
    
    

    🧾 Summary Table

    CategoryLibraries
    Data & MathNumPy, Pandas, Matplotlib
    Machine Learningscikit-learn, TensorFlow, Keras
    Web DevelopmentFlask, Django
    AutomationSelenium, pytest, unittest
    Web ScrapingBeautifulSoup, requests
    GUI DevelopmentTkinter, PyQt
    Image ProcessingPillow, OpenCV

    🧠 Final Tip:

    Learn the library you need for your project.
    You don’t have to learn all at once.


    πŸ“£ Coming Up Next:

    ➑️ How to Create Your Own Python Package (Step-by-Step)


  • Difference Between Abstraction and Encapsulation in Python | Simple Words + Examples


    πŸ”Έ Let’s Understand Both:

    FeatureAbstractionEncapsulation
    MeaningHide how it works, show only what it doesHide data and code in one unit
    FocusOn functionalityOn security and data protection
    Used withAbstract Classes, @abstractmethodPrivate variables, methods, classes
    Real-life ideaTV remote – You don’t know how it works insideMedicine capsule – It hides the inner parts

    πŸ”Ή Example of Abstraction:

    from abc import ABC, abstractmethod
    
    class Payment(ABC):
        @abstractmethod
        def pay(self):
            pass
    
    class UPI(Payment):
        def pay(self):
            print("Payment using UPI")
    
    p = UPI()
    p.pay()
    
    

    βœ… The user only knows they are using UPI. How it works inside is hidden.


    πŸ”Ή Example of Encapsulation:

    class Student:
        def __init__(self):
            self.__marks = 0  # private variable
    
        def set_marks(self, m):
            self.__marks = m
    
        def get_marks(self):
            return self.__marks
    
    s = Student()
    s.set_marks(95)
    print(s.get_marks())  # Output: 95
    
    

    βœ… The marks are protected. We use methods to access them.


    🧾 Summary Table

    Key PointAbstractionEncapsulation
    PurposeHides unnecessary detailsHides sensitive data
    How it’s doneWith abstract classes & methodsUsing private variables & methods
    Access control?NoYes (__private)
    Real-life comparisonTV remoteMedicine capsule

    🧠 Easy Tip to Remember

    • πŸ” Abstraction = “Don’t show how it works” (Focus on What)
    • πŸ”’ Encapsulation = “Don’t let others touch my data” (Focus on How safe)

    🎯 Recap in 2 Lines:

    • Abstraction hides logic
    • Encapsulation hides data

    Both help you write clean and secure code.


  • Abstraction in Python | Hiding the Complex, Showing Only the Needed



    πŸ”Ή What is Abstraction?

    Abstraction means:

    Hiding the complex details and showing only the important parts.

    It helps us to:

    • Focus on what an object does
    • Not worry about how it does it

    πŸ”Έ Real-Life Example:

    Think about a TV remote:

    • You press the power button to turn on the TV.
    • You don’t need to know how electricity flows inside.

    🟒 This is abstraction β€” showing only the button (interface), hiding the working inside.


    πŸ”Ή Abstraction in Python

    We use:

    • Abstract Base Class (ABC)
    • The abc module

    πŸ”Ή How to Use Abstraction in Python

    1. Import ABC and abstractmethod
    2. Create a class that inherits from ABC
    3. Use @abstractmethod to define abstract methods
    4. Subclass must override these methods

    πŸ”Ή Example:

    from abc import ABC, abstractmethod
    
    class Animal(ABC):  # Abstract class
        @abstractmethod
        def sound(self):  # Abstract method
            pass
    
    class Dog(Animal):
        def sound(self):
            print("Dog barks")
    
    class Cat(Animal):
        def sound(self):
            print("Cat meows")
    
    d = Dog()
    c = Cat()
    d.sound()
    c.sound()
    
    

    🟒 Output:

    Dog barks
    Cat meows
    
    

    πŸ”Ή Key Rules of Abstraction:

    • You cannot create an object of abstract class.
    • Child class must implement (override) abstract methods.
    • Abstract class can also have normal methods.

    πŸ”Ή Abstract Class with Normal Method

    from abc import ABC, abstractmethod
    
    class Vehicle(ABC):
        @abstractmethod
        def start(self):
            pass
    
        def fuel_type(self):
            print("Fuel type is petrol")
    
    class Car(Vehicle):
        def start(self):
            print("Car is starting...")
    
    c = Car()
    c.start()
    c.fuel_type()
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create an abstract class Shape with abstract method area(). Implement it in Rectangle and Circle.

    βœ… Answer:

    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
    
    class Rectangle(Shape):
        def area(self):
            print("Area = length Γ— width")
    
    class Circle(Shape):
        def area(self):
            print("Area = Ο€ Γ— radiusΒ²")
    
    r = Rectangle()
    c = Circle()
    r.area()
    c.area()
    
    

    ❓ Q2: Make an abstract class Device with turn_on() and turn_off() methods.

    βœ… Answer:

    from abc import ABC, abstractmethod
    
    class Device(ABC):
        @abstractmethod
        def turn_on(self):
            pass
    
        @abstractmethod
        def turn_off(self):
            pass
    
    class Laptop(Device):
        def turn_on(self):
            print("Laptop is turning on")
    
        def turn_off(self):
            print("Laptop is shutting down")
    
    l = Laptop()
    l.turn_on()
    l.turn_off()
    
    

    🧾 Summary Table

    TermMeaning
    AbstractionHiding how things work, showing only what’s needed
    Abstract ClassA class with abstract methods
    Abstract MethodMethod with no body (empty function)
    @abstractmethodUsed to create abstract methods

    🎯 Quick Recap

    • Abstraction = Hiding details, showing only the essentials.
    • Use abc module, ABC, and @abstractmethod.
    • Helps write clean, structured, and safe code.

    πŸ“£ Coming Up Next:

    ➑️ Difference Between Abstraction and Encapsulation in Python (Simple Words)


  • Method Overriding in Python | Easy Explanation with Examples



    πŸ”Ή What is Method Overriding?

    Method Overriding means:

    A child class (subclass) writes its own version of a method that already exists in the parent class (superclass).

    • It helps the child class change or improve the behavior of a parent method.
    • The method name must be same in both classes.

    πŸ”Έ Real-Life Example:

    Imagine a general printer prints in black & white. But a color printer overrides that function and prints in color.


    πŸ”Ή Basic Example of Method Overriding:

    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):
        def speak(self):  # Overriding the parent's method
            print("Dog barks")
    
    d = Dog()
    d.speak()  # Output: Dog barks
    
    

    βœ… Dog class has its own version of the speak() method.


    πŸ”Ή Why Use Method Overriding?

    βœ… To customize behavior
    βœ… To add extra work in child class
    βœ… To make code flexible and clean


    πŸ”Ή Calling Parent Method Using super()

    Sometimes we want to call the original (parent) method also:

    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):
        def speak(self):
            super().speak()  # Call parent method
            print("Dog barks")
    
    d = Dog()
    d.speak()
    
    

    🟒 Output:

    Animal speaks
    Dog barks
    
    

    πŸ”Ή Another Example: Bank Account

    class Account:
        def show_balance(self):
            print("Balance is $1000")
    
    class SavingsAccount(Account):
        def show_balance(self):
            print("Savings balance is $1500")
    
    a = SavingsAccount()
    a.show_balance()
    
    

    πŸ“ Practice Questions with Answers

    ❓ Q1: Create a class Shape with a method draw(). Override it in Circle and Square.

    βœ… Answer:

    class Shape:
        def draw(self):
            print("Drawing a shape")
    
    class Circle(Shape):
        def draw(self):
            print("Drawing a circle")
    
    class Square(Shape):
        def draw(self):
            print("Drawing a square")
    
    c = Circle()
    s = Square()
    
    c.draw()
    s.draw()
    
    

    ❓ Q2: Create a class Employee with method work(). Override it in Manager and Developer.

    βœ… Answer:

    class Employee:
        def work(self):
            print("Employee works")
    
    class Manager(Employee):
        def work(self):
            print("Manager manages the team")
    
    class Developer(Employee):
        def work(self):
            print("Developer writes code")
    
    m = Manager()
    d = Developer()
    
    m.work()
    d.work()
    
    

    🧾 Summary

    TermMeaning
    OverridingChild class redefines parent method
    Method NameMust be the same in both classes
    Use of super()To call the parent class method from child

    🎯 Quick Recap

    • Method Overriding = Changing a parent method in the child class.
    • Useful when child class needs a different behavior.
    • super() helps to use parent’s method with the new one.