Chapter 1 - Introduction To Computer Systems
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 .
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.
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:
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 .
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).
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:
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.
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 .
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:
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:
if condition:
# code to run if condition is true
Example:
temperature = 25
if temperature > 30:
print("It's hot outside")
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")
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 .
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:
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.
9
for i in range(5): # range(5) generates 0,1,2,3,4
print(i, "squared is", i*i)
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.
Multi-Scenario Examples:
1. Simple for loop:
10
for c in "Python":
print(c) # prints each character P, y, t, h, o, n
x = 10
while True:
print(x, end=' ')
x -= 2
if x <= 0:
break
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:
Example (upper/lower):
t = 'PyThOn'
print([Link]()) # prints 'python'
print([Link]()) # prints 'PYTHON'
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)
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:
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).
14
Examples:
• 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.
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)
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
x = 7
if x % 2 == 0: # Check if x is even
print(x, "is even")
16
else:
print(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:
17
colors = ["red", "green", "blue"]
for col in colors:
print("Color:", col)
Output:
Color: red
Color: green
Color: blue
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
Nested for Loop Example: (Matrices multiplication – illustration of loops within loops)
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.
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted.")
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).
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).
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.
• 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\'' .
• 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]):
• 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.
• Example:
numbers = [3, 1, 4, 1, 5]
[Link](9) # [3,1,4,1,5,9]
[Link]()
print(numbers) # [1,1,3,4,5,9]
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:
• 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.
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
• 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}!")
• 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:
• Writing:
f = open("[Link]", "w")
[Link]("Hello, world!\n")
[Link]()
• 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:
• 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.)
• 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.
• 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.
• Basic SELECT query: [18] “The SQL SELECT statement is used to retrieve data from one or more
tables 66 .”
Syntax: 67 :
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
• GROUP BY and HAVING: Group rows on a column, often with aggregate functions like COUNT ,
SUM , AVG . HAVING filters groups. Example from [18]:
• JOINs: Combine rows from two or more tables based on related columns. (Inner, left, right joins, etc.)
Example:
• SQL Functions:
• Aggregates: COUNT(*) , SUM(col) , AVG(col) , MIN(col) , MAX(col) .
• String functions: e.g., UPPER() , LOWER() , LENGTH() .
• Date/time, numeric, etc.
1. Simple SELECT:
SELECT *
FROM Students
WHERE grade = 'A';
28
SELECT name, salary
FROM Employees
WHERE salary > 50000 AND department = 'Sales';
4. INSERT example:
5. UPDATE example:
UPDATE Students
SET age = age + 1
WHERE id = 101;
6. DELETE example:
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.
• 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.
• Viruses/Malware: Install antivirus (system utility) to scan and remove harmful software 31 .
• 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.)
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]
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]
39 40 55 56 57 58 Python Lists
[Link]
42 43 44 60 61 Python Loops
[Link]
45 47 49 63 64 65 Python Strings
[Link]
31