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
.pyfile 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 eitherTrueorFalse.
Formatted Strings (f-strings):
Prefixing a string literal with
f(orF) 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(), orbool().Truth value evaluation when casting to boolean:
Casting a non-empty string to
boolreturnsTrue.Casting an empty string (
"") toboolreturnsFalse.
User Input:
The
input("Prompt")function displays an optional prompt string to the user and captures their keyboard response as astr.User inputs intended for numerical calculations must be explicitly cast to an
intorfloat.
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: ) andmath.e(Euler's number: ).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
-1targets the last character of the string,-2targets the second to last character, and so forth.Setting
stepto-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-1if 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(): ReturnsTrueif all characters in the string are digits.isalpha(): ReturnsTrueif 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:
:.2fformats a float to two decimal places.Field Width & Zero Padding:
:10sets a minimum field width of 10 characters;:010pads 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), andelseblocks 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 toTrueif at least one of the conditions is true.and: Evaluates toTrueonly if all evaluated conditions are true.not: Inverts a boolean condition (TruebecomesFalse, and vice versa).
Conditional Expressions (Ternary Operator):
Provides a concise, one-line syntax for evaluating conditions:
X if condition else Y.Evaluates to
XifconditionisTrue; otherwise evaluates toY.
Match-Case Statements:
Provides a multi-way branch conditional alternative to complex
elifchains.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 conditionalbreakstatement.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:

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(), andclear().
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 viaremove()andpop().
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(), anditems().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 toTrueif a value or variable is found within a target collection or sequence.not in: Evaluates toTrueif 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
defkeyword:def function_name(parameters):.Invoked by placing arguments inside parentheses after the function identifier.
The
returnstatement 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):
Local: Defined inside the current function/method body.
Enclosed: Defined in enclosing/nested function scopes.
Global: Defined at the top level of the module/script file.
Built-in: Predefined identifiers within standard Python runtime modules.
Modules & Execution Check:
Modules are external Python script files ending in
.pyincluded into a script usingimport 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 usingself.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 acceptclsas 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
*argsand**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
osmodule (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 viafile.write().JSON: Handled using
json.dump()for serialization andjson.load()for deserialization.CSV: Handled using
csv.writer()for writing structured tabular data andcsv.reader()for reading tabular rows.
Dates & Times:
The
datetimemodule supplies classes and tools includingdate,time, and current system timestamp retrieval viadatetime.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
requestsHTTP 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 viasys.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().