PROGRAMMING IN PYTHON - Unit1,2
PROGRAMMING IN PYTHON - Unit1,2
1. Introduction
• Execution Model:
o Python operates via an interpreter (e.g., CPython), which reads source code,
converts it to bytecode, and executes it in the Python Virtual Machine (PVM).
• Language Characteristics:
o Strongly Typed: No automatic type coercion (e.g., adding a string and integer
fails without conversion).
• Significance:
2. Python Basics
• Concept:
• Expressions:
>>> 2 ** 3 → 8 (exponentiation).
• Evaluation Rules:
• Underlying Mechanism:
o The interpreter parses the expression into an Abstract Syntax Tree (AST),
evaluates it, and prints the result.
o Division (/) always returns a float to ensure precision, a deliberate design choice
in Python 3.
• Errors:
• Integer (int):
o Represents whole numbers (e.g., 5, -10, 0) with no size limit in Python 3 (uses
arbitrary-precision arithmetic).
o Theory: Models the mathematical set of integers (ℤ), closed under addition,
subtraction, and multiplication.
>>> 7 % 2 → 1 (remainder).
• Floating-Point (float):
o Represents real numbers with decimal points (e.g., 3.14, -0.001, 2.0).
o Theory: Approximates the real number line (ℝ) using IEEE 754 double-precision
format (64-bit: 1 sign, 11 exponent, 52 mantissa).
• String (str):
o Properties:
• Type Checking:
• String Concatenation:
o Type Constraint: Operands must be strings; >>> "Hi" + 5 → TypeError (use str(5)
to fix).
• String Replication:
o Rules: One operand must be a string, the other an integer; order is irrelevant (3 *
"Hi" works).
o Edge Cases:
>>> "Hi" * 0 → "" (empty string).
o Theory: Time complexity is O(n * m), where n is string length and m is the
multiplier.
• Concept:
o Variables are names bound to objects in memory, acting as labels for data.
• Dynamic Typing:
o No type declaration needed; type is tied to the object, not the variable.
• Naming Rules:
o Case-sensitive: x ≠ X.
• Memory Model:
o Objects are stored in heap memory; variables reference them via pointers.
o Multiple variables can reference the same object: x = 5; y = x (both point to the
same 5).
• Theory:
• Program Structure:
• Comments:
• Indentation:
o Example:
python
x=5
if x > 0:
• Execution Flow:
3. Flow Control
• Definition:
o Boolean type has two values: True and False, representing binary logic states.
• Theory:
o In Python, True and False are singleton objects (unique instances in memory).
• Implicit Conversion:
• Definition:
• List:
• Theory:
o Implements relational logic, defining order (for <, >) or equivalence (==, !=).
• String Comparison:
• Definition:
• Semantics:
• Theory:
A B A and B A or B not A
• Evaluation:
• Concept:
o Combines comparison (<, >, etc.) and Boolean (and, or, not) operators to form
complex conditions.
• Theory:
• Examples:
• Definition:
• Components:
• Types:
• Theory:
• Concept:
• Flow:
• Theory:
o Follows a control flow graph (CFG), where nodes are statements and edges
represent execution paths.
• Example:
python
x=5
print("Start")
if x > 0:
print("Positive")
print("End")
• if Statement:
o Syntax: if condition:
• else Statement:
o Example:
python
if x > 0:
print("Positive")
else:
print("Non-positive")
• elif Statement:
o Example:
python
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
• while Loop:
o Example:
python
x=3
while x > 0:
print(x)
x -= 1 # Prints 3, 2, 1
• for Loop:
o Example:
python
for i in range(3):
print(i) # Prints 0, 1, 2
• break Statement:
o Example:
python
for i in range(5):
if i == 2:
break
print(i) # Prints 0, 1
• continue Statement:
o Example:
python
for i in range(5):
if i % 2 == 0:
continue
print(i) # Prints 1, 3
• Theory:
• Concept:
• Mechanism:
o Loads module into memory, making its contents accessible via dot notation
(e.g., math.sqrt).
o Example:
python
import math
• Variants:
• Theory:
• Concept:
• Syntax:
• Mechanism:
o Example:
python
import sys
x = -1
if x < 0:
print("Won’t run")
• Theory:
• Python Basics: Built on a dynamic, object-oriented model where everything (ints, floats,
strings) is an object, influencing memory and typing behavior.
• Design Choices: Indentation, strong typing, and module system reflect Python’s focus
on clarity and maintainability.
UNIT-II
1. Functions
• Theoretical Foundation:
o The def statement defines a function object, stored in the namespace as a first-
class entity (can be passed, assigned, etc.).
• Parameter Passing:
Immutable objects (e.g., int, str): Changes are local (new object
created).
o Theory: This reflects Python’s object model, where all values are references to
heap-allocated objects.
• Scope Binding:
• Theoretical Basis:
o Functions are mappings from inputs to outputs, with return specifying the
codomain value.
• Semantics:
o return expr terminates execution and yields expr to the caller; without return,
None is implicitly returned.
o Multiple returns (e.g., return a, b) leverage Python’s tuple packing, a lightweight
sequence type.
• Control Flow:
o Early return alters the function’s control flow graph, exiting the current frame and
unwinding the call stack.
• Theory:
o Supports functional purity when side effects are avoided, aligning with
declarative paradigms.
• Theoretical Foundation:
o None is Python’s null object, embodying the unit type in type theory—a type
with a single value signifying “no meaningful result.”
• Semantics:
o Distinct from falsy values (0, "")—has no inherent truth value beyond bool(None)
= False.
• Theory:
• Theoretical Basis:
• Semantics:
o Default parameters (e.g., def f(a=0):) are evaluated once at definition, stored in
f.__defaults__.
• print() Details:
o Signature: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False).
o sep and end control output formatting, reflecting I/O stream manipulation.
• Theory:
• Theoretical Foundation:
• Scope Rules:
o Local Scope: Created on function entry; variables are bound to the function’s
frame (stack-allocated namespace).
o LEGB Rule: Lookup order—Local, Enclosing (for nested functions), Global, Built-
in.
• Shadowing:
o Local assignment creates a new binding, masking outer scopes unless explicitly
overridden.
• Theory:
• Theoretical Basis:
• Semantics:
o global var declares var as a reference to the global variable, not a new local one.
• Implementation:
o Modifies the function’s symbol table at compile time, linking var to the module’s
__dict__.
• Theory:
• Theoretical Foundation:
• Semantics:
• Control Flow:
o An exception unwinds the call stack until caught or terminates the program.
• Theory:
2. Lists
• Theoretical Foundation:
o Contrast with static arrays: Python lists resize via reallocation (amortized O(1)
appends).
• Semantics:
o Indexed via integers (0-based), with negative indices for reverse access.
• Theory:
o Implements a sequence abstract data type (ADT), supporting iteration and
random access.
• Theoretical Basis:
• Operations:
• Implementation:
• Theory:
• Theoretical Foundation:
o Augmented operators (+=, etc.) are syntactic sugar for in-place operations,
optimizing mutable object manipulation.
• Semantics:
• Theory:
o Reduces temporary object creation, leveraging mutability for efficiency (O(1) vs.
O(n) for concatenation).
2.4 Methods
• Theoretical Basis:
• Semantics:
o append(x): O(1) amortized, adds to end.
• Theory:
• Theoretical Foundation:
o Dictionaries implement a hash table, a key data structure for associative arrays
with O(1) average-time operations.
• Semantics:
o Defined as {key: value, ...}, unordered until Python 3.7 (insertion order
preserved).
• Theory:
o Hashing maps keys to indices, resolving collisions via open addressing (Python’s
approach).
• Theoretical Basis:
• Semantics:
• Theory:
• Theoretical Foundation:
o Data structures are abstractions for real-world entities, mapping properties
(keys) to attributes (values) or sequences (lists).
• Semantics:
• Theory:
4. Manipulating Strings
• Theoretical Foundation:
• Semantics:
• Theory:
o Immutability ensures safety (e.g., as hash keys) and predictability, at the cost of
memory for modifications.
• Theoretical Basis:
• Semantics:
• Theory: