Python installation in Windows OS:

  • Open Google Chrome or any other web browser and search for Python. 1 1 e1737919354722
  • Visit the official Python website at python.org.2 1 e1737960267614
  • Navigate to the Downloads section and select the latest stable release for Windows.Choose the appropriate installer based on your system architecture:
  • For 64-bit systems: “Windows installer (64-bit)”
  • For 32-bit systems: “Windows installer (32-bit)”3 1 e1737960433455
  • Locate the downloaded installer file (e.g., python-3.x.x-amd64.exe) and double-click to run it.4 1
  • Check the box labeled “Add Python to PATH” to ensure you can run Python from the command line.Click on “Install Now” to proceed with the default installation.5 1
  • In the “Optional Features” section, you can select additional components like:
    • Documentation
    • pip (Python package installer)
    • tcl/tk and IDLE (Python’s Integrated Development and Learning Environment)
    • Python test suite
    • py launcher6 1
  • Click “Next” and in the “Advanced Options” section, you can:
    • Choose the installation location
    • Add Python to environment variables
    • Install for all users7 1
  • After selecting the desired options, click “Install” to begin the installation.8 19 1 e1737960510964
  • Verify the Installation:
    • Open the Command Prompt:
    • Press Win + R, type cmd, and press Enter.
  • pip --version run in command prompt and python --version.14 1 e1737961172208

Python Installation for MacOS:

  • Check System Requirements: Ensure your macOS version is 10.9 or later.
  • Go To google chrome and search python

seach on google

  • Visit Python’s Official Website: Open https://www.python.org and navigate to the “Downloads” section. The website will auto-detect the appropriate version for macOS.irst page for python
  • Wait until the installation take place & navigate in download bar. 4 e1737897166784
  • Open the .pkg file.5 e1737900198771
  • Click to continue.6 e1737900590266
  • Again click on continue.7 e1737900689287
  • Now click on Agree.8
  • Now complete the processing and click on Install Button.10 e1737901071202And move the python installer package to bin12 e1737902387634
  • Now close all the tabs and open IDLE python.11 e1737902149333
  • Open IDLE shell and try a hello world Program.14 e1737902564954
  • Simple “Hello World” program.16You can also check version in Terminal by giving the following command to check the version of python.
    python3 –versionScreenshot 2025 01 26 at 11.38.27 PM

    Pycharm Configurations

    PyCharm Installation for Windows OS:

    To install PyCharm on a Windows system, first ensure your computer meets the necessary system requirements, including running Windows 10 64-bit or later and having an active internet connection. Begin by downloading the latest version of PyCharm from the official JetBrains website: here Once the download is complete, run the installer and follow the on-screen instructions to complete the installation process. After installation, launch PyCharm, create a new project, and ensure that the appropriate Python interpreter is selected to start your development work.

    Official pycharm and windows logo in one frame


    PyCharm Installation for MacOS:

    hh

    Python Installation & Configuration

    Python Installation for MacOS:

    To install Python on macOS, ensure your system meets the basic requirements: macOS 10.9 or later with a stable internet connection. Download the latest Python installer from python.org, follow the on-screen instructions, and verify the installation via Terminal. Ensure sufficient storage and admin rights for installation.


    mac os python install


    Python Installation for Windows OS:

    To install Python on Windows, ensure your system runs Windows 7 or later with an internet connection. Download the latest Python installer from python.org, run the installer, and select “Add Python to PATH.” Follow the on-screen instructions and verify the installation through Command Prompt.

    an image with windows logo and python language logo

    Python datetime Module

    Introduction

    Welcome to our comprehensive guide on Python’s datetime module! In the world of programming, handling dates and times is a common requirement.

    Features

    The datetime module in Python boasts a range of features that make it an indispensable tool for working with date and time data:

    • Precise date and time representation.
    • Time zone awareness for handling time differences.
    • Arithmetic operations on dates and times.
    • Formatting and parsing of date and time strings.
    • Support for both Gregorian and Julian calendar systems.
    1. datetime.now() – Current Date and Time:

    Returns the current date and time.

             2. datetime.combine() – Combine Date and Time:

    Combines a date and a time into a single datetime object.

            3. datetime.strptime() – String to Datetime:

    Converts a string to a datetime object based on a specified format.

    Common Format Codes

    CodeMeaning
    %YYear (2025)
    %yYear (25)
    %mMonth (01-12)
    %BMonth (full name)
    %dDay (01-31)
    %AWeekday (full name)
    %HHour (24 hr)
    %IHour (12 hr)
    %MMinute
    %SSecond

            4. datetime.strftime() – Datetime to String:

    Formats a datetime object as a string according to a given format.

            5. timedelta() – Time Interval:

    Represents a duration of time, supporting arithmetic operations with datetime objects.

            6. datetime.date() – Extract Date:

    Extracts the date portion from a datetime object.

            7. datetime.time() – Extract Time:

    Extracts the time portion from a datetime object.

            8. datetime.replace() – Replace Components:

    Creates a new datetime object by replacing specific components.

            9. datetime.weekday() – Weekday Index:

    Returns the index of the weekday (0 for Monday, 6 for Sunday).

           10. datetime.isoweekday() – ISO Weekday:

    Returns the ISO weekday (1 for Monday, 7 for Sunday).

           11. datetime.timestamp() – Unix Timestamp:

    Returns the Unix timestamp (the number of seconds since January 1, 1970).

           12. datetime.astimezone() – Timezone Conversion:

    Converts a datetime object to a different timezone.

           13. datetime.utcoffset() – UTC Offset:

    Returns the UTC offset of a datetime object.

           14. datetime.timedelta.total_seconds() – Total Seconds:

    Returns the total number of seconds in a timedelta object.

           15. datetime.fromtimestamp() – Datetime from Timestamp:

    Creates a datetime object from a Unix timestamp.

    Python sys Module

    The argv list contains command-line arguments passed to the script.

    The path list contains directories where Python searches for modules.

    The version string provides information about the Python interpreter.

    The platform string indicates the operating system platform.

    The getsizeof() function returns the size of an object in bytes.

    The exit() function terminates the program with an optional exit code.

    The maxsize integer represents the maximum size of a list or range.

    The modules dictionary contains information about loaded modules.

    The exc_info() function returns information about the current exception.

    Python Collection Module

    The namedtuple() function creates a new subclass of tuple with named fields, enhancing code clarity.

    The Counter() function creates a dictionary-like object to count occurrences of elements in an iterable.

    The deque() function creates a double-ended queue, useful for fast appends and pops from both ends.

    The defaultdict() function creates dictionaries with default values for missing keys.

    The OrderedDict() function creates dictionaries that remember the order of insertion.

    The ChainMap() function combines multiple dictionaries into a single view.

    Python Exception Handling

    Exception Handling

    Exception Handling is used to manage runtime errors and prevent programs from crashing.

    Exceptions occur when:

    • User enters invalid input
    • File not found
    • Network connection fails
    • Wrong operations (divide by zero)

    Basic Structure


    Basic Example


    Catching Specific Exceptions


    Multiple Except Blocks


    Using else Block

    Runs only when no exception occurs.


    Using finally Block

    Always runs — even if an error occurs.


    Raise an Exception Yourself

    Use raise for rules/validation.


    Custom Exception


    File Handling with Exception


    Multiple Exceptions in One Line


    Catch All Exceptions


    Common Built-in Exceptions

    ExceptionWhen it Occurs
    ZeroDivisionErrorDivide by zero
    ValueErrorWrong data type in conversion
    TypeErrorUnsupported operations between types
    FileNotFoundErrorFile does not exist
    KeyErrorKey not found in dictionary
    IndexErrorIndex out of range
    NameErrorVariable not defined
    ImportErrorModule not found

    Real-Time Examples

    User Input Validation


    Retry File Opening Automatically


    API Request Error Handling (Concept)

    Python Modules

    Python Modules Tutorial

    Introduction

    Python, renowned for its simplicity and versatility, owes a significant part of its power to modules. Modules are an essential concept in Python programming, enabling developers to organize code, enhance reusability, and maintain a clean project structure. In this tutorial, we’ll delve into the world of Python modules, exploring their significance, creation, unique features, and diverse applications.

    Importance of Modules

    Modules serve as building blocks that encapsulate code, variables, and functions, making it easier to manage and scale projects. By grouping related functionalities together, modules facilitate code readability, reduce redundancy, and enable collaborative development. This modular approach enhances the maintainability and extensibility of Python applications.

    Creating a Module

    Creating a module is a straightforward process. To begin, save a collection of related functions and variables in a .py file. This file name becomes the module name. For instance, let’s create a simple module named math_operations:

    				
    					# math_operations.py
    def add(a, b):
        return a + b
    
    def subtract(a, b):
        return a - b
    
    def multiply(a, b):
        return a * b
    
    				
    			

    Features

    Python modules offer a range of features that streamline development and optimize code organization:

    1. Namespace Isolation: Modules create separate namespaces, preventing naming conflicts between variables and functions.
    2. Reusability: Code encapsulated within modules can be easily reused in multiple projects.
    3. Modularity: Modules support a modular architecture, enhancing code separation and maintainability.
    4. Information Hiding: By controlling what is exposed in a module’s interface, you can encapsulate implementation details.
    5. Standard Library: Python’s standard library provides a plethora of pre-built modules, saving time and effort in coding common functionalities.

    Different Python Modules

    1. Math Module: The math module offers a suite of mathematical functions. Let’s calculate the factorial of a number using the math module:
    				
    					import math
    num = 5
    factorial = math.factorial(num)
    print(f"The factorial of {num} is {factorial}")
    
    				
    			
    1. Datetime Module: The datetime module simplifies date and time manipulation. Here’s an example of getting the current date and time:
    				
    					import datetime
    current_datetime = datetime.datetime.now()
    print(f"Current date and time: {current_datetime}")
    
    				
    			
    1. Random Module: The random module facilitates random number generation. Let’s generate a random integer between 1 and 100:
    				
    					import random
    random_number = random.randint(1, 100)
    print(f"Random number: {random_number}")
    
    				
    			
    1. JSON Module: The json module simplifies JSON encoding and decoding. Here, we’ll encode a Python dictionary as a JSON string:
    				
    					import json
    data = {'name': 'John', 'age': 30, 'city': 'New York'}
    json_string = json.dumps(data)
    print(f"JSON representation: {json_string}")
    
    				
    			

    Python OOPS

    Python OOP – Fundamentals

    Object-Oriented Programming (OOP) is a programming style organized around objects instead of functions.
    It helps structure code that is scalable, reusable, and modular.


    Four Pillars of OOP

    Pillar Meaning Example
    Encapsulation Hiding internal details Private variables
    Abstraction Showing only necessary features Interfaces-like behavior
    Inheritance Acquiring properties from parent class Parent → Child
    Polymorphism Same function name, different behavior Method overriding

    Basic Terminology

    Term Meaning
    Class Blueprint/template for an object
    Object Instance created from a class
    Method A function inside a class
    Attribute Variables in a class (properties)
    Constructor Initializes object values (__init__())
    class Person:
        def __init__(self, name, age):
            self.name = name    # Instance attribute
            self.age = age
    
        def greet(self):
            print(f"Hello, my name is {self.name} and I am {self.age} years old.")
    
    p1 = Person("Amit", 25)
    p1.greet()
    

    Description

    • Person is a class (blueprint).
    • p1 is an object/instance of the class.
    • __init__ is a constructor that initializes object attributes when created.
    • self refers to the current object.
    • greet() is an instance method, accessible using the object.

    class Employee:
        company = "Google"  # Class variable (shared by all objects)
    
        def __init__(self, name):
            self.name = name  # Instance variable (unique to each object)
    
    e1 = Employee("Sam")
    e2 = Employee("Riya")
    print(e1.company, e2.company)
    print(e1.name, e2.name)
    

    Description

    • company belongs to the class, so every Employee object uses “Google”.
    • name is an instance variable — each object has a different value.
    • Helps differentiate data shared across objects and unique to each.

    Encapsulation refers to the concept of bundling data and methods that operate on that data into a single unit, i.e., a class. It prevents direct access to data from outside the class and promotes data hiding.

    class BankAccount:
        def __init__(self, balance):
            self.__balance = balance  # Private variable
    
        def get_balance(self):
            return self.__balance  # Getter method
    
        def deposit(self, amount):
            self.__balance += amount  # Setter method
    
    account = BankAccount(1000)
    account.deposit(500)
    print(account.get_balance())
    

    Description

    • The variable __balance is private and cannot be accessed directly using object.
    • Encapsulation protects data from accidental modification.
    • We control access through getter & setter functions.

    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass  # Abstract method (must be implemented)
    
    class Circle(Shape):
        def __init__(self, r):
            self.r = r
    
        def area(self):
            return 3.14 * self.r * self.r
    
    c = Circle(5)
    print(c.area())
    

    Description

    • Shape is an abstract class — cannot be instantiated.
    • Contains an abstract method that forces subclasses to implement it.
    • The Circle must provide its own area method → ensuring a standard structure.

    class Sample:
        def __init__(self):
            print("Constructor executed")
    
        def __del__(self):
            print("Destructor executed")
    
    obj = Sample()
    del obj
    

    Description

    • __init__ runs automatically when the object is created.
    • __del__ runs when the object is destroyed or the program ends.
    • Used for resource management (like closing files, DB connections, etc.)

    1. Class Method
    • In Python, a class method is a type of method that is bound to the class itself rather than to instances of the class.
    • It can access and modify class-level attributes and perform actions related to the class as a whole.
    • Class methods are defined using the @classmethod decorator and take the class itself as the first parameter, conventionally named cls.
    • This makes them different from instance methods, which take the instance itself (self) as the first parameter.
    1. Static Method
    • A static method is a method that is defined within a class but is not bound to the class instance or class-level attributes.
    • It doesn’t receive any implicit reference to the class or its instances as parameters. Static methods are defined using the @staticmethod decorator.
    • Static methods are often used to create utility functions that are logically related to the class but don’t require access to instance-specific or class-level data.
    class Student:
        school = "DAV School"
    
        @staticmethod
        def welcome():
            print("Welcome to the School!")  # No object needed
    
        @classmethod
        def get_school_name(cls):
            return cls.school
    
    Student.welcome()
    print(Student.get_school_name())
    

    Description

    • @staticmethod → Does not access class or object data. Used as helper logic.
    • @classmethod → Access class variables using cls.

    class Car:
        def __init__(self, brand, model, price):
            self.brand = brand
            self.model = model
            self.price = price
    
        def details(self):
            print(f"{self.brand} {self.model} costs ₹{self.price}")
    
    c1 = Car("Toyota", "Fortuner", 3500000)
    c1.details()
    

    Description

    • Represents real-world entities as Python objects.
    • Helps in designing software similar to real systems.