0% found this document useful (0 votes)
9 views20 pages

PROGRAMMING IN PYTHON - Unit1,2

This document provides an introduction to Python programming, covering its definition, execution model, and key characteristics such as dynamic and strong typing. It also outlines basic Python concepts, including data types, expressions, variables, flow control, and program structure, emphasizing the importance of readability and simplicity. Additionally, it discusses various control flow mechanisms, including conditional statements and loops, as well as the use of modules and program termination.

Uploaded by

shubham jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views20 pages

PROGRAMMING IN PYTHON - Unit1,2

This document provides an introduction to Python programming, covering its definition, execution model, and key characteristics such as dynamic and strong typing. It also outlines basic Python concepts, including data types, expressions, variables, flow control, and program structure, emphasizing the importance of readability and simplicity. Additionally, it discusses various control flow mechanisms, including conditional statements and loops, as well as the use of modules and program termination.

Uploaded by

shubham jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT-I: Introduction and Python Basics

1. Introduction

• Definition and Purpose:

o Python is a high-level, interpreted programming language designed for


simplicity, readability, and versatility.

o Introduced by Guido van Rossum in 1991, it emphasizes human-readable code


to reduce the cognitive load of programming.

• 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).

o This interpreted nature allows flexibility and immediate execution, contrasting


with compiled languages requiring a separate compilation step.

• Language Characteristics:

o Dynamically Typed: Types are inferred at runtime, not declared explicitly,


allowing rapid prototyping.

o Strongly Typed: No automatic type coercion (e.g., adding a string and integer
fails without conversion).

o Indentation-Based: Uses whitespace to define code blocks, enforcing a


uniform structure.

• Significance:

o Python’s design bridges theoretical programming concepts (e.g., control


structures) with practical applications, making it ideal for beginners and
professionals alike.

2. Python Basics

2.1 Entering Expressions into the Interactive Shell

• Concept:

o The interactive shell is a command-line environment (REPL: Read-Eval-Print


Loop) where Python code is executed line-by-line.

o Launch: Type python or python3 in a terminal; exit with exit() or Ctrl+D/Z.

• Expressions:

o An expression is a syntactic unit combining values and operators to produce a


result.

o Supported operators: + (addition), - (subtraction), * (multiplication), / (division),


// (floor division), % (modulus), ** (exponentiation).
o Examples:

 >>> 2 + 3 → 5 (integer result).

 >>> 5 / 2 → 2.5 (float result).

 >>> 2 ** 3 → 8 (exponentiation).

• Evaluation Rules:

o Follows PEMDAS: Parentheses, Exponents, Multiplication/Division,


Addition/Subtraction.

 >>> 2 + 3 * 4 → 14 (multiplication first).

 >>> (2 + 3) * 4 → 20 (parentheses override).

• 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:

o ZeroDivisionError: >>> 5 / 0 (undefined mathematically).

o SyntaxError: >>> 5 + (incomplete input).

2.2 The Integer, Floating-Point, and String Data Types

• 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.

o Operations: Arithmetic operators apply; division (/) yields floats, // preserves


integers.

 >>> 7 // 2 → 3 (floor division).

 >>> 7 % 2 → 1 (remainder).

o Implementation: Stored as objects with dynamic memory allocation.

• 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).

o Precision: Limited to ~15-17 decimal digits; binary representation causes


rounding errors (e.g., 0.1 + 0.2 ≈ 0.30000000000000004).
o Operations: All arithmetic operators apply, always returning floats.

 >>> 1.5 * 2 → 3.0.

• String (str):

o A sequence of Unicode characters enclosed in single (') or double (") quotes.

o Theory: Represents textual data as an ordered, immutable collection of code


points.

o Properties:

 Immutable: Cannot modify individual characters (e.g., s[0] = 'x' fails).

 Indexing: 0-based; >>> "Hello"[1] → "e".

 Slicing: >>> "Hello"[1:4] → "ell".

o Escape Sequences: \n (newline), \t (tab), \' (literal quote).

 >>> "Hi\nThere" → prints on two lines.

• Type Checking:

o >>> type(5) → <class 'int'>.

o >>> type(3.14) → <class 'float'>.

o >>> type("Hi") → <class 'str'>.

2.3 String Concatenation and Replication

• String Concatenation:

o Definition: Combines two strings into a new string using +.

o Mechanism: Allocates new memory and copies both strings (due to


immutability).

 >>> "Hello" + " World" → "Hello World".

o Type Constraint: Operands must be strings; >>> "Hi" + 5 → TypeError (use str(5)
to fix).

o Theory: Linear-time operation (O(n), where n is total length), but inefficient in


loops due to repeated allocation.

• String Replication:

o Definition: Repeats a string a specified number of times using *.

o Mechanism: Creates a new string by duplicating the original.

 >>> "Hi" * 3 → "HiHiHi".

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).

 >>> "Hi" * -1 → "" (negative yields empty).

o Theory: Time complexity is O(n * m), where n is string length and m is the
multiplier.

2.4 Storing Values in Variables

• Concept:

o Variables are names bound to objects in memory, acting as labels for data.

o Assignment: = binds a name to an object; e.g., x = 10 creates an integer object


and associates x with it.

• Dynamic Typing:

o No type declaration needed; type is tied to the object, not the variable.

o >>> x = 5; x = "Hello" is valid (rebinds x to a new object).

• Naming Rules:

o Must start with a letter (a-z, A-Z) or underscore (_).

o Can include letters, numbers (0-9), and underscores.

o Case-sensitive: x ≠ X.

o Cannot use keywords (e.g., if, for, while).

• 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).

o Immutability Impact: Reassigning x = 6 creates a new object, leaving y


unchanged.

• Theory:

o Variables form a namespace (symbol table) mapping names to objects,


managed by Python’s runtime.

2.5 Dissecting Your Program

• Program Structure:

o A Python program is a sequence of statements (assignments, expressions,


control flow) executed top-down.

o Blocks: Groups of statements defined by indentation after a colon (:).

• Comments:

o Single-line: # This is ignored by the interpreter.


o Multi-line: """This spans multiple lines""" (technically a string, ignored unless
assigned).

o Purpose: Document intent, ignored during execution (removed during


tokenization).

• Indentation:

o Theory: Replaces delimiters (e.g., {} in C) with whitespace to denote block


scope.

o Mandatory: 4 spaces (PEP 8 standard) or 1 tab; mixing causes IndentationError.

o Example:

python

x=5

if x > 0:

print("Positive") # Indented block

print("Outside") # Not in block

• Execution Flow:

o Sequential unless modified by flow control; interpreter processes line-by-line,


respecting block boundaries.

3. Flow Control

3.1 Boolean Values

• Definition:

o Boolean type has two values: True and False, representing binary logic states.

• Theory:

o Based on Boolean algebra (George Boole), foundational to computer science for


decision-making.

o In Python, True and False are singleton objects (unique instances in memory).

• Implicit Conversion:

o Non-Boolean values are coerced in conditions:

 False: 0, 0.0, "", None.

 True: Non-zero numbers, non-empty strings.

 >>> bool(0) → False, >>> bool("Hi") → True.

• Role: Drives conditional execution and loop termination.


3.2 Comparison Operators

• Definition:

o Operators that compare two values, returning True or False.

• List:

o ==: Equality (e.g., 5 == 5.0 → True).

o !=: Inequality (e.g., 5 != 6 → True).

o <: Less than (e.g., 3 < 4 → True).

o >: Greater than (e.g., 5 > 2 → True).

o <=: Less than or equal (e.g., 3 <= 3 → True).

o >=: Greater than or equal (e.g., 4 >= 4 → True).

• Theory:

o Implements relational logic, defining order (for <, >) or equivalence (==, !=).

o Operands must be comparable; 5 < "5" → TypeError.

• String Comparison:

o Lexicographical (dictionary) order based on Unicode values.

 >>> "abc" < "abd" → True (c < d).

3.3 Boolean Operators

• Definition:

o Combine Boolean expressions: and, or, not.

• Semantics:

o and: True if both operands are True.

 >>> True and False → False.

o or: True if at least one operand is True.

 >>> False or True → True.

o not: Inverts the value.

 >>> not True → False.

• Theory:

o Logical connectives from propositional logic; obey truth tables:

A B A and B A or B not A

True True True True False


A B A and B A or B not A

True False False True False

False True False True True

False False False False True

• Evaluation:

o Short-Circuiting: and stops at first False; or stops at first True.

 >>> False and (1 / 0) → False (no error).

3.4 Mixing Boolean and Comparison Operators

• Concept:

o Combines comparison (<, >, etc.) and Boolean (and, or, not) operators to form
complex conditions.

• Theory:

o Creates compound predicates, parsed as a single Boolean expression.

o Follows operator precedence: not > and > or.

• Examples:

o >>> (5 > 3) and (10 < 15) → True.

o >>> not (2 == 2) or (3 < 5) → True (evaluates as False or True).

• Purpose: Enables multi-criteria decision-making in flow control.

3.5 Elements of Flow Control

• Definition:

o Mechanisms to alter the sequential execution of a program.

• Components:

o Conditions: Boolean expressions (e.g., x > 0).

o Blocks: Indented statement groups executed as a unit.

• Types:

o Sequential: Default line-by-line flow.

o Selection: Conditional branching (e.g., if).

o Iteration: Repetition (e.g., loops, covered in statements).

• Theory:

o Implements structured programming, ensuring predictable control flow without


arbitrary jumps.
3.6 Program Execution

• Concept:

o The process by which Python interprets and runs code.

• Flow:

o Top-down, statement-by-statement, unless redirected by flow control.

o Blocks are entered/exited based on conditions or loops.

• 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")

# Executes: Start → Positive → End

3.7 Flow Control Statements

• if Statement:

o Syntax: if condition:

o Executes block if condition is True.

o Example: if x > 0: print("Positive").

• else Statement:

o Executes if if condition is False.

o Syntax: else: (no condition).

o Example:

python

if x > 0:

print("Positive")
else:

print("Non-positive")

• elif Statement:

o Short for “else if”; tests additional conditions.

o Syntax: elif condition:.

o Example:

python

if x > 0:

print("Positive")

elif x == 0:

print("Zero")

else:

print("Negative")

• while Loop:

o Repeats block while condition is True.

o Syntax: while condition:.

o Example:

python

x=3

while x > 0:

print(x)

x -= 1 # Prints 3, 2, 1

• for Loop:

o Iterates over a sequence (e.g., range()).

o Syntax: for var in sequence:.

o Example:

python

for i in range(3):
print(i) # Prints 0, 1, 2

• break Statement:

o Exits the innermost loop immediately.

o Example:

python

for i in range(5):

if i == 2:

break

print(i) # Prints 0, 1

• continue Statement:

o Skips to the next iteration of the innermost loop.

o Example:

python

for i in range(5):

if i % 2 == 0:

continue

print(i) # Prints 1, 3

• Theory:

o These statements provide Turing completeness, enabling any computable


function via selection and iteration.

3.8 Importing Modules

• Concept:

o Modules are files containing reusable Python code (functions, variables).

o Syntax: import module_name.

• Mechanism:

o Loads module into memory, making its contents accessible via dot notation
(e.g., math.sqrt).

o Example:

python
import math

print(math.sqrt(16)) # Prints 4.0

• Variants:

o from module import name: Imports specific item directly.

 >>> from math import pi; print(pi) → 3.14159….

• Theory:

o Supports modularity, a key software engineering principle, by encapsulating


functionality in namespaces.

3.9 Ending a Program Early with sys.exit()

• Concept:

o sys.exit() terminates the program immediately, part of the sys module.

• Syntax:

o import sys; sys.exit([message]) (message optional).

• Mechanism:

o Raises SystemExit exception, caught by the interpreter to halt execution.

o Example:

python

import sys

x = -1

if x < 0:

sys.exit("Negative value detected")

print("Won’t run")

• Theory:

o Provides controlled termination, mimicking OS-level exit codes (0 = success,


non-zero = failure).
Key Theoretical Takeaways

• Python Basics: Built on a dynamic, object-oriented model where everything (ints, floats,
strings) is an object, influencing memory and typing behavior.

• Flow Control: Implements structured programming paradigms, ensuring logical,


predictable execution paths.

• Design Choices: Indentation, strong typing, and module system reflect Python’s focus
on clarity and maintainability.
UNIT-II

1. Functions

1.1 def Statements with Parameters

• Theoretical Foundation:

o Functions embody abstraction and modularity, core principles of structured


programming (Dijkstra, 1970s). They encapsulate reusable logic, reducing
redundancy.

o The def statement defines a function object, stored in the namespace as a first-
class entity (can be passed, assigned, etc.).

• Syntax and Semantics:

o def fname(param1, param2): creates a function with formal parameters,


mapping to actual arguments at call time.

o Parameters represent variables in the function’s local scope, forming a contract


between caller and callee.

• Parameter Passing:

o Python uses pass-by-object-reference, a hybrid of pass-by-value and pass-by-


reference:

 Immutable objects (e.g., int, str): Changes are local (new object
created).

 Mutable objects (e.g., list): Modifications affect the original (reference


shared).

o Theory: This reflects Python’s object model, where all values are references to
heap-allocated objects.

• Scope Binding:

o Parameters are bound at invocation, evaluated left-to-right, ensuring


deterministic behavior.

1.2 Return Values and return Statements

• Theoretical Basis:

o The return statement implements the function return mechanism, a


fundamental concept in computability (e.g., λ-calculus), enabling output
production.

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.

1.3 The None Value

• 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.”

o Singleton design ensures one instance exists (id(None) is constant), optimizing


memory.

• Semantics:

o Returned implicitly by functions lacking return, explicitly to indicate absence


(e.g., failed operation).

o Distinct from falsy values (0, "")—has no inherent truth value beyond bool(None)
= False.

• Theory:

o Facilitates safe handling of undefined states, a common requirement in robust


program design.

1.4 Keyword Arguments and print()

• Theoretical Basis:

o Keyword arguments extend parameter passing with named bindings, enhancing


clarity and flexibility—a nod to Python’s “explicit is better than implicit”
philosophy.

o print() is a built-in function demonstrating practical application of keyword


arguments.

• Semantics:

o Positional arguments match parameters by order; keyword arguments match by


name, overriding order.

 Example: def f(a, b): ...; f(b=2, a=1) is valid.

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:

o Keyword arguments align with named parameter passing in formal languages,


reducing errors in complex calls.

1.5 Local and Global Scope

• Theoretical Foundation:

o Scope defines name resolution, a critical aspect of programming language


semantics (e.g., ALGOL’s block scope).

o Python uses lexical scoping: variable visibility is determined by source code


structure.

• Scope Rules:

o Local Scope: Created on function entry; variables are bound to the function’s
frame (stack-allocated namespace).

o Global Scope: Module-level namespace, persistent across the program’s


lifetime.

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:

o Encapsulation via local scope prevents unintended interactions, supporting


modular design.

1.6 The global Statement

• Theoretical Basis:

o The global statement overrides lexical scoping, allowing direct manipulation of


the global namespace—a controlled breach of encapsulation.

• Semantics:

o global var declares var as a reference to the global variable, not a new local one.

o Required before assignment; reading globals doesn’t need it (due to LEGB).

• Implementation:

o Modifies the function’s symbol table at compile time, linking var to the module’s
__dict__.
• Theory:

o Reflects a trade-off between flexibility and safety, discouraged in favor of explicit


data passing (e.g., return values).

1.7 Exception Handling

• Theoretical Foundation:

o Exception handling implements fault tolerance, rooted in Hoare’s work on


program correctness—separating normal from exceptional control flow.

o Exceptions are objects, subclassing BaseException, forming a hierarchy (e.g.,


ZeroDivisionError < ArithmeticError).

• Semantics:

o try: Marks a block for exception monitoring.

o except: Matches and handles specific exception types, using pattern-matching


semantics.

o else: Executes only if no exception occurs, optimizing normal-case logic.

o finally: Ensures cleanup (e.g., resource release), executed unconditionally.

• Control Flow:

o An exception unwinds the call stack until caught or terminates the program.

• Theory:

o Provides a structured alternative to error codes, aligning with modern language


design (e.g., Ada, Java).

2. Lists

2.1 The List Data Type

• Theoretical Foundation:

o Lists are dynamic arrays, a fundamental data structure in computer science,


offering ordered, mutable storage.

o Contrast with static arrays: Python lists resize via reallocation (amortized O(1)
appends).

• Semantics:

o Defined as [item1, item2, ...], supporting heterogeneous elements (type-


agnostic).

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.

2.2 Working with Lists

• Theoretical Basis:

o Lists support sequence operations, a generalization of string-like behaviors,


adapted for mutability.

• Operations:

o Indexing: O(1) access via offset calculation.

o Slicing: O(k) where k is slice length, creates a shallow copy.

o Concatenation: O(n + m) for lists of lengths n and m.

o Modification: Direct assignment (e.g., lst[i] = x) is O(1).

• Implementation:

o Internally a contiguous array of object pointers, resized dynamically (over-


allocation strategy).

• Theory:

o Mutability enables in-place updates, contrasting with immutable sequences


(e.g., tuples).

2.3 Augmented Assignment Operators

• Theoretical Foundation:

o Augmented operators (+=, etc.) are syntactic sugar for in-place operations,
optimizing mutable object manipulation.

• Semantics:

o For lists, += invokes __iadd__, equivalent to extend() for iterables.

 Example: lst = [1]; lst += [2] → [1, 2].

o For scalars, reassigns (e.g., x += 1 → x = x + 1).

• Theory:

o Reduces temporary object creation, leveraging mutability for efficiency (O(1) vs.
O(n) for concatenation).

2.4 Methods

• Theoretical Basis:

o Methods are object-bound functions, implementing list-specific operations via


the sequence ADT.

• Semantics:
o append(x): O(1) amortized, adds to end.

o insert(i, x): O(n) due to shifting elements.

o remove(x): O(n) for search and shift.

o pop(i): O(1) at end, O(n) elsewhere.

• Theory:

o Methods exploit mutability and dynamic sizing, balancing flexibility and


performance.

3. Dictionaries and Structuring Data

3.1 The Dictionary Data Type

• Theoretical Foundation:

o Dictionaries implement a hash table, a key data structure for associative arrays
with O(1) average-time operations.

o Keys must be hashable (immutable, implementing __hash__), ensuring unique


mappings.

• Semantics:

o Defined as {key: value, ...}, unordered until Python 3.7 (insertion order
preserved).

o Access via dict[key], modification via assignment.

• Theory:

o Hashing maps keys to indices, resolving collisions via open addressing (Python’s
approach).

3.2 Pretty Printing

• Theoretical Basis:

o Pretty printing is a visualization technique, enhancing human interpretation of


complex data structures.

• Semantics:

o pprint formats nested structures with indentation, preserving semantics.

• Theory:

o Aids debugging and data inspection, abstracting raw memory representation.

3.3 Using Data Structures to Model Real-World Things

• Theoretical Foundation:
o Data structures are abstractions for real-world entities, mapping properties
(keys) to attributes (values) or sequences (lists).

• Semantics:

o Dictionaries model entities with attributes; lists model ordered collections.

• Theory:

o Reflects object-oriented modeling, bridging procedural and structural


paradigms.

4. Manipulating Strings

4.1 Working with Strings

• Theoretical Foundation:

o Strings are immutable sequences, a specialization of the sequence ADT, rooted


in text processing theory.

• Semantics:

o Operations (e.g., slicing, concatenation) return new strings, preserving original


state.

• Theory:

o Immutability ensures safety (e.g., as hash keys) and predictability, at the cost of
memory for modifications.

4.2 Useful String Methods

• Theoretical Basis:

o Methods are functional extensions of string operations, leveraging immutability


for pure transformations.

• Semantics:

o Case: lower(), upper()—O(n) character mappings.

o Trimming: strip()—O(n) edge scanning.

o Splitting: split()—O(n) tokenization.

o Joining: join()—O(n) aggregation.

• Theory:

o Methods support string processing as a stateless operation, aligning with


functional programming.
Core Theoretical Insights

• Functions: Formalize computation as input-output mappings, with scope and


exceptions enforcing robustness.

• Lists: Dynamic sequences balance flexibility and efficiency.

• Dictionaries: Hash-based mappings optimize associative access.

• Strings: Immutable sequences prioritize safety and simplicity.

You might also like