Follow Us
Select Medium / माध्यम चुनें:
Eng (English) Hindi (हिन्दी)
CBSE • Class XI • Computer Science • Ch 5
Estimated Time: 45 Mins
Study Progress: In Progress

Getting Started with Python

In CBSE Class 11 Computer Science, "Getting Started with Python" delivers an authoritative, exhaustive master resource on the foundational syntax, runtime architecture, and data structures of Python 3. This chapter deconstructs the CPython bytecode execution engine (PVM), interactive vs script execution modes, lexical tokens (keywords, identifiers, literals, operators, delimiters), dynamic name-binding memory semantics, the complete Python data type hierarchy, mutability vs immutability, standard stream I/O (`print()`, `input()`), and explicit type casting aligned with the 2026–27 CBSE curriculum.

Why Does NASA, Instagram, and Every Top AI Lab Run on Python?

In 1989, Dutch programmer Guido van Rossum spent his Christmas vacation building a programming language focused on one core philosophy: code is read much more often than it is written, so readability matters above all else. Today, Python powers the data pipelines that rendered the first photograph of a black hole at NASA, manages over 2 billion active accounts on Instagram, and anchors the foundational frameworks behind modern artificial intelligence (PyTorch, TensorFlow, OpenAI). How can a language so intuitive that a middle-schooler can learn it in an afternoon simultaneously orchestrate high-performance supercomputing clusters? This chapter opens the hood of the Python language.

Why This Chapter Matters

Python is the undisputed lingua franca of contemporary computer science, artificial intelligence, cloud computing, and data analytics. Unlike low-level languages that require manual memory pointers and boilerplate declarations, Python's dynamic typing, automatic garbage collection, and elegant syntax allow software engineers to implement complex algorithms in a fraction of the time. Mastering Python's memory model—specifically how variables behave as references to heap-allocated objects and how mutability impacts memory allocation—is the defining threshold between writing buggy scripts and engineering robust, scalable software.

Before You Begin (Prerequisites)

  • Fundamental concepts of computer systems (CPU, RAM, secondary storage).
  • Basic problem-solving skills: algorithms, flowcharts, and logical branching.
  • Elementary mathematics: arithmetic operations, modulo arithmetic, and variable substitution.

What You Will Learn (Core Objectives)

  • Explain the CPython interpreter architecture: Source code → Bytecode compilation (`.pyc`) → Python Virtual Machine (PVM).
  • Differentiate between Interactive Mode (REPL) and Script Mode (`.py` files) execution environments.
  • Categorize Python lexical tokens: Keywords (35+), Identifiers, Literals, Operators, and Delimiters.
  • Deconstruct Python's dynamic typing and object reference memory model (`id()`, `type()`, garbage collection).
  • Master the complete built-in Data Type taxonomy: Numbers (`int`, `float`, `complex`), Sequences (`str`, `list`, `tuple`), Mappings (`dict`), Sets, and Boolean.
  • Distinguish rigorously between Mutable and Immutable data structures with memory identity proofs.
  • Master standard stream I/O formatting: `input()` type casting, and `print()` with `sep` and `end` keyword arguments.

Chapter Roadmap & Progression

1 1. Python Architecture: From Source...
2 2. Lexical Tokens: The Building Blo...
3 3. Variables, Dynamic Typing & Memo...
4 4. Mutability vs. Immutability: The...
5 5. Python Standard Stream I/O & Typ...

Complete Concept Guide (100% Curriculum Coverage)

1. Python Architecture: From Source Code to the Virtual Machine

Understand

Python is commonly classified as an interpreted language, but behind the scenes, modern CPython (the standard reference implementation written in C) employs a hybrid compilation-interpretation pipeline:

  1. Lexing & Parsing: When a Python program (`script.py`) is executed, the interpreter's tokenizer converts source text into a stream of lexical tokens. The parser then validates grammatical syntax against Python's formal grammar, generating an Abstract Syntax Tree (AST).
  2. Bytecode Compilation: If syntax is valid, the compiler translates the AST into an intermediate, platform-independent representation called Python Bytecode. Bytecode instructions are low-level numeric opcodes optimized for virtual execution. Bytecode is cached on disk inside the `pycache` directory as `.pyc` files to accelerate future execution startup.
  3. Python Virtual Machine (PVM): The PVM is the runtime software engine of Python. It contains an execution loop that reads bytecode instructions one by one, maps them to native machine code instructions, and directs the underlying CPU to execute them.
Execution Modes
  • Interactive Mode (REPL): Launched by typing `python` in a terminal. Provides an immediate Read-Eval-Print Loop denoted by the primary prompt `>>>`. Excellent for rapid prototyping, syntax experimentation, and one-line evaluations. Code is executed immediately and not saved to disk.
  • Script Mode: Source code is authored in a plain text file saved with a `.py` extension (e.g., `main.py`). The entire script is executed from top to bottom via `python main.py`. Required for multi-line modular programming, functions, and persistent production software.

2. Lexical Tokens: The Building Blocks of Python

Understand

Every character sequence in a Python script is parsed into one of five fundamental Tokens:

A. Keywords

Reserved words with predefined, immutable grammatical meanings to the compiler. Python 3 contains 35 keywords (all lowercase except `False`, `None`, and `True`):

False, None, True, and, as, assert, async, await, break, class,
continue, def, del, elif, else, except, finally, for, from, global,
if, import, in, is, lambda, nonlocal, not, or, pass, raise,
return, try, while, with, yield
B. Identifiers

User-defined names assigned to variables, functions, classes, and modules. Identifier Rules:

  • Must begin with an alphabet letter ($A-Z, a-z$) or an underscore (`_`).
  • Subsequent characters can include letters, underscores, or digits ($0-9$).
  • Cannot begin with a digit (e.g., `2count` is illegal; `count2` is legal).
  • Python is strictly case-sensitive (`Total`, `total`, and `TOTAL` are three distinct identifiers).
  • Cannot use special punctuation characters or whitespace (`@`, `$`, `%`, `-`, `.` are prohibited).
  • Cannot be a reserved keyword (e.g., `def = 10` causes a `SyntaxError`).
C. Literals (Constant Data Values)
  • Integer: Unbounded arbitrary-precision integers (e.g., `42`, `-100`, `0b1010` [binary], `0o77` [octal], `0xFF` [hex]).
  • Floating-Point: Real numbers with decimal points or scientific exponential notation (`3.14159`, `-0.005`, `2.5e-3` $= 2.5 \times 10^{-3}$).
  • Complex Numbers: Real and imaginary parts: $z = a + bj$ where $j = \sqrt{-1}$ (e.g., `z = 3 + 4j`; access via `z.real` and `z.imag`).
  • Boolean: Truth values `True` (evaluates to numeric 1) and `False` (evaluates to numeric 0).
  • String Literals: Text enclosed in single (`'...'`), double (`"..."`), or triple quotes (`'''...'''` or `"""..."""` for multi-line strings).
  • Special Literal: `None` represents the absence of a value or null state.

3. Variables, Dynamic Typing & Memory Semantics

Understand & Deep Dive

In languages like C or C++, a variable is a named physical memory box with a fixed type: `int x = 10;`. The box `x` can only ever hold integers.

In Python, everything is an object, and variables are names (references/tags) bound to objects in heap memory:

x = 10       # 1. Integer object 10 created in heap memory.
             # 2. Variable name 'x' is bound (points) to this object.
print(id(x)) # Outputs the unique 64-bit memory address of object 10.
print(type(x)) # <class 'int'>

x = "Hello"  # 3. String object "Hello" created.
             # 4. 'x' is rebound to "Hello". Object 10 is dereferenced.
print(type(x)) # <class 'str'> (Dynamic Typing in action!)
Automatic Garbage Collection

Python tracks the number of references pointing to every heap object via Reference Counting. When an object's reference count drops to zero (no variable names point to it), Python's automatic Garbage Collector immediately reclaims that memory block.

4. Mutability vs. Immutability: The Core Python Paradigm

Understand & Examiner Trap

Every Python object is classified as either Mutable or Immutable based on whether its in-place memory state can be modified after creation:

CategoryData TypesMemory Behavior When "Modified"
Immutable (Cannot be changed in-place)`int`, `float`, `complex`, `bool`, `str`, `tuple`, `frozenset`Any modification creates a brand-new object at a completely different memory address (`id()` changes). The original object remains unmodified.
Mutable (Can be modified in-place)`list`, `dict`, `set`, bytearrayElements can be appended, deleted, or reassigned directly within the same physical memory block (`id()` remains constant).
Proof of Immutability vs Mutability in Python:
# Immutable Example (Integer):
a = 5
old_id = id(a)
a = a + 1
print(id(a) == old_id) # False! New object 6 created; 'a' points to new ID.

# Mutable Example (List):
lst = [1, 2, 3]
old_id = id(lst)
lst.append(4)
print(id(lst) == old_id) # True! Same memory block modified in-place!

5. Python Standard Stream I/O & Type Casting

Understand
A. Standard Input (`input()`)

The `input([prompt])` function reads a line of text from standard input (keyboard) and strictly returns it as a string (`str`). To perform arithmetic, explicit type casting is mandatory:

# WRONG (String concatenation trap):
a = input("Enter a: ") # User inputs 5 -> a = "5"
b = input("Enter b: ") # User inputs 10 -> b = "10"
print(a + b)           # Prints "510" (String concatenation!)

# CORRECT (Explicit Type Casting):
a = int(input("Enter a: ")) # Casts "5" -> 5
b = int(input("Enter b: ")) # Casts "10" -> 10
print(a + b)                # Prints 15 (Arithmetic addition!)
B. Standard Output (`print()`)

The `print()` function accepts variable arguments along with two critical keyword formatting parameters:

  • `sep`: The string inserted between multiple values. Default is a single space (`sep=' '`).
  • `end`: The string appended at the very end of the output. Default is a newline (`end='\n'`).
print("2026", "09", "08", sep="-") # Prints: 2026-09-08
print("Loading", end="...")
print("Done")                       # Prints: Loading...Done (on same line!)

Key Programming Syntax, Statements & Translator Rules

Identity vs Equality Check
$$a == b \text{ (checks values)}; \quad a \text{ is } b \text{ (checks } id(a) == id(b)\text{)}$$
Equality compares values; identity compares underlying heap memory addresses.
Floor Division & Modulo Identity
$$a = (a // b) \times b + (a \% b)$$
Mathematical law governing Python integer arithmetic.
Operator Precedence Hierarchy

$$() > ** > (+, - \text{ unary}) > (*, /, //, %) > (+, - \text{ binary}) > (<, <=, >, >=, ==, !=) > not > and > or$$

Order of operations in complex expressions.

Python Virtual Machine & Memory Model Architecture

CPython Virtual Machine & Heap Memory Model Source Code script.py Bytecode .pyc (Opcodes) Python VM (PVM) Runtime Loop Engine Hardware CPU Machine Instructions Python Object Reference Model: Stack Names vs Heap Memory Stack (Variable Names) x y lst Private Heap Space (Objects) Type: int | Val: 10 id: 0x7ffd91a (Ref count: 2) Type: list (MUTABLE) Val: [100, 200] | id: 0x24a10

Chapter Summary & 10 Key Takeaways

Takeaway 1
Python was engineered by Guido van Rossum in 1991, emphasizing human readability, expressiveness, and rapid development.
Takeaway 2
CPython compiles human source code (`.py`) into platform-independent bytecode (`.pyc`), which is executed line-by-line by the Python Virtual Machine (PVM).
Takeaway 3
Interactive Mode (REPL) executes one-liner commands immediately in memory; Script Mode runs persistent source files saved to disk.
Takeaway 4
Python keywords (35 reserved words) cannot be used as identifier names; identifiers must begin with a letter or underscore and are strictly case-sensitive.
Takeaway 5
Python is dynamically typed: variable types are inferred automatically at runtime based on the object bound to them, and can be rebound dynamically.
Takeaway 6
Variables in Python are not physical memory storage containers; they are reference tags (pointers) bound to objects allocated in heap memory.
Takeaway 7
The `id()` function returns the unique 64-bit physical memory address of an object; `type()` returns its class/data type.
Takeaway 8
Immutable objects (`int`, `float`, `complex`, `bool`, `str`, `tuple`) cannot be altered in-place; modifications create brand-new objects.
Takeaway 9
Mutable objects (`list`, `dict`, `set`) allow in-place element insertion, deletion, and updates within the same memory block.
Takeaway 10
The `input()` function strictly returns a string (`str`); explicit type casting (`int()`, `float()`) is mandatory for mathematical operations.

Check Your Understanding (Diagnostic Practice Questions)

Diagnostic questions testing core conceptual clarity. Answers are hidden initially — solve each problem first, then click to reveal the step-by-step verified solution.

1
Explain the step-by-step internal execution mechanism of Python from human source code (`.py`) to physical CPU execution.
Reveal Answer & Explanation
Answer:
  1. Tokenizing & Parsing: The CPython lexer converts source code into tokens, and the parser builds an Abstract Syntax Tree (AST), checking for syntax errors.
    2. Bytecode Compilation: The compiler converts the AST into platform-independent intermediate instructions called Python Bytecode (cached as .pyc files).
    3. PVM Execution: The Python Virtual Machine (PVM) reads bytecode opcodes in an evaluation loop, translates them to host machine instructions, and commands the physical CPU to execute them.

Source code (.py) → Bytecode (.pyc) → Python Virtual Machine (PVM) → CPU execution.
2
Which of the following are invalid Python identifiers and why? (a) `_total_score`, (b) `2nd_place`, (c) `class`, (d) `student#1`, (e) `True_Value`.
Reveal Answer & Explanation
Answer: • `2nd_place` is INVALID: Identifiers cannot begin with a numeric digit.
• `class` is INVALID: `class` is a reserved Python keyword.
• `student#1` is INVALID: Contains the illegal special character `#`.
• `_total_score` is VALID: Begins with an underscore and contains letters/underscores.
• `True_Value` is VALID: Begins with a letter and does not match a reserved keyword exactly.
Rules: Cannot start with a digit, cannot contain symbols like #, cannot be a keyword.
3
Explain the memory model of Python. What is the difference between dynamic typing and static typing?
Reveal Answer & Explanation
Answer: In statically typed languages (like C++ or Java), variables are physical memory locations with declared types that can never change. In Python, variables are reference labels (pointers) residing in stack memory that bind to typed objects allocated in private heap memory. Dynamic typing means a variable name does not possess a fixed type; its type is determined dynamically by the object it currently points to, allowing the same variable name to point to an integer, then a string, and then a list during runtime.
Python variables are reference tags bound to heap objects; type belongs to the object, not the variable name.
4
What is the output of the following code? Explain why using Python's mutability rules:
a = 10
b = a
a = a + 5
print(a, b)
Reveal Answer & Explanation
Answer: Output: `15 10`
Explanation: Integers in Python are IMMUTABLE. Initially, both `a` and `b` reference the same integer object `10`. When `a = a + 5` is executed, Python evaluates `10 + 5 = 15`, allocates a brand-new integer object `15` in heap memory, and rebinds `a` to point to `15`. Variable `b` continues pointing to the original, unmodified integer object `10`.
Integers are immutable; modifying a creates a new object 15 while b still references 10.
5
What is the difference between the equality operator `==` and the identity operator `is` in Python? Illustrate with an example.
Reveal Answer & Explanation
Answer: The equality operator `==` compares the *values* or contents of two objects. The identity operator `is` checks whether two variables reference the *exact same physical object* in memory (i.e., whether `id(a) == id(b)`).
Example:
x = [1, 2, 3]
y = [1, 2, 3]
Here, `x == y` evaluates to `True` because their elements are identical, but `x is y` evaluates to `False` because they are two distinct list objects stored at different heap memory addresses.
== checks value equality; is checks whether they share the exact same memory address (id).
6
Predict the output of the following Python statements:
x = input("Enter number: ") # User inputs: 7
print(x * 3)
print(int(x) * 3)
Reveal Answer & Explanation
Answer: Output line 1: `777`
Output line 2: `21`
Explanation: `input()` returns user input strictly as a string (`str`). Therefore, `x` holds `"7"`. When the multiplication operator `*` is used with a string and an integer (`"7" * 3`), Python performs string replication, yielding `"777"`. In line 2, `int(x)` explicitly type casts `"7"` to the integer `7`, so `7 * 3` performs arithmetic multiplication, yielding `21`.
String * 3 performs repetition; Integer * 3 performs arithmetic multiplication.
7
How do the `sep` and `end` keyword arguments in the `print()` function work? Provide a code example demonstrating their use.
Reveal Answer & Explanation
Answer: In `print()`, `sep` defines the separator string placed between multiple arguments (default is a single space ``), and `end` defines the string appended at the end of the printed line (default is a newline character `'\n'`).
Example:
print("Sun", "Mon", "Tue", sep=" | ", end=" -> ")
print("Wed")
Output:
Sun | Mon | Tue -> Wed
sep specifies inter-item delimiter; end specifies terminal character replacing default newline.
8
Classify the following Python data types into Mutable and Immutable: `int`, `list`, `str`, `dict`, `tuple`, `set`, `float`.
Reveal Answer & Explanation
Answer: • Immutable Types: `int`, `float`, `str`, `tuple` (their contents cannot be modified in-place once created).
• Mutable Types: `list`, `dict`, `set` (elements can be added, modified, or removed in-place without altering the object's memory address).
Lists, dictionaries, and sets are mutable; numbers, strings, and tuples are immutable.
Finished Studying This Chapter?
READY TO PRACTICE?

Timed CBT Practice Tests (Exam Simulator)

Put your concepts to the test with official curriculum-aligned Foundation and Advanced practice tests. Get instant accuracy scores, time metrics, and step-by-step verified explanations.