0% found this document useful (0 votes)
10 views31 pages

Chapter 1 - Introduction To Computer Systems

Chapter 1 introduces computer systems, explaining the roles of hardware and software, including the CPU's function and memory types. It details the fetch-decode-execute cycle of the CPU, the hierarchy of memory, and the importance of data storage and software categories. Chapter 2 covers Python fundamentals, focusing on variables, data types, and basic operations in the programming language.
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)
10 views31 pages

Chapter 1 - Introduction To Computer Systems

Chapter 1 introduces computer systems, explaining the roles of hardware and software, including the CPU's function and memory types. It details the fetch-decode-execute cycle of the CPU, the hierarchy of memory, and the importance of data storage and software categories. Chapter 2 covers Python fundamentals, focusing on variables, data types, and basic operations in the programming language.
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

Chapter 1: Introduction to Computer Systems

A computer system has both physical hardware (the machine parts) and non‐physical software (programs
and data). Hardware by itself is useless; it must be driven by instructions (software). Software is essentially
sets of instructions and data that make the hardware perform useful tasks 1 . For example, operating
systems like Windows or Ubuntu, or applications like Microsoft Word or VLC player, are software that tell the
hardware what to do 2 . In contrast, hardware refers to tangible components like the CPU, memory chips,
keyboard, monitor, etc. (RAM, CPU, keyboard, printer, monitor…) 3 .

• Computer Evolution: Modern computers evolved from early devices (vacuum tubes → transistors →
integrated circuits). Each generation shrank circuits and boosted speed.
• Bits and Bytes: Data is stored in binary (bits). Four bits make a nibble, and two nibbles (8 bits) form a
byte 4 . The byte is the basic storage unit; larger memory units include kilobytes (KB), megabytes
(MB), gigabytes (GB), etc. For example, 1 KB = 1024 bytes 5 .

Core Hardware Components


1. Central Processing Unit (CPU): The CPU is the brain of the computer. It runs programs by repeatedly
fetching instructions from memory, decoding them, and executing them. This process is known as
the Fetch–Decode–Execute (machine instruction) cycle 6 . In practice, the CPU cycles through:
2. Fetch: Read the next instruction from RAM into the CPU.
3. Decode: Interpret what the instruction means (through the Control Unit).
4. Execute: Perform the operation (often in the ALU) and possibly write back results.
5. Store/Write-back: Save results to a register or back to memory.

Under the Hood: The CPU contains several key parts: - The Control Unit (CU): Directs CPU operations. It
decodes each instruction and generates control signals that manage all other parts of the CPU and
peripherals 7 8 . Think of it as a traffic controller: it fetches instructions, decodes them, and tells the ALU
and registers what to do. Crucially, the Control Unit does not do arithmetic itself; it only manages and
sequences the tasks 9 . - The Arithmetic Logic Unit (ALU): Performs all arithmetic (add, subtract, multiply,
divide) and logical (AND, OR, NOT, comparisons) operations 10 11 . For example, when you compute 5 + 3,
the ALU does the addition. If a program asks “is 7 > 4?”, the ALU checks the numbers and returns True or
False. Complex CPUs may have separate units for integer ALU and a Floating Point Unit (FPU) for decimal
calculations, but conceptually it’s all about doing math and logic operations 10 . - Registers: Very small,
very fast memory locations inside the CPU that temporarily hold data and instructions during processing 12
13 . Registers provide quicker access than main memory. Common registers include: - General-Purpose

Registers: These hold intermediate data being processed. For example, when adding two numbers, the
ALU might use registers to hold those numbers and the result.
- Memory Address Register (MAR): Holds a memory address (location) of data to fetch or store. It never
holds the data itself, only the address 14 .
- Memory Data Register (MDR): Holds the data being transferred to or from memory. If you fetch from
memory, data moves into the MDR before being used 15 . Together, MAR and MDR act as a buffer between
CPU and main memory.
- Current Instruction Register (CIR): Holds the instruction currently being decoded and executed. The CU

1
decodes instructions after they have been fetched into the CIR.
- Accumulator: A special register that typically holds ALU results temporarily 16 . For example, after the
ALU adds two numbers, it might store the sum in the Accumulator before it’s saved elsewhere.

1. Memory (Primary and Secondary): Computers have a memory hierarchy.


2. Primary Memory (Main Memory): This is fast memory directly accessible by the CPU. It includes:
◦ RAM (Random Access Memory): Volatile memory that holds both program instructions and
data while the computer is on 17 . For instance, when you launch an application, its code and
data are loaded into RAM. If power is lost or the computer is turned off, RAM is cleared (its
contents are wiped) 17 . RAM is faster than any secondary storage, which is why active
programs run from it 18 .
◦ ROM (Read-Only Memory): Non-volatile memory; its contents persist without power 19 . It
typically holds permanent programs, like the bootstrap loader or firmware. You can read from
ROM but generally not overwrite it in normal operation. ROM is slower and more limited than
RAM.
◦ Cache: A tiny, very high-speed memory placed between the CPU and RAM 20 . Since the CPU
is much faster than RAM, the CPU would often idle waiting for data from RAM. Cache stores
copies of frequently or recently accessed data from RAM, reducing the need to fetch from
slower main memory 20 . On a memory access, the CPU first checks the cache; if the needed
data is present (a cache hit), it reads from cache. Otherwise, it reads from RAM (a cache miss),
loads that data into the cache, and then proceeds. Cache speeds up processing by reducing
average access time 20 .

3. Secondary Memory (Storage): Non-volatile storage for the long term. Examples include Hard Disk
Drives (HDDs), Solid State Drives (SSDs), CDs/DVDs, flash drives, etc 21 . Secondary storage holds
programs and data permanently (until overwritten). It is slower than RAM but has much larger
capacity. The CPU cannot directly operate on secondary storage; data must be loaded into RAM first.
For instance, when you open a file from an HDD, the OS reads it into RAM so the CPU can work with
it.

◦ Important: Data in secondary memory is safe even when the power is off. For example, files
on a hard disk stay intact after shutdown. SSDs are newer secondary devices that are faster
than HDDs and have no moving parts.

4. Buses: Internal wires that connect CPU to memory and I/O devices. There are generally three kinds
of buses:

5. Data Bus: Carries actual data being transferred.


6. Address Bus: Carries the addresses specifying where data should be read from or written to.
7. Control Bus: Carries control signals (e.g., read/write signals) sent by the CU to coordinate
operations.
Think of buses as highways for data and signals inside the computer 22 . For example, when the
CPU fetches data from memory, it places the address on the address bus, the memory places the
data on the data bus, and the control bus has signals indicating a read operation.

2
How the CPU Works Together
When a program runs, these steps occur repeatedly: 23 24

1. Fetch: The Control Unit (CU) reads the address of the next instruction from the Program Counter
into the MAR, sends a read signal on the control bus, and retrieves the instruction from main
memory into the MDR. Then the instruction is copied into the Current Instruction Register (CIR).
2. Decode: The CU interprets the bits of the instruction in the CIR, determining what operation is
needed and what data/registers are involved. It sets up the ALU or other hardware accordingly.
3. Execute: The ALU or relevant unit performs the required operation (e.g., ALU adds numbers,
compares values, logical AND, etc.). Intermediate values are used from and stored into registers.
4. Store Results: The ALU’s result is often placed into the Accumulator or another register, and may be
written back to memory via MDR/MAR if needed.
5. Repeat: The cycle repeats for the next instruction.

In summary, CU controls (fetches/decode/send signals), ALU calculates, and Registers store 25 26 . This
continuous loop – “fetch–decode–execute” – is how any program (even a simple print command) runs on the
CPU 6 24 .

Data Storage Details


• Memory Units: Computer memory is counted in bytes (8 bits). For example, 1 KB = 1024 bytes, 1 MB
= 1024 KB, up to GB, TB, etc 5 .
• Data Deletion and Recovery: Deleting files on a computer doesn’t immediately erase the data bits;
it usually just marks the space as free 27 . In other words, after deletion, the file’s directory entry is
removed but the actual bits remain until overwritten. This is why deleted data can often be
recovered if not yet reused. Due to this, accidents or malicious deletions pose security risks. To
protect data:
• Recovery: Tools can recover recently deleted files as long as the data hasn’t been overwritten 27 .
• Security: Prevent unauthorized deletion by using user passwords, access controls, and encryption
28 . For example, encrypting files or requiring login credentials helps protect against unauthorized

or accidental loss 28 .

Software Categories
Hardware needs software to work. Software is intangible instructions and data (called a softcopy) that run
on hardware to perform tasks 1 . Once printed or output to paper, it becomes a hardcopy 2 .

Roles of Software:

• System Software: Manages and interfaces with hardware. It provides basic functionality and
services so other programs can run 29 . The most fundamental system software is the Operating
System (OS) 30 . An OS (like Windows, Linux, macOS, Android) bootstraps the machine, manages
resources, handles file operations, and provides a user interface. Without an OS, you cannot run
applications effectively 30 . Other system software includes:

3
• Device Drivers: Specialized programs (drivers) tell the OS how to communicate with hardware
devices (keyboard, printer, graphics card). They translate generic OS commands to device-specific
actions (and vice versa).

• Utilities: Tools for system maintenance (disk defragmenter, antivirus, backup tools, format utility,
etc.) 31 . Some come with the OS; others (like third-party antivirus) improve performance or security.

• Programming Tools: These include compilers, interpreters, assemblers, and IDEs that developers
use to write and test code. They are often system-level software but not directly used by end-users.
For example, Python itself is a programming tool (interpreter).

• Application Software: Programs that perform specific user tasks 2 . These run on top of the
operating system to solve problems or entertain users. Examples: word processors (MS Word),
spreadsheet (Excel), games, web browsers, photo editors (Paint, GIMP) 2 . Application software
relies on system software to access hardware.

In short: Software makes hardware useful, acting as the interface between humans and the machine 32 .
Hardware is the visible machine components, and software is the collection of instructions (hidden) that tell
that hardware how to operate 33 32 . Together, they complete every computing task.

Key Points to Remember (Chapter 1): - CPU components: Control Unit (CU) controls; Arithmetic Logic Unit
(ALU) calculates; Registers store data temporarily 13 24 .
- Fetch–Execute Cycle: The CPU continuously fetches, decodes, executes, and stores results of instructions 6
24 .

- Memory types: - RAM: Volatile primary memory (fast, lost on power-off) 17 . - ROM: Non-volatile primary
memory (read-only, holds firmware) 19 . - Cache: Very fast buffer between CPU and RAM for frequently
used data 20 . - Secondary Storage: Non-volatile (HDD/SSD) for long-term, slower, cannot be accessed
directly by CPU 34 .
- Data deletion marks space free; data remains until overwritten 27 .
- Software vs Hardware: - Software = intangible instructions/data; Hardware = physical components 33 .
- System software (OS, drivers, utilities) runs hardware; application software runs user tasks 29 30 .

Watch Out:
- Never confuse the Control Unit (CU) with the ALU: CU controls execution (fetch/decode/issue signals),
while ALU performs math/logic 8 11 .
- Accessing a memory location directly (e.g. secondary storage) by the CPU isn’t possible; data must first be
in RAM.
- Deleting a file doesn’t erase its contents immediately 27 (use secure deletion for confidentiality).

Chapter 2: Python Fundamentals


Python is a high-level, interpreted programming language widely used for teaching and real-world
development. Unlike C or Java, Python emphasizes readability and uses indentation to structure code.
Python programs can be run interactively (typing commands one-by-one in a REPL) or as scripts (running a
.py file) 35 .

4
Variables and Data Types
• Variables: In Python, a variable is a name that refers to a value stored in memory 36 . You do not
need to declare a variable before using it. A variable is automatically created when you first assign to
it 37 . For example:

age = 18
name = "Alice"

Here, age is created and assigned the integer 18, and name is assigned the string "Alice" .
Variables in Python are case-sensitive ( Age and age are different) and can be overwritten with
new values of possibly different types. The variable x can later be assigned a string instead of a
number.

• Data Types: Each value has a type. Common built-in types include:

• Integer ( int ): Whole numbers (e.g., 0, 42, -7).


• Floating-Point ( float ): Decimal numbers (e.g., 3.14, -0.001).
• Boolean ( bool ): Logical values True or False .
• String ( str ): Sequence of characters, enclosed in quotes 38 . Python does not have a separate
character type; a single character is just a string of length 1 38 .
• List: Ordered, mutable collection of items (e.g., [1, 2, 3] , or ["apple", "banana"] ). Lists
can hold mixed types too. They are defined with square brackets 39 40 .
• Dictionary ( dict ): Unordered (as of Python 3.7, insertion-ordered) collection of key:value pairs
41 . Defined with braces, e.g. {"name": "Bob", "age": 25} . Keys are unique and used to look
up associated values.
• Tuple: Like a list, but immutable (cannot be changed after creation). Defined with parentheses ( ) .
• Set: Unordered collection of unique items, defined with curly braces (e.g., {1, 2, 3} ), useful for
membership tests and removing duplicates.
• None: A special type representing “no value”.

Core Definition: For example, Python variables reserve memory to store values 36 . You can store integers,
decimals, or strings in variables and change them freely.

• Type Checking and Conversion: You can check a variable’s type with type(x) . Python is
dynamically typed: the same variable can hold different types over time. You can convert between
types using built-in functions:
• int(x) converts to integer (if possible),
• float(x) to float,
• str(x) to string, etc.
For example, int("100") yields the integer 100.

Example:

5
x = 10 # x is an integer
x = "hello" # now x is a string
y = 3.5 # a float
print(type(x), type(y))

This prints <class 'str'> <class 'float'> , showing the current types.

Watch Out: Using the wrong type can cause runtime errors (e.g., adding a string to an integer without
conversion). Always be mindful of the data type you need.

Basic Operations and Expressions


Python supports standard operators on data:

• Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division producing


float), // (integer division), % (modulus for remainder), ** (exponentiation).
Example: 3 + 5 == 8 , 10 % 3 == 1 , 2**3 == 8 .
• Comparison Operators: == , != , > , < , >= , <= . These produce boolean results. E.g., 5 > 3
is True .
• Logical Operators: and , or , not for combining boolean expressions. Example: (x > 0) and
(x < 10) .
• Assignment Operators: = assigns a value to a variable (e.g., x = 5 ). There are compound forms
like x += 1 (increment).
• Other Operators: in (membership), is (identity), etc., used later.

Under the Hood: When you write an expression like a = b + c , Python evaluates the right side ( b + c ),
then stores the result into the variable on the left ( a ) 36 .

Example (with syntax breakdown):

result = (value1 + value2) * 2


# breakdown: result ← expression (value1 + value2) * 2

- value1 and value2 are variables or values.


- (value1 + value2) adds them.
- The result is multiplied by 2.
- Finally, the variable result is assigned this final value.

Watch Out: Operator precedence matters. For example, multiplication * happens before addition + ,
unless parentheses override. Always use parentheses if unsure: e.g., a + b * c is a + (b * c) , not
(a + b) * c .

6
Input/Output and Comments
• Input: Use input() to read a line from the user (always returns a string). Example:

name = input("Enter your name: ")


age = input("Enter your age: ")
print("Hello,", name, "! You are", age, "years old.")

By default, input() returns text; to get numbers, convert the string: age = int(input(...)) .

• Output: Use print() to display data. E.g., print("Sum =", x+y) . print can output multiple
items separated by spaces.

• Comments: Use # to start a comment. Everything after # on that line is ignored by Python. Good
for explaining code. For example:

total = price * quantity # multiply price by quantity for total cost

Comments make code more readable.

Control Flow: Conditions and Decisions


Programs often need to make decisions based on conditions. Python provides if , elif , and else
statements for this.

• if Statement: Executes a block of code if a condition is true. Syntax:

if condition:
# code to run if condition is true

Example:

temperature = 25
if temperature > 30:
print("It's hot outside")

This prints nothing because 25 > 30 is false.

• if-else Statement: Includes an alternative path. Syntax:

7
if condition:
# if true
else:
# if false

Example:

age = 18
if age >= 18:
print("You are eligible to vote")
else:
print("You are not eligible to vote")

Here, age >= 18 is true, so it prints "You are eligible to vote".

• elif (Else If): For multiple conditions. Syntax:

if cond1:
...
elif cond2:
...
else:
...

Example:

score = 75
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print("Grade =", grade)

This checks each condition in order and picks the first true one.

8
Under the Hood: Python evaluates conditions in order. Once a true condition is found, its block is executed
and the rest are skipped.

• Boolean Logic in Conditions: Conditions can use logical operators ( and , or , not ):
Example: if (x > 0) and (x < 10): checks if x is between 1 and 9. Or if not done:
checks if done is False .

Example: If-Else with Syntax Explained

x = 7
if x % 2 == 0: # condition: is x divisible by 2?
print(x, "is even")
else: # if not (i.e., x is odd)
print(x, "is odd")

- x % 2 == 0 tests divisibility.
- If true, the indented block under if runs.
- Otherwise, the block under else runs.

Watch Out: - Always indent the blocks correctly (usually 4 spaces) or Python will error. For example, code
under if must line up consistently. - Comparison for equality is == , not = . Using = in a condition is a
syntax error. - Order of elif and else matters: elif checks extra conditions, else catches all
remaining cases (and must come last, with no condition).

Loops: Repetition
Loops let us execute code multiple times. Python has two main loop types:

• for Loop: Iterates over items in a sequence (like a list, string, or range of numbers).
Syntax:

for item in sequence:


# code using item

Example (iterating a list):

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

This prints each fruit on a separate line. Under the hood, Python takes each element of fruits in
order and assigns it to fruit , then runs the loop body.

Example (using range ):

9
for i in range(5): # range(5) generates 0,1,2,3,4
print(i, "squared is", i*i)

Prints squares of numbers 0 to 4.

• while Loop: Repeats as long as a condition is true. Syntax:

while condition:
# code to repeat

Example:

count = 0
while count < 3:
print("Count is", count)
count = count + 1

This loop runs with count=0,1,2. When count becomes 3, count < 3 is false and the loop stops.

Under the Hood: Each time through the loop, Python checks the condition. If true, it executes the loop body
and then checks again. Once false, it exits.

• Loop Control (break, continue):


• break : Immediately exits the innermost loop. For example, in for x in ...: if x == 5:
break stops the loop when x is 5 42 .
• continue : Skips the rest of the loop body and immediately re-tests the loop condition for the next
iteration 43 .
Example:

for n in range(1, 6):


if n == 3:
continue # skip when n is 3
print(n)

This prints 1,2,4,5 (skips printing 3).


• pass : A no-operation placeholder (does nothing; used when syntax requires a statement but you
don’t want action) 44 .

Multi-Scenario Examples:
1. Simple for loop:

10
for c in "Python":
print(c) # prints each character P, y, t, h, o, n

2. Nested loops (real-world):

# Matrix multiplication example (2x2 matrices)


A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
result = [[0,0],[0,0]]
for i in range(2):
for j in range(2):
for k in range(2):
result[i][j] += A[i][k] * B[k][j]
print(result) # [[19, 22], [43, 50]]

Here, loops are nested to compute the product of two matrices.


3. While loop with break:

x = 10
while True:
print(x, end=' ')
x -= 2
if x <= 0:
break

This prints 10 8 6 4 2 0 and stops when x becomes 0 or negative.

Watch Out:
- Risk of infinite loops: If a while condition never becomes false (e.g. forgetting to increment a counter),
the program will loop forever.
- Off-by-one errors: In for i in range(n) , i goes from 0 to n-1. Make sure to set the correct range
limit.
- Indentation errors: Indentation defines loop bodies. Mistakes here cause syntax errors.

Python Strings
Definition: A string is a sequence of characters (letters, digits, symbols) enclosed in quotes 38 . It can be in
single quotes '...' or double quotes "..." – Python treats them the same 45 . Triple quotes
( '''...''' or """...""" ) define multi-line strings 46 . Internally, Python stores strings as immutable
sequences of Unicode characters 47 38 .

• Core Properties: Python strings are immutable: once created, their contents cannot be changed 48 .
Any “change” creates a new string.

11
• Indexing: Like a list of characters, you can access characters by index with str[index] 49 50 .
Indexing starts at 0 for the first character. Negative indices count from the end: -1 is the last
character 50 .
Example:

s = "Hello"
print(s[0]) # prints 'H'
print(s[-1]) # prints 'o'

Out-of-range indices or non-integer indices raise errors (e.g., s[100] or s[2.5] will crash) 51 .

• Slicing: You can extract substrings using str[start: end] . This gives characters from index
start up to (but not including) end 52 . Examples:

text = "GeeksforGeeks"
print(text[1:5]) # 'eeks' (1,2,3,4)
print(text[:3]) # 'Gee' (start defaults to 0)
print(text[3:]) # 'ksforGeeks' (end defaults to end of string)
print(text[::-1]) # 'skeeGrofskeeG' (step -1 reverses the string)

Slicing does not modify the original string; it produces a new one.

• Common Methods: There are many built-in string methods. For instance:

• len(s) returns length.


• [Link]() , [Link]() : return new strings converted to upper/lower case 53 .
• [Link]() : trims whitespace from ends.
• [Link](sub) : returns index of substring (or -1 if not found) 54 .
• [Link](old, new) : returns a new string with all occurrences of old replaced by new .
• [Link](delim) : splits the string into a list of parts by the delimiter.

Example (upper/lower):

t = 'PyThOn'
print([Link]()) # prints 'python'
print([Link]()) # prints 'PYTHON'

The original t remains unchanged (strings are immutable) 53 .

• Concatenation and Repetition: Use + to join strings, and * to repeat:

a = "Hello"
b = "World"

12
print(a + " " + b) # "Hello World"
print(a * 3) # "HelloHelloHello"

• Format Strings: You can embed values using f-strings (Python 3.6+) or the % operator or
format() method. Example f-string:

name = "Alice"
print(f"Hello, {name}!") # prints "Hello, Alice!"

Examples:
1. Indexing:

word = "Python"
print(word[0], word[2], word[-1])
# Output: P t n

2. Immutability:

s = "cat"
# s[0] = 'b' # ERROR: strings are immutable!
s = 'b' + s[1:] # create a new string "bat"
print(s)

3. Loop through string:

for ch in "IP Class":


print(ch, end=' ')
# Output: I P C l a s s

Watch Out:
- Strings are immutable 48 : operations like concatenation or replacement create new strings. You cannot
do something like str[0] = 'x' .
- Always use quotes correctly. Mismatched quotes cause syntax errors. To include a quote inside a string,
use the other kind of quote or escape it (e.g. "He said \"Hi\"" ).
- Remember that operations like slicing or + produce new strings; the original remains unchanged.

Python Lists
A list is an ordered, mutable collection of items 55 40 . Lists can hold any data type, even mixed together.
They are defined with square brackets.

13
Key Points about Lists:
- Order & Indexing: Items have a fixed order. The first item has index 0. E.g., ["apple", "banana",
"cherry"] has "apple" at index 0, "banana" at 1, etc 40 .
- Mutable: You can change, add, or remove elements after creation 56 . For example, mylist[1] =
"orange" changes the second item; append() , insert() , pop() , remove() are common
methods to modify lists.
- Allow Duplicates: Lists can have duplicate values; each has its own index 57 . E.g.,
["apple","banana","apple"] is allowed.

Examples:

fruits = ["apple", "banana", "cherry"] # Create list


print(fruits[0]) # "apple"
[Link]("date") # Add item at end
print(fruits) # ["apple", "banana", "cherry", "date"]
fruits[1] = "blueberry" # Change item
print(fruits) # ["apple", "blueberry", "cherry", "date"]

• Length: Use len(fruits) to get number of items 58 .


• Built-in list functions: list() to convert an iterable to a list; min() , max() , sum() work on
numeric lists; sorted() returns a sorted copy.

Iterating through a list:

for item in fruits:


print(item)

Watch Out:
- Index-out-of-range error if you access beyond list ends.
- Remember list slicing: works similarly to strings (e.g. fruits[1:3] gives a sublist).

Python Dictionaries
A dictionary is a collection of key:value pairs 59 . Each key in a dictionary maps to a value. For example,
{"name": "Bob", "age": 30} stores two pairs. Dictionaries are written with curly braces {} and are
unordered (as of Python 3.7, they preserve insertion order but conceptually think of them as look-up
tables).

• Keys: Must be unique and immutable types (often strings or numbers).


• Values: Can be any Python object (number, string, list, another dict, etc.).
• Mutable: You can add, update, or delete entries. Example: d["age"] = 31 changes the value for
"age" .

Core Definition: In Python, a dictionary is an unordered, changeable collection of key–value pairs 59 .

14
Examples:

student = {"name": "Alice", "age": 21, "grade": "A"}


print(student["name"]) # Alice
student["age"] = 22 # update value
student["major"] = "CS" # add new key:value
print([Link]("grade")) # "A" (safe access)
del student["grade"] # remove key:value
print(student) # {'name': 'Alice', 'age': 22, 'major': 'CS'}

• Access: dict[key] returns the value for that key (KeyError if absent), or use [Link](key,
default) which returns None or a default if key not found.
• Traverse: You can loop through a dictionary’s keys, values, or items:

for k in [Link]():
print(k, student[k])
for v in [Link]():
print(v)
for k,v in [Link]():
print(k, "=>", v)

• Built-ins:
• len(dict) gives number of pairs.
• [Link]() , [Link]() , [Link]() return views of keys, values, and (key,value)
pairs respectively.
• update() : merge another dict in.
• clear() : remove all items.

Watch Out:
- Keys are case-sensitive ( "age" vs "Age" ).
- If you try to access a non-existent key with dict[key] , you get an error. Use get() if uncertain.
- Order: In very old Python (<3.6), dicts were truly unordered; nowadays insertion order is preserved, but
don’t rely on it for logic.

Python Control Structures Summary


• if / elif / else: Use these for conditional execution. Conditions must evaluate to True/False.
• for loops: Great for iterating through lists, ranges, strings, etc.
• while loops: Good when you need a loop with a condition that is checked each iteration.

Indentation is syntactically significant. All code blocks under if , for , etc., must be indented. Typically
use 4 spaces. For example:

15
for i in range(3):
print(i) # This is inside the loop
print("Done") # Not inside loop (no indentation)

Points to Remember (Python Basics):


• Python is dynamically typed: variables are created by assignment 37 .
• Strings are immutable sequences of characters 38 48 .
• Use == for comparison, not = .
• Lists: ordered, indexed, mutable 40 .
• Dictionaries: key–value maps, keys unique 59 .
• Indentation matters: inconsistent indenting causes IndentationError .
• Always close quote marks, brackets, and parentheses.

Chapter 3: Python Flow Control and Loops


Building on the basics, here we delve deeper into decision-making and loops, with syntax and examples.

if / elif / else Statements


Core Definition:
- if checks a condition (a boolean expression). If it’s true, the indented block under if runs.
- elif (short for “else if”) checks another condition if previous if was false.
- else catches all other cases if none of the above conditions were true.

Syntax Breakdown:

if condition1:
# (code block A) runs if condition1 is True
elif condition2:
# (code block B) runs if condition1 False AND condition2 True
else:
# (code block C) runs if neither condition1 nor condition2 is True

Each condition is a boolean expression (e.g., x > 5 , s == "yes" , n % 2 == 0 , etc.).

Example 1 (Simple if-else):

x = 7
if x % 2 == 0: # Check if x is even
print(x, "is even")

16
else:
print(x, "is odd")

- If x is divisible by 2 ( x % 2 == 0 ), prints "x is even", else prints "x is odd".

Example 2 (if-elif-else):

score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print("Grade =", grade)

This assigns a letter grade based on score . The conditions are checked in order; the first true branch is
taken.

Watch Out:
- Only the first true branch executes. Once a condition is satisfied, Python skips the rest of the chain.
- Indentation marks the scope of each block. Mixing tabs and spaces or incorrect indentation levels causes
errors.
- Forgot elif : If you need multiple alternatives, use elif ; chaining multiple if blocks will cause all to
be tested separately (not mutually exclusive).

Loops (Detailed)

for Loop

Definition: Repeats a block for each item in a sequence (list, string, range, etc.) 60 . Use it when you know
(or want to process) each element of an iterable.

Syntax:

for variable in sequence:


# code block (loop body)

variable takes each value from sequence in turn.

Example A: Iterate through a list:

17
colors = ["red", "green", "blue"]
for col in colors:
print("Color:", col)

Output:

Color: red
Color: green
Color: blue

Here, col successively becomes "red" , then "green" , then "blue" .

Example B: Use range() to iterate numbers:

for i in range(1, 6): # 1 to 5 inclusive


print("i =", i)

Output:

i = 1
i = 2
i = 3
i = 4
i = 5

range(1, 6) generates 1,2,3,4,5. If you use range(5) , it goes 0–4.

Nested for Loop Example: (Matrices multiplication – illustration of loops within loops)

# Multiply 2x2 matrices


A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
# Initialize result with zeros
result = [[0,0],[0,0]]
for i in range(2):
for j in range(2):
for k in range(2):
result[i][j] += A[i][k] * B[k][j]
print(result) # [[19, 22], [43, 50]]

This shows three nested loops (for i, j, k) to compute matrix product. Each for loop controls one
dimension of the computation.

18
Watch Out (for loops):
- The loop variable ( col , i , etc.) is re-assigned each iteration.
- If you modify the list while iterating (e.g., remove items from it inside the loop), results can be
unpredictable; avoid that or iterate over a copy.
- By default, loops run to completion. Use break or continue to alter flow (see below).

while Loop

Definition: Repeats a block as long as a condition remains true 61 . Use when you don’t know in advance
how many times to loop, but have a test condition.

Syntax:

while condition:
# code block (loop body)
# (must eventually make condition false, else infinite loop)

Example:

n = 1
while n <= 5:
print(n)
n = n + 1

Output:

1
2
3
4
5

Here the loop runs while n <= 5 . Each time we increment n . When n becomes 6, the condition fails
and the loop stops.

Another example (practical):

password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted.")

This keeps asking until the user types "secret".

19
Watch Out (while loops):
- Infinite Loop Danger: If condition never becomes false (e.g., you forget n = n + 1 ), the loop runs
forever. Always ensure the condition will eventually fail.
- If you really need to break early on some condition, use a break inside (see control below).

Loop Control Statements

As noted from the tutorials 42 44 :

• break: Immediately exit the nearest loop.

for i in range(10):
if i == 5:
break # exit loop when i is 5
print(i)
# prints 0 1 2 3 4 and then stops

• continue: Skip the rest of this iteration and return to the top of the loop.

for i in range(6):
if i % 2 == 0:
continue # skip even numbers
print(i)
# prints 1 3 5

• pass: Does nothing (a placeholder). Syntactically valid where a statement is required but no action is
needed. For example:

for x in range(5):
if x < 2:
pass # placeholder
else:
print(x)
# prints 2 3 4

(Here pass is redundant, just shows usage. Often used in function/class stubs).

Watch Out (control):


- Misplacing break or continue outside loops causes errors.
- Using break in nested loops only breaks the innermost loop.

20
Chapter 4: Python Collections – Strings, Lists,
Dictionaries (Advanced)
Building on previous sections, here we delve further into common data structures with examples and
pitfalls.

Strings (Review and Methods)


Strings we covered basics; here are more operations:

• Indexing & Slicing: Characters can be accessed and substrings extracted with the same syntax as
lists 62 52 . Multi-line strings (with ''' or """ ) preserve newlines automatically 46 .

• Escape Sequences: Use a backslash \ for special characters. E.g., \n for newline, \t for tab 63 .
To include quotes in strings, either use the other quote type or escape: "He said \"Hi\"" or
'He said \'Hi\'' .

• String Concatenation and Repetition: + and * operators work as noted 64 .

• Membership Tests: 'a' in s returns True if 'a' occurs in s . 'abc' not in s similarly
tests absence.

• Formatting:

• Old style % formatting: E.g., "%s is %d years old" % (name, age) . Placeholders %s ,
%d , etc. refer to string, integer, float, etc. 65 .
• format() method: E.g., "{} loves {}".format("Alice","Bob") .

• f-strings (Python 3.6+): Put f before quotes and use {} inside. (Example above.) These allow
embedding variables into strings cleanly.

• Common Methods: A few highlights (many are listed in [31] and [28]):

• .split(sep) : split into list on separator.


• .join(list) : join list of strings into one string, inserting the original string between items.
• .replace(old, new) : replace substrings.
• .startswith(prefix) / .endswith(suffix) : check start/end.
• .upper() , .lower() , .title() , .capitalize() , .swapcase() : change case 53 .

• .find(sub) vs .index(sub) : find returns -1 if not found; index raises an error 54 .

• Examples (methods):

21
s = " Hello, World! "
print([Link]()) # "Hello, World!"
print([Link]("World","Python")) # " Hello, Python! "
parts = [Link](",")
print(parts) # [' Hello', ' World! ']
print("-".join(["A","B","C"])) # "A-B-C"

Lists (In-Depth)
We introduced lists; more details:

• Access & Modify: You can index or slice lists. To change an element, assign to an index (unlike
strings). E.g., fruits[1] = "kiwi" 56 .
• Add/Insert:
• .append(x) : add item x at end.
• .insert(i, x) : insert x at index i , shifting later elements right.
• .extend([a,b]) : append elements from another list.
• Remove:
• .pop(i) : remove and return item at index i (default last).
• .remove(x) : remove first occurrence of value x .
• del list[i] : delete by index.
• Sorting & Reversing:
• .sort() : sorts the list in-place (only if elements are comparable, e.g. all numbers or all strings)
(ascending by default).
• sorted(list) : returns a new sorted list, leaving original.

• .reverse() : reverses the list in-place.

• Example:

numbers = [3, 1, 4, 1, 5]
[Link](9) # [3,1,4,1,5,9]
[Link]()
print(numbers) # [1,1,3,4,5,9]

• Iterating through List (with index):


Sometimes you want both index and value. Use range(len(list)) or enumerate() .
Example with enumerate :

for idx, val in enumerate(numbers):


print(f"Index {idx} -> {val}")

22
Watch Out:
- When using .remove(x) , if x is not in the list, Python raises a ValueError.
- [Link](x) finds the first index of x, else error.
- Avoid modifying a list while iterating over it (e.g., removing elements in a loop) – it can skip elements or
cause errors. If needed, iterate over a copy ( for x in list[:] ).

Dictionaries (In-Depth)
We gave basic examples. Further details:

• Creating & Updating: Besides direct literal {} , you can use dict() constructor. Example:

info = dict(name="Alice", age=21)

• Accessing Safely:
• [Link](key, default) returns default (or None ) if key not present, instead of an
error. Useful for checking if key exists.
• Iterating: Covered earlier ( .items() , .keys() , .values() ).
• Common Methods:
• keys() , values() , items() return view objects (which can be turned into lists if needed).
• update(other_dict) : merges another dictionary’s key-values into this one. E.g.
[Link]({"age":22, "major":"CS"}) .
• pop(key) : remove and return value for key.
• clear() : empties the dictionary.

Watch Out:
- Keys must be immutable (numbers, strings, tuples, but not lists or dicts).
- Trying to modify a key (e.g. mydict[3] = ... vs. del mydict[3] ) – the latter is delete.
- Large dictionaries use more memory than lists for same number of items due to hashing overhead.

Chapter 5: Functions and Modules (Python)


Functions let you encapsulate code for reuse. Python has built-in functions (e.g., len() , print() ) and
you can define your own.

• Defining Functions: Use def keyword.


Syntax:

def function_name(parameters):
"""Optional docstring: describes what the function does."""
# code block
return value # optional

Example:

23
def add(a, b):
"""Return the sum of a and b."""
return a + b

result = add(3, 5) # result is 8

• Parameters/Arguments: Variables in parentheses are parameters (inputs). When calling, you


supply arguments.

• Return: return sends a result back. If omitted, function returns None .

• Scopes: Variables defined inside a function are local to that function. Parameters and variables
declared there do not affect variables outside.

• Example (multi-scenario):

def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice") # Hello, Alice!


greet() # Hello, Guest! (uses default)

• Recursive Functions: A function can call itself to solve smaller sub-problems. For example,
calculating factorial:

def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5)) # 120

Watch Out: Recursion must have a base case; otherwise it leads to infinite recursion.

• Modules: Python allows grouping functions into modules (.py files). You can import modules using
import module_name or from module import func . Standard library modules include
math , random , etc.

Watch Out:
- Indentation inside function defines its body.
- return exits the function immediately. Code after return in the function is not executed.

24
Chapter 6: File Handling in Python
Python can read/write files for persistent data.

• Opening Files: Use open(filename, mode) where mode is 'r' (read), 'w' (write, overwrite),
'a' (append), 'r+' (read/write), etc.

• Reading:

f = open("[Link]", "r")
text = [Link]() # read entire file into a string
[Link]()

Or line by line:

with open("[Link]", "r") as f:


for line in f:
print([Link]())

Using with ensures automatic closing.

• Writing:

f = open("[Link]", "w")
[Link]("Hello, world!\n")
[Link]()

Append mode 'a' adds to end without erasing content.

• Working with CSV: A CSV is a text file with comma-separated values. Python’s csv module helps
parse it. Example:

import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)

Watch Out:
- Always close files ( [Link]() ), or better use with to auto-close.
- Writing mode 'w' erases existing file content. Use 'a' to preserve existing data.

25
Chapter 7: Data Visualization (Python Libraries)
Python has powerful libraries for plotting.

• Matplotlib: A core library for 2D plots. The pyplot interface is used for charts.
Example:

import [Link] as plt


x = [1,2,3,4,5]
y = [2,3,5,7,11]
[Link](x, y, marker='o')
[Link]("Example Plot")
[Link]("x axis")
[Link]("y axis")
[Link]()

• Other libraries: Seaborn (statistical plots), pandas (dataframes with built-in plot), etc.

Visualizing data helps with analysis (e.g., histograms, scatter plots). Each library has its syntax, but all
require turning data (lists, arrays) into charts.

(For IB/IP focus, detail here is optional; emphasis is usually on knowing the concepts, not library syntax.)

Chapter 8: Introduction to Databases and SQL


A Database is a structured collection of data. A DBMS (Database Management System) like MySQL or
SQLite lets us define databases, tables, and query them.

• Relational Model: Data organized in tables (relations). Each table has rows (tuples) and columns
(attributes).
• Key Terms:
• Tuple: a row in a table (one record).
• Attribute: a column (one field, like “Name” or “Age”).
• Domain: the set of allowed values for an attribute (e.g., integer 1-100).
• Keys:
◦ Primary Key: a minimal column (or combination) that uniquely identifies each tuple. E.g.,
StudentID in a student table.
◦ Candidate Key: any column (or set of columns) that can serve as a unique identifier (primary
key is one candidate).
◦ Alternate Key: a candidate key not chosen as primary.
◦ Foreign Key: a field in one table that matches the primary key of another table, used to link
tables.

26
A quote-style definition: A table is formally a set of tuples over defined domains. Each attribute has a domain
(the type/range of values) and each row satisfies those domains. The primary key enforces entity
uniqueness.

Structured Query Language (SQL)


SQL is used to manage and retrieve data from relational databases. Some key commands:

• DDL (Data Definition Language): Define database structures.


• CREATE DATABASE dbname; creates a new database.
• DROP DATABASE dbname; deletes it.
• CREATE TABLE table_name (col1 TYPE, col2 TYPE, ...);
• ALTER TABLE table_name ADD COLUMN newcol TYPE; or DROP COLUMN .

• DROP TABLE table_name; deletes a table.

• DML (Data Manipulation Language): Insert, query, update, and delete data.

• INSERT INTO table_name (col1, col2) VALUES (val1, val2); adds a row.
• SELECT ... FROM ... WHERE ...; retrieves data.
• UPDATE table_name SET col = newval WHERE condition; modifies existing rows.

• DELETE FROM table_name WHERE condition; removes rows.

• Basic SELECT query: [18] “The SQL SELECT statement is used to retrieve data from one or more
tables 66 .”
Syntax: 67 :

SELECT column1, column2, ...


FROM table_name;

Example: SELECT name, age FROM Students; fetches the name and age columns for all rows.
Use SELECT * to get all columns.

• Filtering with WHERE: The WHERE clause filters rows to those meeting conditions 68 .
Syntax:

SELECT columns
FROM table
WHERE condition;

Example: SELECT * FROM Students WHERE age > 18; retrieves only students older than 18.
Conditions can use =, >, <, >=, <=, <> (not equal) 69 , and combine with AND , OR .
String comparisons require quotes, numeric do not 70 :

27
SELECT * FROM Customers WHERE Country = 'Mexico'; -- text in quotes 71
SELECT * FROM Customers WHERE CustomerID = 5; -- number without quotes
70

• ORDER BY: Sorts results. ORDER BY column [ASC|DESC] .

• GROUP BY and HAVING: Group rows on a column, often with aggregate functions like COUNT ,
SUM , AVG . HAVING filters groups. Example from [18]:

SELECT Country, COUNT(*) AS cust_count


FROM Customer
GROUP BY Country
HAVING COUNT(*) >= 2;

• JOINs: Combine rows from two or more tables based on related columns. (Inner, left, right joins, etc.)
Example:

SELECT [Link], Departments.dept_name


FROM Employees
INNER JOIN Departments ON Employees.dept_id = [Link];

• SQL Functions:
• Aggregates: COUNT(*) , SUM(col) , AVG(col) , MIN(col) , MAX(col) .
• String functions: e.g., UPPER() , LOWER() , LENGTH() .
• Date/time, numeric, etc.

Example SQL Queries:

1. Simple SELECT:

SELECT student_name, age


FROM Students;

2. SELECT with WHERE:

SELECT *
FROM Students
WHERE grade = 'A';

3. SELECT with multiple conditions (AND/OR):

28
SELECT name, salary
FROM Employees
WHERE salary > 50000 AND department = 'Sales';

4. INSERT example:

INSERT INTO Students (id, student_name, age)


VALUES (101, 'Alice', 20);

5. UPDATE example:

UPDATE Students
SET age = age + 1
WHERE id = 101;

6. DELETE example:

DELETE FROM Students


WHERE age < 18;

Watch Out:
- SQL keywords (SELECT, FROM, WHERE, etc.) are case-insensitive, but identifiers (table/column names) may
be case-sensitive depending on the database.
- Always use quotes around string literals in WHERE conditions 72 .
- Remember the semicolon ( ; ) ends an SQL statement in many systems.
- SELECT * is convenient but not efficient for large tables or production code (it fetches all columns).
Better list only needed columns.

Chapter 9: Integrating Python with Data


Python can work with databases and files:

• CSV and DataFrames: Use the csv module or Pandas for reading CSV files (comma-separated
values).
• Database Access: Python’s sqlite3 module or external libraries (like mysql-connector-
python ) allow executing SQL commands from Python:

import sqlite3
conn = [Link]('[Link]')

29
cursor = [Link]()
[Link]('SELECT * FROM Students WHERE age > 18;')
rows = [Link]()
for row in rows:
print(row)
[Link]()

• Visualization with Data: Data retrieved via SQL or files can be plotted using Matplotlib/pandas.

Chapter 10: Cyber Security and Emerging Trends


(While the syllabus has a small section on security and emerging IT fields, here is a brief overview.)

• Security Concerns (Hardware/Software):


• Data Protection: Use passwords, encryption, and backups to protect data from unauthorized
access/deletion 28 .

• Viruses/Malware: Install antivirus (system utility) to scan and remove harmful software 31 .

• Emerging Trends: (A brief mention)

• Artificial Intelligence (AI) & Machine Learning (ML): Computer programs that learn from data to
make decisions.
• Internet of Things (IoT): Everyday devices connected to the internet, collecting and exchanging
data.
• Cloud Computing: Using remote servers over the internet to store, manage, and process data.
• Big Data: Handling very large data sets that traditional databases struggle with.
• AR/VR (Augmented/Virtual Reality): Technologies that merge or simulate environments.

(Each of these fields leverages the core computing and programming concepts above and is worth
exploring in advanced studies.)

Summary of Key Concepts


• CPU: Contains ALU (calculations) and CU (control signals) 7 11 ; follows fetch-decode-execute cycle
6 .
• Memory: RAM (volatile, primary) vs ROM (non-volatile) vs Cache (very fast) 17 20 . Secondary
storage is permanent but slow 34 .
• Software: System software (OS, drivers) vs Application software (user apps) 29 2 .
• Python Basics: Variables store data types (int, float, str, list, dict, etc.) 36 59 . Strings are immutable
sequences 38 .
• Control Flow: if/elif/else for decisions; loops ( for over sequences, while with condition)
for repetition 8 42 .
• Data Structures: Lists (ordered, mutable) and dictionaries (key:value maps) are fundamental for
storing collections of data 40 59 .

30
• SQL: Used to query databases. Basic query is SELECT ... FROM ... [WHERE ...] 66 68 . DDL
(CREATE/DROP) defines tables; DML (INSERT, UPDATE, DELETE) modifies data.
• Integration: Python can manipulate files and databases (with modules like csv , sqlite3 ) to
build full applications.

This completes a detailed walk-through of all foundational topics for Class 11 Informatics Practices, with
definitions, “under-the-hood” insights, syntax breakdowns, multiple examples, and cautionary points.

1 2 3 4 5 17 18 19 20 21 27 28 29 30 31 32 33 34 [Link]
[Link]

6 7 10 12 14 15 16 22 23 Paper 1 Lesson 2.3 - CPU Architecture | Graded IB Computer Science Notes


[Link]

8 9 11 13 24 25 26 How the CPU Really Works: ALU, Control Unit, and Registers Explained |
RevisionDojo
[Link]

35 [Link]
[Link]

36 37 Python Variables
[Link]

38 46 48 50 51 52 62 Python String - GeeksforGeeks


[Link]

39 40 55 56 57 58 Python Lists
[Link]

41 59 Python | Count number of items in a dictionary value that is a list - GeeksforGeeks


[Link]

42 43 44 60 61 Python Loops
[Link]

45 47 49 63 64 65 Python Strings
[Link]

53 Python String Methods - GeeksforGeeks


[Link]

54 Python String Methods


[Link]

66 67 SQL SELECT Query - GeeksforGeeks


[Link]

68 69 70 71 72 SQL WHERE Clause


[Link]

31

You might also like