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_casefor variables and functions,CamelCasefor classes,UPPER_CASEfor 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, andNone(printis 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 withj.bool: Truth values (True,False), implemented as a subclass ofintwhereTrue == 1andFalse == 0.str: Immutable sequences of Unicode characters.NoneType: Represents the absence of a value via singletonNone.
Mutability Categories: Immutable types include
int,float,complex,bool,str, andtuple; mutable collections includelist,set, anddict.Falsy Values: Evaluate to
Falsein boolean contexts:0,0.0,0j,"",None,False, and empty containers ([],(),{},set()); all other expressions evaluate toTrue.Type Casting: Supports implicit coercion up the hierarchy (
booltointtofloattocomplex) and explicit casting using functions such asint(),float(),str(),bool(),chr(), andord().
Operators and Precedence
Operator Categories:
Arithmetic:
+,-,*,/(always yieldsfloat),//(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 ),<<(multiply by ),>>(floor divide by ).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):
Parentheses:
()Exponentiation:
**(associates right-to-left)Unary operators:
+x,-x,~x(right-to-left)Multiplicative:
*,/,//,%(left-to-right)Additive:
+,-(left-to-right)Bitwise shifts:
<<,>>(left-to-right)Bitwise AND:
&(left-to-right)Bitwise XOR:
^(left-to-right)Bitwise OR:
|(left-to-right)Comparisons, identity, membership:
==,!=,<,<=,>,>=,is,is not,in,not in(chained)Logical NOT:
not(right-to-left)Logical AND:
and(left-to-right)Logical OR:
or(left-to-right)Conditional expression:
x if cond else y(right-to-left)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 astrand requires explicit casting for arithmetic.
Strings and String Processing
String Structure: Immutable Unicode sequence indexed via zero-based indexing from the left ( to ) and negative indexing from the right ( to ).
Slicing Syntax:
s[start:stop:step]extracts characters fromstartup to, but excluding,stop; omitting fields defaults to0, length of string, and step1; negative step reverses traversal (s[::-1]reverses the entire string).Common Methods:
Case Modification:
upper(),lower(),capitalize(),title(),swapcase().Searching & Counting:
find()(returns if absent),index()(raisesValueErrorif 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-elseladders, 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 toFalse.for: Definite, sequence-driven traversal over an iterable or generated integer sequences viarange([start], stop, [step]).
Loop Else Construct: Loops accept an optional
elseblock that executes exclusively when the loop terminates naturally without triggering abreakstatement.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 aSystemExitexception.
Core Exam Implementations
Factorial: Iterative product accumulator
fact *= irunning over range1ton.Fibonacci Series: Simultaneous tuple assignment
a, b = b, a + boverniterations starting from0, 1.Palindrome Check: Slicing comparison
s == s[::-1]on input strings.Digit Reversal & Summation: Extract the lowest digit via
n % 10and reduce using integer floor divisionn //= 10.Prime Verification: Loop over candidate factors
2tonum - 1; triggerbreakifnum % i == 0, concluding via the loop'selseclause to certify primality.