Python Programming Fundamentals & Math Applications

Setup & Core Fundamentals

  • Environment Setup:

    • Running Python code requires installing the Python interpreter.

    • On Windows operating systems, ensure the option "Add Python executable to PATH" is enabled during setup.

    • Recommended Integrated Development Environments (IDEs) include PyCharm Community Edition and VS Code.

    • Python script files use the .py file extension.

  • Printing & Comments:

    • Printing: The print() function outputs text to the console using either double quotes ("...") or single quotes ('...').

    • Comments: Code comments start with a hashtag/pound sign (#) and are ignored by the Python interpreter during execution.

  • Basic Data Types:

    • String (str): Represents a sequence of characters enclosed in single or double quotes.

    • Integer (int): Represents whole numbers (positive, negative, or zero) used in mathematical arithmetic.

    • Floating-Point (float): Represents real numbers containing a decimal portion.

    • Boolean (bool): Represents a binary truth state, holding either True or False.

  • Formatted Strings (f-strings):

    • Prefixing a string literal with f (or F) enables variable interpolation and expression evaluation directly within curly braces {variable}.

  • Type Casting:

    • Converts a variable or value from one data type to another using constructor functions: str(), int(), float(), or bool().

    • Truth value evaluation when casting to boolean:

    • Casting a non-empty string to bool returns True.

    • Casting an empty string ("") to bool returns False.

  • User Input:

    • The input("Prompt") function displays an optional prompt string to the user and captures their keyboard response as a str.

    • User inputs intended for numerical calculations must be explicitly cast to an int or float.

Operators, Math & String Manipulation

  • Arithmetic & Augmented Assignment Operators:

    • Standard Arithmetic Operators:

    • Addition (+): Sums two operands.

    • Subtraction (-): Subtracts the second operand from the first.

    • Multiplication (*): Multiplies two operands.

    • Division (/): Divides the first operand by the second, returning a floating-point result.

    • Exponentiation (**): Raises the base operand to the power of the exponent operand.

    • Modulus (%): Divides the first operand by the second and returns the division remainder.

    • Augmented Assignment Operators:

    • Perform an arithmetic operation and reassign the resulting value back to the variable in a single atomic step: +=, -=, *=, /=, **=.

  • Math Functions & Math Module:

    • Built-in Math Functions:

    • round(): Rounds a number to a specified number of digits or nearest integer.

    • abs(): Returns the absolute value of a number.

    • pow(): Raises a number to a specified power.

    • max(): Returns the largest item among arguments or iterable.

    • min(): Returns the smallest item among arguments or iterable.

    • The Math Module (import math):

    • Provides mathematical constants: math.pi (pi: 3.14159...3.14159...) and math.e (Euler's number: 2.71828...2.71828...).

    • Functions provided:

      • math.sqrt(): Computes the square root of a number.

      • math.ceil(): Rounds a number upwards to its nearest integer.

      • math.floor(): Rounds a number downwards to its nearest integer.

  • String Indexing & Slicing:

    • Elements in a sequence/string are accessed using bracket syntax [start:end:step].

    • Indexing rules:

    • start: The starting index (inclusive).

    • end: The ending index (exclusive).

    • step: Specifies the increment step size between elements.

    • Negative indexing: Index -1 targets the last character of the string, -2 targets the second to last character, and so forth.

    • Setting step to -1 (e.g., [::-1]) reverses the string.

  • String Methods:

    • len(): Returns the total character count / length of the string.

    • find(): Returns the index of the first occurrence of a substring (or -1 if not found).

    • rfind(): Returns the index of the last occurrence of a substring.

    • capitalize(): Capitalizes the first character of the string and lowercases the rest.

    • upper(): Converts all characters in the string to uppercase.

    • lower(): Converts all characters in the string to lowercase.

    • isdigit(): Returns True if all characters in the string are digits.

    • isalpha(): Returns True if all characters in the string are alphabetic.

    • count(): Counts non-overlapping occurrences of a substring within the string.

    • replace(): Replaces occurrences of a specified substring with a replacement string.

  • Format Specifiers:

    • Format specifiers are applied inside f-strings using the syntax f"{value:flags}" to control output visual formatting:

    • Decimal Precision: :.2f formats a float to two decimal places.

    • Field Width & Zero Padding: :10 sets a minimum field width of 10 characters; :010 pads the number with leading zeros to fill a width of 10.

    • Alignment Options:

      • <: Left-aligns text within the allocated field width.

      • >: Right-aligns text within the allocated field width.

      • ^: Centers text within the allocated field width.

    • Thousands Separator: , adds comma separators for thousands groupings (e.g., 1,000,000).

Control Flow & Loops

  • Conditional Statements:

    • Code execution is directed conditionally using if, elif (else if), and else blocks based on comparison operations:

    • Equal to (==)

    • Not equal to (!=)

    • Less than (<)

    • Greater than (>)

    • Less than or equal to (<=)

    • Greater than or equal to (>=)

    • Python relies on strict code block indentation to define scope under conditional branches.

  • Logical Operators:

    • or: Evaluates to True if at least one of the conditions is true.

    • and: Evaluates to True only if all evaluated conditions are true.

    • not: Inverts a boolean condition (True becomes False, and vice versa).

  • Conditional Expressions (Ternary Operator):

    • Provides a concise, one-line syntax for evaluating conditions: X if condition else Y.

    • Evaluates to X if condition is True; otherwise evaluates to Y.

  • Match-Case Statements:

    • Provides a multi-way branch conditional alternative to complex elif chains.

    • Syntax pattern:

    • match value:

    • case pattern:

    • Uses case _: as a catch-all wildcard default pattern.

  • Loops & Iteration:

    • While Loop: Repeatedly executes a block of code as long as its condition remains True.

    • Infinite loops created via while True: can be safely exited using a conditional break statement.

    • For Loop: Iterates a deterministic number of times over a sequence or specified range generator range(start, stop, step).

    • The reversed() function iterates over a sequence in reverse order.

    • Loop Control Statements:

    • continue: Immediately skips the remaining statements in the current iteration and jumps to the next loop iteration.

    • break: Terminates the loop execution entirely and transfers control to the statement following the loop.

    • Nested Loops: An inner loop placed completely inside an outer loop body. Commonly used for processing multidimensional data structures or coordinate grids.

Data Structures & Collections

  • Core Collection Types:

Data Structures Comparison Table Header
  • List:

    • Syntax: [...]

    • Ordered: Yes

    • Changeable (Mutable): Yes

    • Duplicates Allowed: Yes

    • Key Characteristics & Use Cases: General-purpose ordered sequence. Supported methods include append(), remove(), insert(), sort(), reverse(), and clear().

  • Set:

    • Syntax: {...}

    • Ordered: No

    • Changeable (Mutable): No (elements themselves are immutable)

    • Duplicates Allowed: No

    • Key Characteristics & Use Cases: Optimized for high-speed lookup and unique element tracking. Elements can be dynamically added via add() or removed via remove() and pop().

  • Tuple:

    • Syntax: (...)

    • Ordered: Yes

    • Changeable (Mutable): No

    • Duplicates Allowed: Yes

    • Key Characteristics & Use Cases: Provides faster execution performance and memory efficiency compared to lists for fixed, immutable sequence data.

  • Dictionary:

    • Syntax: {k: v}

    • Ordered: Yes

    • Changeable (Mutable): Yes

    • Duplicates Allowed: No (requires unique keys)

    • Key Characteristics & Use Cases: Stores associative key-value mappings. Supported methods include get(), update(), pop(), keys(), values(), and items().

    • 2D Collections:

  • Multidimensional structures constructed by nesting collections within collections (e.g., lists of lists or tuples of tuples).

  • Accessed using matrix indexing notation: [row][column].

    • Membership Operators:

  • in: Evaluates to True if a value or variable is found within a target collection or sequence.

  • not in: Evaluates to True if a value or variable is absent from a target collection or sequence.

    • List Comprehensions:

  • Offers a compact, single-line syntax for constructing new lists from existing iterables:

    • Syntax: [expression for value in iterable if condition]

Functions, Scope & Modules

  • Functions & Return Statements:

    • Functions are defined using the def keyword: def function_name(parameters):.

    • Invoked by placing arguments inside parentheses after the function identifier.

    • The return statement exits a function and sends a computed result back to the caller.

  • Argument Types:

    • Default Arguments: Assign default fallback values to parameters if arguments are omitted during function call. Parameters with default values must be placed after non-default positional parameters.

    • Keyword Arguments: Arguments explicitly preceded by parameter names (key=value), allowing arguments to be passed out of order. Keyword arguments must follow positional arguments.

    • Arbitrary Arguments (*args & **kwargs):

    • *args: The single asterisk unpacking operator packs an arbitrary number of positional arguments into a tuple.

    • **kwargs: The double asterisk unpacking operator packs an arbitrary number of keyword arguments into a dictionary.

  • Variable Scope & LEGB Rule:

    • Determines the visibility and resolution order of variable names across standard namespaces.

    • Python searches for variables in the following sequence (LEGB):

    1. Local: Defined inside the current function/method body.

    2. Enclosed: Defined in enclosing/nested function scopes.

    3. Global: Defined at the top level of the module/script file.

    4. Built-in: Predefined identifiers within standard Python runtime modules.

  • Modules & Execution Check:

    • Modules are external Python script files ending in .py included into a script using import module_name.

    • Main Execution Check (if __name__ == '__main__':):

    • Determines whether the script is being executed directly as the primary program or imported as a module into another file.

Object-Oriented Programming (OOP)

  • Classes & Objects:

    • Objects: Data containers that bundle related attributes (variables holding state) and methods (functions defining behavior).

    • Classes: Serve as templates or blueprints for instantiating object instances.

    • __init__ Method: Special constructor method automatically invoked to initialize object attributes upon creation.

  • Class vs. Instance Variables:

    • Instance Variables: Declared inside the __init__ method using self. prefix. Unique to each individual object instance.

    • Class Variables: Declared directly within the class body outside __init__. Shared across all instantiated objects of that class.

  • Inheritance:

    • Enables child subclasses to inherit attributes and methods from parent superclasses: class Child(Parent):.

    • Multiple Inheritance: A subclass inheriting features from more than one parent class (e.g., class Fish(Prey, Predator):).

    • Multi-level Inheritance: A hierarchical chain where a child class inherits from a parent class, which in turn inherits from a grandparent class.

  • The super() Function:

    • Provides direct access to methods and constructors of a parent class (e.g., super().__init__(...)).

  • Polymorphism & Duck Typing:

    • Polymorphism: Allows objects of different classes to be treated through a unified interface via inheritance or abstract base classes (from abc import ABC, abstractmethod).

    • Duck Typing: Dynamic typing concept where object suitability is determined by the presence of specific methods and properties rather than explicit class inheritance ("if it walks like a duck and quacks like a duck…").

  • Static Methods vs. Class Methods:

    • Static Methods (@staticmethod): Utility methods bound to a class that do not access or modify instance state (self) or class state (cls).

    • Class Methods (@classmethod): Methods that accept cls as their first parameter, enabling access and modification of class-level state.

  • Magic (Dunder) Methods:

    • Special methods delimited by double underscores that override standard built-in operators and behaviors.

    • Common dunder methods: __str__, __eq__, __lt__, __gt__, __add__, __contains__, __getitem__.

  • Property Decorator (@property):

    • Wraps private attributes with custom getter, setter, and deleter access methods:

    • @property: Defines the getter method.

    • @attribute.setter: Defines the setter method.

    • @attribute.deleter: Defines the deleter method.

  • Decorators:

    • Higher-order functions that take another function as an argument and extend or modify its behavior without altering its source code (@decorator_name).

    • Implemented using nested wrapper functions that handle parameters via *args and **kwargs.

File Handling, Exceptions & Advanced Topics

  • Exception Handling:

    • Error-prone code is enclosed inside a try: block.

    • Exceptions are intercepted and handled using except SpecificError: blocks.

    • An optional finally: block contains cleanup code that executes unconditionally, regardless of whether an exception occurred.

  • File Operations:

    • File & Path Detection: The os module (import os) provides path inspection utilities:

    • os.path.exists(): Checks if a path exists.

    • os.path.isfile(): Checks if a target path is a file.

    • os.path.isdir(): Checks if a target path is a directory.

    • I/O Management:

    • Managed safely using context managers: with open(filepath, mode) as file:, which automatically closes files after execution.

    • File Modes:

      • 'w': Write mode (creates a new file or overwrites existing content).

      • 'a': Append mode (adds data to the end of an existing file).

      • 'r': Read mode (opens file for reading content).

      • 'x': Exclusive creation mode (fails if the file already exists).

    • Data Formats & Operations:

    • Plain Text: Reading via file.read(), writing via file.write().

    • JSON: Handled using json.dump() for serialization and json.load() for deserialization.

    • CSV: Handled using csv.writer() for writing structured tabular data and csv.reader() for reading tabular rows.

  • Dates & Times:

    • The datetime module supplies classes and tools including date, time, and current system timestamp retrieval via datetime.now().

    • Date string formatting is accomplished using strftime().

  • Multithreading:

    • Concurrent execution module (import threading).

    • Spawns concurrent threads using threading.Thread(target=func, args=(...)) to execute I/O-bound tasks in parallel.

    • Call .start() to launch thread execution.

    • Call .join() to block execution until the target thread finishes.

  • API Requests:

    • Supported by the requests HTTP library.

    • Executes GET requests using requests.get(url).

    • Verifies successful response codes (response.status_code == 200).

    • Extracts parsed JSON payloads directly using response.json().

  • PyQt5 GUI Applications:

    • Applications initialize through QApplication(sys.argv) and run inside an event loop via sys.exit(app.exec_()).

    • User Interface Components:

    • Base Windows & Containers: QWidget, QMainWindow.

    • Layout Managers: QVBoxLayout (vertical), QHBoxLayout (horizontal), QGridLayout (grid-based).

    • Standard Widgets: QLabel, QPushButton, QCheckBox, QRadioButton, QLineEdit.

    • Custom widget styling is applied using CSS-like syntax via .setStyleSheet().