Python Fundamentals Masterclass – Complete Notes for KVS/NVS PGT CS

1. Author’s Note: The Architecture of Success

By Sriram

“Welcome to the single most important document you will read for your PGT preparation.

In my mentoring of Computer Science aspirants, I have seen a clear trend: The difference between a ‘Selected’ candidate and a ‘Waitlisted’ candidate often comes down to their understanding of Python’s Fundamental Architecture.

Anyone can write a for loop. But can you explain why a = a + [1] creates a new list while a += [1] modifies the existing one? Can you predict the output of print(-5 // 2) correctly under exam pressure? Do you understand how Python’s Garbage Collector handles reference counting?

In high-stakes exams like KVS, NVS, and EMRS, the examiner is not looking for a coder; they are looking for a Computer Scientist. They test your understanding of memory, precedence, and logic. This Masterclass is designed to take you from ‘Coding’ to ‘Engineering’. We will dissect Python layer by layer, ensuring that no question—no matter how twisted—can surprise you.”


2. The Genesis: Python’s Philosophy & Architecture

Before we touch the syntax, we must understand the soul of the language. Python was conceived in the late 1980s by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language.

2.1 The “Zen of Python”

Python is built on a set of guiding principles called the “Zen of Python.” You can see this by typing import this in the Python shell. The core philosophies relevant to your exam are:

  1. Readability counts: Code is read much more often than it is written.
  2. Explicit is better than implicit: Don’t rely on hidden magic; make your logic clear.
  3. Simple is better than complex: If you can write it in 2 lines, don’t use 10.

2.2 The Internal Execution Model (PVM)

Unlike C or C++, which compile directly to machine code, Python uses a two-step process. This is a favorite topic in interviews.

  1. Compilation (Translation to Bytecode):
    • When you run a .py file, the Python Compiler first checks for syntax errors.
    • If valid, it translates the source code into a lower-level, platform-independent format called Bytecode.
    • This Bytecode is often stored in .pyc files (inside the __pycache__ folder) to speed up future runs.
  2. Interpretation (The PVM):
    • The Python Virtual Machine (PVM) is the runtime engine. It takes the Bytecode and converts it into machine instructions (\(0 \)s and \(1 \)s) that your specific CPU (Intel/AMD/ARM) can understand.
  • Insight for U: This architecture makes Python Platform Independent (Write Once, Run Anywhere) but slightly slower than compiled languages like C++.

2.3 Execution Modes

Python offers two distinct environments for code execution:

A. Interactive Mode (The Shell):

  • Identified by the prompt >>> (Primary) or ... (Secondary).
  • Pros: Immediate feedback. Excellent for testing small snippets (3 + 5).
  • Cons: Code is lost once the window is closed. Not suitable for large projects.

B. Script Mode:

  • You write the code in a text file saved with the .py extension.
  • You execute the file using the command python filename.py.
  • Pros: Code is saved permanently. Essential for building modules and software.

3. Variables and Memory Management

(The “Object Reference” Model)

This is where C++ and Java developers often stumble.

3.1 Variables as “Tags”, Not “Boxes”

In traditional languages (C++), a variable int a = 10 is a memory location (a box) named a containing the value 10.

In Python, everything is an Object.

  • 10 is an Integer Object stored at a specific memory address (e.g., 0x100).
  • a is simply a Name (Tag) that points to that address.

The Implications:

Python

x = 10
y = x
  • Here, Python does not copy the value 10. It simply makes y point to the same object that x is pointing to.
  • If you run x = 20, x moves to a new object 20. y stays pointing at 10.

3.2 Object Inter-ning (Small Integer Caching)

Python optimizes memory for efficiency. It pre-allocates objects for small integers (usually -5 to 256).

  • If you say a = 100 and b = 100, they will point to the same memory address automatically.
  • If you say a = 1000 and b = 1000, they might point to different addresses (depending on the implementation).

3.3 The id() and type() Functions

  • id(object): Returns the unique identity (memory address) of an object.
  • type(object): Returns the class type of the object.
  • Exam Tip: id() is guaranteed to be unique and constant for an object during its lifetime.

4. Python Tokens: The Grammar of Code

A Python program is composed of tokens. A token is the smallest lexical unit.

4.1 Keywords (Reserved Words)

These are the vocabulary of Python. As of Python 3.10+, there are roughly 35 keywords.

  • Control Flow: if, elif, else, while, for, break, continue, return.
  • Structure: def, class, with, as, pass, lambda.
  • Logic: and, or, not, is, in.
  • Import: import, from, as.
  • Exception Handling: try, except, raise, finally, assert.
  • Async: async, await.
  • Constants: True, False, None.

Caution: Do not try to memorize the list. Just remember the Capitalized Three: True, False, None. All others are lowercase.

4.2 Identifiers (Naming Convention)

Identifiers are user-defined names for variables, functions, and classes.

The Rules (Strictly Enforced):

  1. Allowed Characters: A-Z, a-z, 0-9, and Underscore (_).
  2. Start Rule: Must start with a Letter or Underscore. Cannot start with a digit.
  3. No Symbols: Special characters like @, $, % are forbidden.
  4. Case Sensitivity: total, Total, and TOTAL are three different identifiers.

Naming Conventions (Good Practice, not Enforced):

  • Variables/Functions: snake_case (e.g., student_name).
  • Classes: PascalCase (e.g., StudentDetails).
  • Constants: UPPER_CASE (e.g., PI_VALUE).

4.3 Literals (Data Values)

Literals are the raw data assigned to variables.

  1. String Literals:
    • Single/Double Quotes: 'Hello', "Hello". (No difference).
    • Triple Quotes: '''Hello'''. Used for multi-line strings or Docstrings.
    • Escape Sequences: Special characters preceded by a backslash \.
      • \n: Newline
      • \t: Tab
      • \\: Backslash
      • \': Single Quote
  2. Numeric Literals:
    • Decimal: 10, -5.
    • Octal: Starts with 0o (e.g., 0o12).
    • Hexadecimal: Starts with 0x (e.g., 0xA5).
    • Float: 10.5 or Scientific 1.5e2 (\(1.5 \times 10^2 = 150.0 \)).
    • Complex: Real + Imagj. E.g., 3 + 5j. (Only j or J is allowed for imaginary part).
  3. Boolean Literals:
    • True (Internal value 1).
    • False (Internal value 0).
  4. Special Literal:None
    • Used to signify “Empty” or “No Value”. It is an object of its own type (NoneType).

5. Data Types: The Core Building Blocks

Python is Dynamically Typed, meaning type checking happens at runtime.

5.1 The Hierarchy of Types

  1. Numbers:
    • int: Arbitrary precision (can grow as large as memory allows). No long type in Python 3.
    • float: Double-precision floating point (accurate up to 15 decimal places).
    • complex: For complex math.
  2. Sequences:
    • Immutable: str (String), tuple, bytes.
    • Mutable: list, bytearray.
  3. Sets:
    • set: Mutable, Unordered, Unique elements.
    • frozenset: Immutable set.
  4. Mappings:
    • dict: Key-Value pairs. Mutable.

5.2 Implicit vs. Explicit Type Casting

  • Implicit (Coercion): Python promotes smaller types to larger types to prevent data loss.
    • True + 5 $\rightarrow$ 1 + 5 $\rightarrow$ 6 (Bool promotes to Int).
    • 10 + 5.5 $\rightarrow$ 15.5 (Int promotes to Float).
  • Explicit (Type Conversion): The programmer forces the change.
    • int("123") $\rightarrow$ 123.
    • str(100) $\rightarrow$ "100".
    • list((1, 2)) $\rightarrow$ [1, 2].
    • ord('A') $\rightarrow$ 65 (Char to ASCII).
    • chr(65) $\rightarrow$ 'A' (ASCII to Char).

6. Operators: The Logic Engine

This section is critical. 90% of “Output Finding” questions come from here.

6.1 Arithmetic Operators

  • + (Add), - (Subtract), * (Multiply).
  • Division (/): Always returns float. 4/2 $\rightarrow$ 2.0.
  • Floor Division (//): Returns the integer floor.
    • 10 // 3 $\rightarrow$ 3.
    • -10 // 3 $\rightarrow$ -4. (Rounds down to -4, not -3).
  • Modulus (%): Remainder.
    • 10 % 3 $\rightarrow$ 1.
    • -10 % 3 $\rightarrow$ 2. (Formula: x % y = x - (x // y) * y).
  • Exponentiation (**): 2 ** 3 $\rightarrow$ 8.

6.2 Bitwise Operators (The Advanced Section)

These work on the binary representation of numbers.

  • Let a = 10 (\(1010 \)) and b = 4 (\(0100 \)).
  1. Bitwise AND (&): Both bits must be 1.
    • a & b $\rightarrow$ 1010 & 0100 $\rightarrow$ 0000 (0).
  2. Bitwise OR (|): Either bit is 1.
    • a | b $\rightarrow$ 1010 | 0100 $\rightarrow$ 1110 (14).
  3. Bitwise XOR (^): Bits must be different.
    • a ^ b $\rightarrow$ 1010 ^ 0100 $\rightarrow$ 1110 (14).
  4. Bitwise NOT (~): Inverts bits. Formula: ~x = -(x+1).
    • ~10 $\rightarrow$ -11.
  5. Left Shift (<<): Shifts bits to the left, filling 0s.
    • 10 << 1 $\rightarrow$ 10100 (20). Effect: Multiplies by 2.
  6. Right Shift (>>): Shifts bits to the right.
    • 10 >> 1 $\rightarrow$ 101 (5). Effect: Divides by 2 (Integer).

6.3 Logical Operators (Short-Circuit Logic)

  1. and: Returns the first False value, or the last value if all are True.
    • 5 and 10 $\rightarrow$ 10.
    • 0 and 10 $\rightarrow$ 0.
  2. or: Returns the first True value, or the last value if all are False.
    • 5 or 10 $\rightarrow$ 5.
    • 0 or 10 $\rightarrow$ 10.
  3. not: Returns boolean Inverse.

6.4 Operator Precedence (BODMAS of Python)

Memorize this hierarchy (Top to Bottom):

  1. () Parenthesis
  2. ** Exponent (Right-to-Left Associativity)
  3. ~, +, - (Unary)
  4. *, /, //, %
  5. +, - (Binary)
  6. <<, >>
  7. &
  8. ^
  9. |
  10. ==, !=, >, >=
  11. not
  12. and
  13. or
  14. = Assignment

Exam Trap:

2 ** 3 ** 2

  • Wrong: $(2^3)^2 = 8^2 = 64$.
  • Correct: \(2^{(3^2)} = 2^9 = 512 \). (Exponent operator is Right-Associative).

7. Flow of Control: Mastering Decisions

7.1 The if Statement

Python

if condition:
    pass
elif condition2:
    pass
else:
    pass
  • Nested If: An if inside another if. Indentation defines the nesting.

7.2 The range() Function Anatomy

range(start, stop, step)

  • It produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
  • It is a Lazy Function: It generates numbers on demand (doesn’t store them all in memory), returning an iterator.

7.3 Loops (for and while)

A. The for Loop

Designed to iterate over sequences (Lists, Strings, Tuples).

Python

for var in sequence:
    # body

B. The while Loop

Runs as long as the condition is True.

Python

while condition:
    # body
  • Infinite Loop: while True: runs forever. Useful for servers or game loops.

C. The else Block in Loops (Unique Feature)

The else block executes if and only if the loop terminates naturally (i.e., the condition became False or the range ended).

  • It does NOT execute if the loop was stopped by a break statement.

Python

for n in range(2, 5):
    if 5 % n == 0:
        print("Not Prime")
        break
else:
    print("Prime")
# Output: Prime (Loop finished naturally without break)

7.4 Jump Statements

  1. break: Terminates the nearest enclosing loop.
  2. continue: Skips the remaining code in the current iteration and returns to the loop header.
  3. pass: A null operation. The statement is syntactically required but no action is needed.

8. String Manipulation: The Art of Text

Strings are Immutable sequences of Unicode characters.

8.1 Indexing and Slicing

  • Positive Index: \(0 \) to \(n-1 \).
  • Negative Index: \(-1 \) to \(-n \).

Slicing Mechanics: S[start : stop : step]

  • Default Start: 0
  • Default Stop: End of String
  • Default Step: 1
  • Reversal: S[::-1] creates a reversed copy.
  • Note: Slicing never raises an IndexError even if indices are out of bounds (it just handles them gracefully). Indexing (S[100]) does raise an error.

8.2 String Methods (The Library)

You must know the return types:

  1. Case Manipulation:
    • s.capitalize(): First char Upper, rest Lower.
    • s.title(): First char of every word Upper.
    • s.upper(), s.lower(), s.swapcase().
  2. Search & Count:
    • s.count(sub, start, end): Returns frequency.
    • s.find(sub): Returns lowest index or -1.
    • s.index(sub): Returns lowest index or raises ValueError.
  3. Validation (Is functions):
    • s.isalnum(): Alpha-numeric?
    • s.isalpha(): Alphabetic only?
    • s.isdigit(): Digits only?
    • s.isspace(): Whitespace only?
  4. Modification (Returns new string):
    • s.strip(): Removes leading/trailing whitespace.
    • s.lstrip(), s.rstrip().
    • s.replace(old, new, count).
  5. Splitting & Joining:
    • s.split(sep): Returns a List.
    • s.partition(sep): Returns a Tuple (pre, sep, post).
    • sep.join(iterable): Joins strings.

8.3 String Formatting

  1. Old Style (%): print("Hi %s" % name)
  2. Format Method: print("Hi {}".format(name))
  3. f-strings (Modern, Python 3.6+):print(f"Hi {name}")
    • Sriram’s Recommendation: f-strings are the fastest and most readable.

9. Input & Output: Advanced Techniques

9.1 The print() Function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

  • sep: What to insert between values.
    • print("A", "B", "C", sep="-") $\rightarrow$ A-B-C
  • end: What to append at the end.
    • print("Hi", end="") keeps the cursor on the same line.
  • flush: If True, forces the stream to be flushed (printed) immediately.

9.2 The input() Function

  • Pauses execution and waits for user.
  • Always returns a String.
  • If you need an integer, you must cast: age = int(input("Age: ")).
  • Using eval(): eval(input()) can evaluate expressions like "10 + 20" automatically. Warning: Security risk in real software, but useful in competitive coding.

10. Exam Corner: (15 Hard Questions)

These questions are designed to break your misconceptions. Solve them without running the code.

Q1. What is the output?

Python

print(3 * 1 ** 3)
  • Explanation: Precedence: ** (Exponent) > * (Multiply).
    • \(1^3 = 1 \).
    • \(3 \times 1 = 3 \).
  • Answer: 3

Q2. What is the value of ~100?

  • Explanation: Formula for bitwise NOT is -(x + 1).
  • Answer: -101

Q3. Output of print(0.1 + 0.2 == 0.3)?

  • Explanation: Floating point numbers are stored in binary. \(0.1 \) is an infinite fraction in binary. \(0.1 + 0.2 \) results in 0.30000000000000004.
  • Answer: False

Q4. What happens here?

Python

x = ['a', 'b']
y = x
y[0] = 'z'
print(x)
  • Explanation: Lists are Mutable. y = x copies the reference, not the data. Modifying y modifies x.
  • Answer: ['z', 'b']

Q5. Is (1) a tuple?

  • Explanation: No. A single element in parenthesis is just a grouped expression. To make it a tuple, you need a comma: (1,).
  • Answer: No, it is an Integer.

Q6. Output of print(type(1/2)) in Python 3?

  • Answer: <class 'float'> (Division always returns float).

Q7. What is the result of print("10" + 2)?

  • Explanation: Python is strongly typed. It does not auto-convert int to string during addition.
  • Answer: TypeError.

Q8. Which keyword is used to do nothing?

  • Answer: pass.

Q9. Can a dictionary key be a List?

  • Explanation: Dictionary keys must be Immutable (Hashable). Lists are Mutable.
  • Answer: No. (But a Tuple can be a key).

Q10. What does range(10, 2) print?

  • Explanation: Start=10, Stop=2, Step=1 (Default). Since Start > Stop and step is positive, it generates nothing.
  • Answer: Empty sequence (Nothing).

Q11. print(bool("False")) outputs?

  • Explanation: Any non-empty string is Truthy. The content “False” is irrelevant; it is a string with characters.
  • Answer: True.

Q12. What is min("hello world")?

  • Explanation: It compares ASCII values. Space ( ) has a lower ASCII value (32) than letters.
  • Answer: (Space).

Q13. How to check if all characters in string S are digits?

  • Answer: S.isdigit().

Q14. What is the output of print(2 ** 3 ** 2)?

  • Explanation: Exponent is Right-Associative. \(3^2 = 9 \). Then \(2^9 = 512 \).
  • Answer: 512.

Q15. In x = 10; y = 10, is x is y True?

  • Explanation: Yes, due to Small Integer Inter-ning (Caching of numbers -5 to 256).
  • Answer: True.

11. Final Summary & Roadmap

You have just navigated the most detailed Python Fundamentals guide available for PGT aspirants. We moved from the philosophical “Zen of Python” to the binary logic of Bitwise operators.

Final Checklist for Module 2:

  1. Architecture: Bytecode $\rightarrow$ PVM.
  2. Memory: Variables are References. Reference Counting manages memory.
  3. Data Types: Lists are Mutable; Strings/Tuples are Immutable.
  4. Math: Watch out for Floor Division (//) with negative numbers.
  5. Logic: and/or return the actual value, not just True/False.

Next Steps:

Now that your foundation is rock-solid, we will move to the heavy lifters of Python: Data Structures. In Module 3, we will dissect Lists, Tuples, Dictionaries, and Sets with the same level of depth.

[Proceed to Module 3: Python Data Structures Masterclass]

SRIRAM
SRIRAM

Sriram is a seasoned Computer Science educator and mentor. He is UGC NET Qualified twice (2014 & 2019) and holds State Eligibility Test (SET) qualifications for both Andhra Pradesh (AP) and Telangana (TG). With years of experience teaching programming languages, he simplifies complex CS concepts for aspirants of UGC NET Computer Science, KVS, NVS, EMRS, and other competitive exams.

2 Comments

  1. Dear Sir,
    Thanks for your valuable effort, I have a query about EMRS tier 2 descriptive answer writing, are these contents sufficient to write in descriptive questions. Please reply me
    Thanks.

    • Sir,

      Thankyou for positive feedback, this article is like overview on chapter, for descriptive you need to write in detail. Here in LarasAcademy we will post in details notes soon!

      Keep Visiting. All the best for your exam.

Leave a Reply

Your email address will not be published. Required fields are marked *