Python Programming: Unit I Comprehensive Study Notes

Python Overview and Architecture

  • Definition & Paradigm: Python is a high-level, interpreted, general-purpose, dynamically typed language supporting procedural, object-oriented, and functional programming paradigms.

  • Origins & Governance: Conceived in 1989 by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands as an ABC-inspired hobby project; named after Monty Python's Flying Circus; van Rossum served as Benevolent Dictator For Life (BDFL) until 2018; current development is overseen by the Python Software Foundation (PSF).

  • Release Timeline:

    • 1991: Python 0.9.0 (first public release).

    • 1994: Python 1.0 (introduced functional tools: lambda, map, filter, reduce).

    • 2000: Python 2.0 (introduced list comprehensions, garbage collection).

    • 2008: Python 3.0 (backward-incompatible language cleanup).

    • 1 January 2020: Python 2 reached end-of-life.

  • Execution Pipeline: Source code compiles into platform-independent bytecode (.pyc), which is executed line-by-line by the Python Virtual Machine (PVM).

  • Major Ecosystem Domains: Web engineering (Django, Flask, FastAPI), data science (NumPy, Pandas, Matplotlib), machine learning (scikit-learn, TensorFlow, PyTorch), web automation (BeautifulSoup, Selenium), desktop GUIs (Tkinter, PyQt), and embedded hardware (MicroPython, Raspberry Pi).

Syntax, Identifiers, and Data Types

  • Identifier Rules: Composed of alphanumeric characters and underscores; must not begin with a digit; special symbols and whitespace are prohibited; case-sensitive with unrestricted length.

  • Styling Conventions (PEP 8): snake_case for variables and functions, CamelCase for classes, UPPER_CASE for constants, leading underscore (_) for internal usage, and double underscores (__dunder__) for system-defined names.

  • Keywords: Python 3.9+ contains 35 reserved words; all are entirely lowercase except True, False, and None (print is a built-in function, not a keyword).

  • Built-in Primitive Data Types:

    • int: Arbitrary-precision whole numbers.

    • float: Double-precision decimal numbers (approximately 15–16 decimal digits of precision).

    • complex: Complex numbers containing real and imaginary components ending with j.

    • bool: Truth values (True, False), implemented as a subclass of int where True == 1 and False == 0.

    • str: Immutable sequences of Unicode characters.

    • NoneType: Represents the absence of a value via singleton None.

  • Mutability Categories: Immutable types include int, float, complex, bool, str, and tuple; mutable collections include list, set, and dict.

  • Falsy Values: Evaluate to False in boolean contexts: 0, 0.0, 0j, "", None, False, and empty containers ([], (), {}, set()); all other expressions evaluate to True.

  • Type Casting: Supports implicit coercion up the hierarchy (bool to int to float to complex) and explicit casting using functions such as int(), float(), str(), bool(), chr(), and ord().

Operators and Precedence

  • Operator Categories:

    • Arithmetic: +, -, *, / (always yields float), // (floor division rounding toward negative infinity), % (modulus), ** (exponentiation).

    • Relational: ==, !=, <, >, <=, >= (support chaining, e.g., 1 < x < 10).

    • Logical: and, or, not (employ short-circuit evaluation returning the terminal operand value).

    • Bitwise: & (AND), | (OR), ^ (XOR), ~ (NOT, defined as −(x+1)-(x + 1)), << (multiply by 2n2^n), >> (floor divide by 2n2^n).

    • Identity & Membership: is / is not (object identity in memory), in / not in (sequence membership).

    • Walrus Operator: := assigns values to variables as part of a larger expression (Python 3.8+).

  • Precedence Hierarchy (Highest to Lowest):

    1. Parentheses: ()

    2. Exponentiation: ** (associates right-to-left)

    3. Unary operators: +x, -x, ~x (right-to-left)

    4. Multiplicative: *, /, //, % (left-to-right)

    5. Additive: +, - (left-to-right)

    6. Bitwise shifts: <<, >> (left-to-right)

    7. Bitwise AND: & (left-to-right)

    8. Bitwise XOR: ^ (left-to-right)

    9. Bitwise OR: | (left-to-right)

    10. Comparisons, identity, membership: ==, !=, <, <=, >, >=, is, is not, in, not in (chained)

    11. Logical NOT: not (right-to-left)

    12. Logical AND: and (left-to-right)

    13. Logical OR: or (left-to-right)

    14. Conditional expression: x if cond else y (right-to-left)

    15. Anonymous function: lambda

Program Structure and Input/Output

  • File Structure: Arranged sequentially into documentation/docstrings, module imports, global constants, functions/classes, and driver logic enclosed within if __name__ == "__main__":.

  • Syntax Rules: Code blocks are structured using consistent 4-space indentation; semicolons (;) permit inline statement sequences; backslashes (\) or unclosed brackets permit explicit line continuations.

  • Console Output: Handled by print(*objects, sep=' ', end=' ', file=sys.stdout).

  • Console Input: Handled by input(prompt), which reads console input strictly as a str and requires explicit casting for arithmetic.

Strings and String Processing

  • String Structure: Immutable Unicode sequence indexed via zero-based indexing from the left (00 to n−1n - 1) and negative indexing from the right (−1-1 to −n-n).

  • Slicing Syntax: s[start:stop:step] extracts characters from start up to, but excluding, stop; omitting fields defaults to 0, length of string, and step 1; negative step reverses traversal (s[::-1] reverses the entire string).

  • Common Methods:

    • Case Modification: upper(), lower(), capitalize(), title(), swapcase().

    • Searching & Counting: find() (returns −1-1 if absent), index() (raises ValueError if absent), count(), startswith(), endswith().

    • Transformation: strip(), lstrip(), rstrip(), replace(old, new), zfill(width).

    • Classification: isalpha(), isdigit(), isalnum(), isspace(), isupper(), islower(), istitle().

    • Splitting & Joining: split(sep) generates a list; partition(sep) produces a 3-tuple (before, sep, after); sep.join(iterable) concatenates string elements.

  • String Formatting Mechanisms:

    • % Formatter: C-style printf format specifiers (e.g., "%s %d" % (name, age)).

    • str.format(): Positional and keyword substitution using curly braces (e.g., "{:.2f}".format(pi)).

    • f-strings: Literal string interpolation prefixed with f (e.g., f"{name} is {age}"), supported in Python 3.6+.

Control Flow Statements

  • Conditionals: Includes if, if-else, if-elif-else ladders, and the ternary conditional assignment syntax: value_if_true if condition else value_if_false.

  • Iterative Loops:

    • while: Indefinite, condition-driven iteration that terminates when its test predicate evaluates to False.

    • for: Definite, sequence-driven traversal over an iterable or generated integer sequences via range([start], stop, [step]).

  • Loop Else Construct: Loops accept an optional else block that executes exclusively when the loop terminates naturally without triggering a break statement.

  • Jump Statements:

    • break: Terminates and exits the innermost loop structure immediately.

    • continue: Aborts the remainder of the current iteration and jumps directly to the next loop cycle.

    • pass: Null statement functioning as a syntactical placeholder for empty blocks.

    • sys.exit(): Terminates running program execution by raising a SystemExit exception.

Core Exam Implementations

  • Factorial: Iterative product accumulator fact *= i running over range 1 to n.

  • Fibonacci Series: Simultaneous tuple assignment a, b = b, a + b over n iterations starting from 0, 1.

  • Palindrome Check: Slicing comparison s == s[::-1] on input strings.

  • Digit Reversal & Summation: Extract the lowest digit via n % 10 and reduce using integer floor division n //= 10.

  • Prime Verification: Loop over candidate factors 2 to num - 1; trigger break if num % i == 0, concluding via the loop's else clause to certify primality.