Full Syllabus
Course Code: MCA504 • 16 Class Hours

Unit 1: Python Language Basics

This study guide provides exhaustive conceptual coverage for Tribhuvan University MCA semester examinations. Hard concepts are explained in Nepali alongside clean code implementations and structured exam answers.

TU Marks Weightage: Approximately 15 to 20 Marks (Theory, Program Tracing & Short Notes)

01. Introduction, Bytecode & PVM

Python was created by Guido van Rossum and released in 1991. It is a high-level, dynamically typed, garbage-collected language that supports procedural, object-oriented, and functional programming paradigms.

Internal Execution Architecture

Python is often termed an interpreted language, but internally it follows a two-stage hybrid execution pipeline:

  1. Compilation to Bytecode: The CPython compiler parses .py source code and translates it into an intermediate, platform-independent representation called Bytecode. These compiled files are saved with the .pyc extension inside the __pycache__ directory.
  2. Execution by PVM: The Python Virtual Machine (PVM) is the runtime engine. It contains an infinite evaluation loop that reads each bytecode instruction, converts it into native CPU instructions, and executes it.
👨‍🏫 Teacher's Board Note: Python code सिधै CPU मा run हुँदैन। पहिले CPython compiler ले .py source code लाई .pyc (Bytecode) मा compile गर्छ। त्यसपछि PVM (Python Virtual Machine) को evaluation loop ले bytecode लाई line-by-line machine instructions मा convert गरेर CPU मार्फत execute गराउँछ।
DIAGRAM 1: PYTHON INTERNAL EXECUTION ARCHITECTURE
Source Code
script.py
CPython Compiler
Lexer, AST & Parser
Bytecode (.pyc)
__pycache__ folder
PVM Runtime
Interpreter Loop
Machine Code
CPU Execution
📌 Exam Tip: 10-mark question मा यो 5-stage pipeline diagram draw गर्दा Full Marks secure हुन्छ।

02. Algorithm & Flowchart Design

An algorithm is a step-by-step, finite sequence of unambiguous instructions designed to solve a specific computational problem. A flowchart is the pictorial or graphical representation of an algorithm.

Five Key Criteria of an Algorithm

  • Input: Zero or more quantities externally supplied.
  • Output: At least one value produced as result.
  • Definiteness: Each step must be clear and unambiguous.
  • Finiteness: The algorithm must terminate after a finite number of steps.
  • Effectiveness: Every instruction must be basic enough to be carried out in practice.

Standard Flowchart Symbols for TU Examination

DIAGRAM 2: STANDARD FLOWCHART SYMBOLS & FUNCTIONAlgorithm Visual Representation
START / STOP
Oval (Terminal)Program Boundary
INPUT/OUT
ParallelogramRead / Print Data
PROCESS
RectangleCalculations / Math
IF?
DiamondDecision (Yes / No)
💡 TU Exam Note: Always connect symbols with directional flowlines (arrows) from top to bottom or left to right.

03. Environment, REPL & Script Modes

Python programs can be executed in two distinct modes:

  • Interactive Mode (REPL): Read-Eval-Print-Loop. Invoked by typing python in the command line. Allows instant evaluation of expressions at the >>> prompt. Ideal for debugging and testing single-line logic.
  • Script Mode: Writing statements inside a persistent text file with a .py extension and executing via terminal (python filename.py). Essential for production programs and TU lab submissions.
$ python -c "print('TU MCA 2081')" # One-line execution flag
$ python -m py_compile app.py # Explicit bytecode compilation

04. Data Types & Mutability (Memory Model)

In Python, variables do not store values directly; they hold references (memory addresses) pointing to objects on the heap. Every object possesses an Identity, a Type, and a Value.

👨‍🏫 Teacher's Board Note:
- Immutable: यस्ता Data Types जसको value Memory मा एकपटक create भएपछि modify गर्न मिल्दैन। Value update गर्न खोज्दा CPython ले नयाँ Memory Address allocate गर्छ (उदा: int, float, str, tuple, bool)।
- Mutable: सोही Memory Address (in-place) मा elements थपघट वा modify गर्न मिल्छ (उदा: list, dict, set)।
DIAGRAM 3: PYTHON HEAP MEMORY REFERENCE MODELImmutable vs Mutable In Memory
A. Immutable (String / Int Reassignment)
Variable x➔ [Address 0x10A : Value 100]
Execute: x = x + 1
Variable x➔ [Address 0x20B : Value 101]
* Old 0x10A is left unreferenced for Garbage Collector.
B. Mutable (List In-Place Update)
Variable lst➔ [Address 0x500 : [10, 20]]
Execute: lst.append(30)
Variable lst➔ [Address 0x500 : [10, 20, 30]]
* EXACT SAME address 0x500! Internal buffer expands in-place.
💡 TU Exam Proof: Always cite id(x) returning distinct integer addresses for immutable reassignment vs identical addresses for mutable in-place append.

Demonstration of Mutability with `id()`

# 1. Immutable (Integer / String): Creates a new memory object
x = 100
print(id(x)) # e.g., 14070520
x = x + 1
print(id(x)) # DIFFERENT id! (New object allocated)

# 2. Mutable (List): Updates in-place
lst = [1, 2]
print(id(lst)) # e.g., 24901040
lst.append(3)
print(id(lst)) # EXACT SAME id!

05. Operators, Expressions & Precedence

Python provides standard Arithmetic, Relational, Logical, Bitwise, Assignment, Identity (is, is not), and Membership (in, not in) operators.

Common Exam Pitfalls & Nuances

  • Division Operators: / (True division) always returns a float (e.g. 4 / 2 = 2.0). // (Floor division) rounds down to nearest integer (e.g. 7 // 2 = 3, but -7 // 2 = -4).
  • Identity vs Equality: == tests whether two objects have matching values. is tests whether two variables point to the exact same memory address (id(a) == id(b)).

Operator Precedence Hierarchy (Highest to Lowest)

Parentheses () ➔ Exponentiation ** ➔ Unary +x, -x, ~x ➔ Multiplication & Division *, /, //, % ➔ Addition & Subtraction +, - ➔ Bitwise Shifts <<, >> ➔ Bitwise AND & ➔ Bitwise XOR ^ ➔ Bitwise OR | ➔ Comparisons (<, >, ==, !=, is, in) ➔ notandor.

06. Control Structures & The `for...else` Construct

Python supports decision-making (if, elif, else, ternary val_if_true if condition else val_if_false) and looping constructs (for, while).

👨‍🏫 Teacher's Board Note: Python मा loop पछाडि else block लेख्न मिल्छ। Core logic बुझ्नुहोस्: यदि loop कुनै पनि break statement बिना naturally exhaust भएर समाप्त भयो भने मात्र else block चल्छ। बीचमै break भेटियो भने else block skip हुन्छ। यसले गर्दा search algorithms मा unnecessary found = False जस्ता flags लेखिरहनु पर्दैन।
# Prime Number Test using for...else
num = 17
for i in range(2, int(num ** 0.5) + 1):
    if num % i == 0:
        print(f"{num} is composite (divisible by {i})")
        break # Hits break -> skips else!
else:
    # Runs only if no break occurred
    print(f"{num} is a PRIME number")
DIAGRAM 4: `for...else` EXECUTION DECISION FLOWLoop Decision Tree
Loop Start
Items in range?
Execute Body
Condition check
Hit breakEXIT (Skip else block)
Normal Finish ➔ EXECUTE else: block
💡 Key Takeaway: break terminates both the loop and suppresses the else: block completely.

07. Python Arrays (`array` module) vs Standard Lists

Students often confuse Python's built-in list with arrays. The TU syllabus explicitly mandates understanding the array module.

FeaturePython ListPython Array (`array` module)
Data HomogeneityHeterogeneous (can store int, str, float together)Strictly Homogeneous (enforces identical typecode)
Memory StructureArray of object pointers (high memory overhead)Contiguous raw C buffer (compact memory)
Import RequirementBuilt-in (no import needed, syntax [])Requires import array as arr
Common TypecodesNone'i' (signed int), 'f' (float), 'd' (double)

08. Functions, Scope Resolution (LEGB) & Arguments

Functions are declared using the def keyword. Arguments can be passed positionally, via keywords, or as default parameters.

Variable-Length Arguments: `*args` and `**kwargs`

  • *args: Collects arbitrary positional arguments into a tuple.
  • **kwargs: Collects arbitrary keyword arguments into a dictionary.

The LEGB Scope Resolution Rule

When an identifier is referenced, Python searches four concentric namespaces:

  1. L (Local): Names defined within the active function body.
  2. E (Enclosing): Names in the local scope of enclosing outer functions (closures).
  3. G (Global): Names defined at the module top level. (Modified via global var).
  4. B (Built-in): Pre-loaded names in Python (e.g. len, range, print).
DIAGRAM 5: LEGB SCOPE RESOLUTION CONCENTRIC HIERARCHYInside-Out Lookup Sequence
Built-in Scope (B) : print(), len(), range(), open()
Global Scope (G) : Module-level declarations (e.g. x = 100)
Enclosing Scope (E) : Outer enclosing functions / closures
Local Scope (L)
Innermost function frame
🔍 Search Direction: Local ➔ Enclosing ➔ Global ➔ Built-inRaises NameError if not found
सम्झिनुहोस्: भित्रको फङ्सनबाट मोड्युलको भ्यालु फेर्न global x चाहिन्छ भने, नेस्टेड (Nested) फङ्सनमा बाहिरी फङ्सनको भ्यालु फेर्न nonlocal y चाहिन्छ।

09. Recursion & Lambda Expressions

A recursive function solves a problem by calling itself with reduced sub-problems. Every valid recursive implementation requires:

  • Base Case: The termination condition that returns directly without recursive descent.
  • Recursive Step: The inductive computation that calls itself towards the base case.
DIAGRAM 6: RECURSION CALL STACK UNWINDING (factorial(3))LIFO Call Stack Frames
1. Push Phase (Winding)
Frame 3: factorial(1) ➔ Base Case reached!
Frame 2: factorial(2) = 2 * factorial(1)
Frame 1: factorial(3) = 3 * factorial(2)
2. Pop Phase (Unwinding)
Returns 1 ➔ Frame 3 Popped
2 * 1 = 2 ➔ Frame 2 Popped
3 * 2 = 6 ➔ Frame 1 Popped (Result = 6)
💡 Exam Warning: Infinite recursion without base case exceeds sys.getrecursionlimit() (1000 frames) and triggers RecursionError.

Python enforces a maximum recursion depth limit (default 1000) accessible via sys.getrecursionlimit() to protect against call stack overflow.

Lambda (Anonymous) Functions

Syntax: lambda arguments : expression. An inline, single-expression anonymous function. Most effectively paired with higher-order functions:

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4, 6]
squares = list(map(lambda x: x ** 2, evens)) # [4, 16, 36]

10. String Slicing Mechanics & Type Casting

Strings are immutable sequences of Unicode characters. Slicing follows the universal formula: string[start : stop : step] where stop is exclusive.

s = "TRIBHUVAN"
print(s[0:3]) # "TRI" (indices 0, 1, 2)
print(s[-4:]) # "UVAN" (last 4 characters)
print(s[::-1]) # "NAVUHBERT" (Reverse string idiom)

Type Conversion & Exception Handling

Implicit conversion occurs in mixed numeric expressions (e.g. int + float ➔ float). Explicit conversion is performed via constructors like int(), float(), str(). Non-numeric literals passed to int() trigger ValueError, which should be caught via try...except ValueError.

Section 11 • High-Probability TU Examination Questions

TU Exam Q&A Bank: Model Answers

Each question is structured with Memorization Bullet Points for quick mental recall, followed by an Elaboration Guide on how to write comprehensive 1–2 page answers during the exam.

QUESTION 1 • 10 MARKS / 5 MARKS

Explain the internal execution architecture of Python. What are Bytecode and the Python Virtual Machine (PVM)?

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Hybrid Model: Python is compiled to intermediate bytecode first, then interpreted by the PVM.
  • Compilation Step: CPython compiles .py into platform-independent .pyc stored in __pycache__.
  • PVM Runtime: The PVM is an evaluation loop in C that translates bytecode opcodes into native machine code.
  • Caching Mechanism: If the source file timestamp is unmodified, compilation is skipped on subsequent runs.
  • Portability Advantage: The same .pyc bytecode executes on Windows, Linux, and macOS without changes.

Paragraph Elaboration Blueprint for Exam:

Introduction: Start by writing that Python is popularly categorized as an interpreted language, but technically it implements a two-stage hybrid architecture combining compilation and interpretation.

Stage 1 (Compilation to Bytecode): When a script (e.g. test.py) is executed, CPython first converts the high-level statements into an Abstract Syntax Tree (AST), performs symbol binding, and produces compact, platform-neutral instructions called Bytecode. These are saved inside the __pycache__ folder with a .pyc extension.

Stage 2 (Interpretation by PVM): The Python Virtual Machine (PVM) is not a virtual hardware emulator; it is a software runtime loop written in C. It continuously fetches bytecode instructions, decodes the opcode, and maps them to native host OS operations.

Pipeline: Source Code (.py) ➔ CPython Compiler ➔ Bytecode (.pyc in __pycache__) ➔ PVM ➔ Machine Code / Output
👨‍🏫 Teacher's Board Note: .py फाइल पहिले भित्रभित्रै .pyc (Bytecode) मा बदलिन्छ, अनि PVM ले त्यसलाई लाइन-बाइ-लाइन पढेर कम्प्युटरको प्रोसेसरलाई बुझाउँछ।
QUESTION 2 • 10 MARKS / 5 MARKS

Differentiate between Mutable and Immutable data types in Python. Prove mutability using the `id()` function.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Object References: Variables do not hold literal data; they store pointers to objects on the heap.
  • Immutable Types: Values cannot be altered in-place. Reassignment allocates a brand new object. (int, float, str, tuple, bool).
  • Mutable Types: Values can be modified in-place without altering the object's memory address. (list, dict, set).
  • id() Function: Returns the unique integer representing the object's memory location.
  • Function Parameter Impact: Passing mutable objects allows in-place side effects in caller scope (Pass-by-Object-Reference).

Paragraph Elaboration Blueprint for Exam:

Core Concept: Every object in Python has an identity (memory address), type, and value. Mutability defines whether an object's value can be mutated while keeping its identity intact.

Immutable Types: When you perform x = x + 1 on an integer, Python does not overwrite the existing memory cell. It instantiates a completely new integer object and redirects x to point to it. The old value is reclaimed by Python's reference-counting garbage collector.

Mutable Types: For lists or dictionaries, operations like list.append() alter the existing heap block. The memory reference remains constant throughout the mutations.

# Immutable Proof (String)
s = "TU"; print("Before id:", id(s))
s = s + " MCA"; print("After id:", id(s)) # New id generated

# Mutable Proof (List)
nums = [1, 2]; print("Before id:", id(nums))
nums.append(3); print("After id:", id(nums)) # EXACT SAME id
👨‍🏫 Teacher's Board Note: Immutable (int, str) बदल्न खोज्दा नयाँ मेमोरी ठेगाना बन्छ; Mutable (list, dict) मा भने त्यही ठेगानामा डाटा थपिन्छ।
QUESTION 3 • 5 MARKS

Explain the LEGB rule for variable scope resolution. How do `global` and `nonlocal` work?

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Search Sequence: Local ➔ Enclosing ➔ Global ➔ Built-in.
  • L (Local): Names assigned inside the executing function.
  • E (Enclosing): Names in the parent functions of nested closures.
  • G (Global): Names declared at the module file level.
  • Scope Modifiers: global x modifies module variables; nonlocal y modifies parent closure variables.

Paragraph Elaboration Blueprint for Exam:

Hierarchy: In Python, scope defines the visibility of names. Whenever an identifier is evaluated, Python searches from the narrowest context outward according to the LEGB sequence. If the identifier is absent in all four tiers, a runtime NameError is triggered.

Shadowing & Modifiers: By default, assigning to a variable inside a function creates a local variable that shadows any identically named variable in the global or enclosing scopes. To bind assignment to the module-level variable, declare global var_name. In nested functions, to bind assignment to an outer function's variable without impacting module globals, declare nonlocal var_name.

x = 10 # Global
def outer():
    y = 20 # Enclosing
    def inner():
        nonlocal y; y += 5
        global x; x += 100
    inner()
👨‍🏫 Teacher's Board Note: भेरिएबल खोज्दा पहिला आफ्नै फङ्सन (Local), अनि बाहिरी फङ्सन (Enclosing), अनि फाइल लेभल (Global), र अन्त्यमा पाइथनका मुख्य किवर्ड (Built-in) मा हेर्छ।
QUESTION 4 • 5 MARKS

Explain the functioning of `for...else` and `while...else` constructs in Python with a practical application.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Normal Completion: The else block runs only if the loop finishes all iterations naturally.
  • Break Suppression: If the loop is terminated prematurely via break, the else block is completely skipped.
  • Flag Elimination: Eliminates boolean search flags like found = False in search loops.
  • While Loop Behavior: In while...else, the else block runs when the test condition evaluates to False.
  • Real-world Case: Prime number testing or record searching in database collections.

Paragraph Elaboration Blueprint for Exam:

Execution Semantics: In traditional C/Java syntax, else is only coupled with if statements. Python extends this keyword to loops. An else clause attached to a for or while loop represents a "completion handler" that triggers when the sequence is exhausted without meeting an early exit condition.

Practical Utility: In searching tasks, developers typically set a boolean flag before a loop, flip it when an element matches, break, and evaluate the flag after the loop. With for...else, if the target is found, we simply break (skipping the else block). If the loop completes without finding the target, the else block naturally executes the fallback logic.

for item in [1, 3, 5, 7]:
    if item % 2 == 0:
        print("Even number found!")
        break
else:
    print("No even numbers in list.") # Executes cleanly!
👨‍🏫 Teacher's Board Note: लुपमा else तब मात्र चल्छ जब लुप बिना कुनै break पूरा घुमेर सकिन्छ। बिचमै break भयो भने else चल्दैन।
QUESTION 5 • 5 MARKS

Describe function argument types in Python and explain the Default Mutable Argument Trap.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Argument Categories: Positional, Keyword, Default, *args (tuple), and **kwargs (dictionary).
  • The Trap Cause: Default parameter expressions are evaluated once at function definition time, not on each call.
  • Shared Mutable State: If a mutable object (like []) is used as default, all calls share the same object.
  • Side-Effect Accumulation: Appending to the default list retains elements across independent function calls.
  • Standard Fix: Assign default=None in definition and initialize fresh collection inside function body.

Paragraph Elaboration Blueprint for Exam:

Argument Classification: Python provides rich parameter binding options: positional parameters are matched by order, keyword parameters by parameter name, *args collects variable positional values into a tuple, and **kwargs collects key-value pairs into a dictionary.

The Trap Mechanism: When Python compiles a def statement, it evaluates default arguments once and binds them to the function object's __defaults__ tuple. If a mutable object like a list or dictionary is used as a default value (e.g. def add(x, lst=[])), that single list instance persists in memory across all invocations, creating unintended state leakage.

# The Safe Exam Idiom:
def add_item(item, basket=None):
    if basket is None:
        basket = [] # Fresh list created on every call
    basket.append(item)
    return basket
👨‍🏫 Teacher's Board Note: def f(x=[]) लेख्दा त्यो लिस्ट एकचोटि मात्र मेमोरीमा बन्छ। त्यसैले हरेक कलमा पुरानै डाटा थपिन्छ। यसबाट जोगिन सधैं def f(x=None) लेख्नुपर्छ।
QUESTION 6 • 5 MARKS

Differentiate between Python's standard `list` and the `array` module.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Type Constraint: list is heterogeneous (mixed types); array is strictly homogeneous (single typecode).
  • Memory Efficiency: list holds pointers to boxed heap objects; array holds packed contiguous C data.
  • Performance: array is significantly faster for intensive numerical calculations due to memory locality.
  • Syntax: list is built-in ([]); array requires import array.
  • Use Case: Use lists for general software logic; use arrays for streaming binary/numeric data.

Paragraph Elaboration Blueprint for Exam:

Internal Differences: A Python list is an array of pointers referencing independent Python objects. Each integer in a list incurs at least 28 bytes of overhead (reference count, type pointer, value). In contrast, the array module wraps a C-style contiguous memory block where each integer occupies only 2 or 4 bytes as determined by its typecode (e.g. 'i').

Architectural Decision: Lists offer maximal convenience and dynamic flexibility at the expense of memory footprint. Arrays provide strict data homogeneity and compact binary layouts suitable for file I/O and low-level processing.

import array as arr
nums = arr.array('i', [10, 20, 30]) # 4-byte integers
# nums.append("TU") ➔ Raises TypeError (enforces homogeneity)
👨‍🏫 Teacher's Board Note: List मा जुनसुकै डाटा मिसाउन मिल्छ तर मेमोरी धेरै खान्छ। Array मा एउटै प्रकारको डाटा मात्र तोकेर राख्नुपर्छ, जसले गर्दा मेमोरी बचत हुन्छ।
QUESTION 7 • 5 MARKS

What is a Lambda function? Demonstrate its usage with `map()`, `filter()`, and `reduce()`.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Anonymous Function: Inline function defined without a name using lambda.
  • Single Expression: Syntax is lambda args : expression; cannot contain statements or explicit return.
  • map(func, iter): Applies function to every element, transforming the sequence.
  • filter(func, iter): Retains elements where boolean condition returns True.
  • reduce(func, iter): Cumulatively aggregates values into a single scalar (imported from functools).

Paragraph Elaboration Blueprint for Exam:

Definition: Lambda functions represent Python's support for functional programming constructs. Unlike standard functions defined with def that support multi-line statements and docstrings, lambda functions are restricted to a single evaluated expression that is returned automatically.

Higher-Order Integration: They are most useful as lightweight arguments passed directly into higher-order functions: map() transforms every element, filter() subsets elements based on a predicate, and reduce() folds a collection into a single result.

from functools import reduce
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
squares = list(map(lambda x: x ** 2, evens)) # [4, 16]
total = reduce(lambda a, b: a + b, squares) # 20
👨‍🏫 Teacher's Board Note: Lambda भनेको एकै लाइनमा लेखिने नाम नभएको फङ्सन हो। यो map (सबैलाई बदल्न) र filter (छान्न) सँग बढी प्रयोग हुन्छ।
QUESTION 8 • 5 MARKS

Explain String Slicing syntax in Python with negative indexing. Write expressions to reverse a string.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Slicing Syntax: sequence[start : stop : step].
  • Half-Open Rule: Includes start, excludes stop (index interval [start, stop)).
  • Negative Indexing: -1 represents the last element, traversing backwards.
  • String Inversion: s[::-1] reverses strings cleanly with a negative step without loops.
  • Safe Boundary Clamping: Slicing out-of-bounds indices never throws an IndexError.

Paragraph Elaboration Blueprint for Exam:

Mechanics: Slicing constructs a new sub-sequence from any ordered collection. If start is omitted, it defaults to 0; if stop is omitted, it defaults to the length of the sequence; if step is omitted, it defaults to 1.

Negative Step & Reversal: When step is negative (e.g. -1), Python traverses from right to left. Writing s[::-1] sets start to the end of the string and decrements to the beginning, providing an optimal $O(N)$ string reversal.

s = "TRIBHUVAN"
print(s[0:3]) # "TRI"
print(s[-4:]) # "UVAN"
print(s[::-1]) # "NAVUHBERT" (Clean reverse)
👨‍🏫 Teacher's Board Note: s[::-1] लेख्दा कुनै लुप नलगाई स्ट्रिङ सिधै उल्टो (Reverse) हुन्छ।
QUESTION 9 • 5 MARKS

Distinguish between Implicit and Explicit Type Conversion. How do you handle `ValueError` during user input casting?

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Implicit (Coercion): Done automatically by Python to preserve precision (e.g. int + float ➔ float).
  • Explicit (Casting): Done intentionally by programmer using constructors (int(), float(), str()).
  • User Input Type: input() always returns a string, necessitating explicit parsing.
  • ValueError Exception: Passing unparseable strings (e.g. int("abc")) raises ValueError.
  • Defensive Pattern: Wrap conversions in a try...except ValueError block.

Paragraph Elaboration Blueprint for Exam:

Implicit Conversion: Python safely widens data types during operations where no information is lost. For instance, evaluating an integer with a float coerces the integer into a float before performing computation.

Explicit Conversion & Exception Handling: When accepting inputs via input(), values arrive as raw text strings. Converting these strings to numeric formats requires explicit constructors like int(). If a user inputs non-digit characters, Python throws a ValueError. Robust code wraps conversions in a try...except ValueError block to prevent unhandled runtime termination.

user_str = "123a"
try:
    val = int(user_str)
except ValueError:
    print(f"Cannot convert '{user_str}' to an integer.")
👨‍🏫 Teacher's Board Note: पाइथनले आफैँ सानो टाइपलाई ठूलो बनाउनु Implicit हो; हामीले आफैँ int("12") लेख्नु Explicit हो। नमिलेको अक्षर आए ValueError आउँछ।
QUESTION 10 • 5 MARKS

What is Recursion? Explain the Base Case, Recursive Step, Call Stack, and Python's recursion limit.

5-Point Quick-Grab Memory Anchors (Exam Hall Revision):
  • Definition: A problem-solving strategy where a function invokes itself with smaller inputs.
  • Base Case: The mandatory stopping condition that terminates recursion without further calls.
  • Recursive Step: The inductive step that shrinks the problem towards the base case.
  • Call Stack: Each invocation pushes a new stack frame storing local variables and return addresses.
  • Guard Limit: Default limit is 1000 frames (sys.getrecursionlimit()) to prevent OS crashes.

परीक्षामा लामो उत्तर यसरी विस्तार गर्ने (Paragraph Elaboration Blueprint):

Components: Any mathematically sound recursive function requires two pillars: a Base Case that returns a trivial solution without further descent, and a Recursive Case that executes work and makes the recursive call with an updated parameter that strictly converges towards the base condition.

Call Stack Dynamics: When a function calls itself, a new frame is allocated on the system call stack. Stack frames unwind in Last-In, First-Out (LIFO) order once the base case returns. Because CPython does not optimize tail calls, deep recursion can consume substantial memory. To prevent C-level stack overflow, Python enforces a strict limit (default 1000), raising RecursionError if exceeded.

def factorial(n):
    if n <= 1: return 1 # Base Case
    return n * factorial(n - 1) # Recursive Step
print(factorial(5)) # 120
👨‍🏫 Teacher's Board Note: फङ्सनले आफैँलाई कल गर्ने तरिका Recursion हो। यसमा रोकिने सर्त (Base Case) अनिवार्य हुनुपर्छ। पाइथनमा सुरक्षाको लागि बढीमा १००० पटक मात्र कल हुन पाउँछ।