PyNoob Python Documentation

website·Indexed 29 days ago

https://pynoob.vercel.app/docs

A comprehensive guide for learning Python, covering basics, data structures, object-oriented programming (OOP), error handling, and file handling. Includes advanced topics such as decorators, dunder methods, async/await, database integration with SQLite, and the use of .env files.

Tokens
17.4K
Snippets
107
Records
121
Agent score
72%

What's inside PyNoob

  1. Overview of Python Database APIs (DB-API)

    Python uses the Database API (DB-API) specification to provide a standardized interface for interacting with different database management systems (DBMS). This allows developers to write portable code that can work across different database drivers with minimal changes. Common drivers include sqlite3 (built-in), psycopg2 (PostgreSQL), mysql.connector (MySQL), pymongo (MongoDB), and pyodbc (ODBC-compliant databases).
  2. Understand Python syntax and execution

    Python uses whitespace indentation to define code blocks instead of curly braces. Programs are written in plain text files with the .py extension and can be executed via the command line or an IDE (e.g., PyCharm, VS Code, Spyder).
  3. Understand asynchronous programming in Python

    Asynchronous programming allows a program to pause a specific task and execute other operations while waiting for a third-party service (like a database or API) to respond. This prevents the entire application from freezing during long-running operations. In Python, this is implemented using the async and await keywords. A function marked as async can use await to signal that Python can perform other tasks while that specific operation completes.
    import discord
    
    async def ping(ctx):
        await ctx.send("Pong!")
  4. Understand the difference between Syntax Errors and Exceptions in Python

    Python errors are categorized into two main types:

    1. Syntax Errors: Occur when code violates language rules (e.g., missing colons, incorrect indentation). These are caught during the parsing phase before execution. The interpreter raises a SyntaxError.
    2. Exceptions: Occur during runtime when an error condition arises that the interpreter cannot handle automatically (e.g., ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError).
  5. Understand and override Python dunder methods

    Double-underscore (dunder) methods are special methods in Python classes that are invoked implicitly by the interpreter. Every new class inherits default dunder methods from the object base class, but these can be overridden to customize behavior. For example, __init__ is the constructor called during instantiation, and __add__ is called when using the + operator.
  6. Perform common file system operations

    Python provides the os and shutil modules for manipulating files on the disk, including renaming, moving, deleting, and checking for existence.
    import os
    import shutil
    import os.path
    
    # Rename a file
    os.rename("old_name.txt", "new_name.txt")
    
    # Move a file
    shutil.move("file.txt", "/path/to/new/location/")
    
    # Delete a file
    os.remove("file.txt")
    
    # Check if a file exists
    if os.path.exists("file.txt"):
        print("Exists")
  7. Install and connect to ODBC databases using pyodbc

    The pyodbc module provides a DB-API 2.0 compliant interface for ODBC-compliant databases (e.g., MS SQL Server, Oracle). It requires a corresponding ODBC driver installed on the host system. Use pyodbc.connect() with a connection string specifying the driver, server, database, and credentials.
    pip install pyodbc
    import pyodbc
    
    # Example connection string for MS SQL Server
    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=myserver.mydomain.com;DATABASE=mydatabase;UID=myuser;PWD=mypassword')
    cursor = conn.cursor()
  8. Install Python on Windows

    To set up Python on Windows:

    1. Download the latest installer from the official Python website.
    2. Run the installer and ensure the 'Add Python to PATH' option is selected to enable running Python from any command prompt directory.
    3. Verify the installation by running python --version in the command prompt (CMD).
    python --version
  9. Close PostgreSQL connections

    Always close the database connection using conn.close() after finishing operations to release system resources such as network sockets and memory buffers, and to ensure pending transactions are handled.
    # Close the connection
    conn.close()
  10. Read data from files in Python

    Python provides multiple ways to read file content depending on the required format and memory constraints:

    • read(): Returns the entire file as a single string. Optionally takes an integer argument to read a specific number of characters/bytes.
    • readline(): Reads a single line as a string.
    • readlines(): Reads all lines and returns them as a list of strings.
    • for loop: Iterating directly over the file object is the most memory-efficient method as it reads one line at a time.
    with open('file.txt', 'r') as f:
        # Read entire file
        content = f.read()
        
        # Read first 10 characters
        chunk = f.read(10)
    
    with open('file.txt', 'r') as f:
        # Read one line
        line = f.readline()
    
    with open('file.txt', 'r') as f:
        # Read all lines into a list
        lines = f.readlines()
    
    with open('file.txt', 'r') as f:
        # Memory-efficient iteration
        for line in f:
            print(line.strip())
  11. Implement Encapsulation using access modifiers

    Encapsulation bundles data and methods into a class and restricts direct access to internal state. Python uses naming conventions to signal access levels:

    • Public: Default. Accessible from anywhere.
    • Protected: Prefixed with a single underscore _. A hint that it should be treated as private, though still technically accessible.
    • Private: Prefixed with a double underscore __. Triggers name mangling to prevent accidental access from outside the class.
    class BankAccount:
        def __init__(self, name, balance):
            self.name = name          # Public
            self.__balance = balance  # Private
    
        def deposit(self, amount):
            self.__balance += amount
    
        def get_balance(self):
            return self.__balance
  12. Implement Multilevel Inheritance in Python

    Multilevel inheritance creates a chain of inheritance where a subclass inherits from a superclass, and another subclass inherits from that first subclass, forming a hierarchical structure.
    class Animal:
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):  # Dog inherits from Animal
        def bark(self):
            print("Dog barks")
    
    class Labrador(Dog):  # Labrador inherits from Dog
        def play(self):
            print("Labrador plays fetch")
    
    labrador = Labrador()
    labrador.speak()  # Output: Animal speaks
    labrador.bark()   # Output: Dog barks
    labrador.play()   # Output: Labrador plays fetch