X Sa Xy CQitu ZXNBND

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Examination Reference Handbook

1. Printing Output:
Use the print() function to display messages.
Example: print("Hello, World!") will print:

Hello, World!

2. Variable Naming Rules:


Variable names cannot begin with a number.
Examples of valid names: my_variable , _data123 , value2 .
Invalid: 123variable .

3. Data Types and Input Handling:


Strings: Store sequences of characters, e.g., "Python" .
Input: The input() function always returns data as a string.
Example:

user_input = input("Enter your name: ")


print(f"Hello, {user_input}!")

4. String Manipulation:
Strings can be sliced using indexing.
Example: "Python Programming"[7:] returns "Programming" .

5. Operators:
Floor Division: // returns the largest whole number.
Example: 10 // 3 gives 3 .
Exponentiation: ** is used for power.
Example: 2 ** 3 gives 8 .

6. Loops:
For Loops: Ideal when the number of iterations is known.
Example:
for i in range(5):
print(i)

While Loops: Execute repeatedly as long as a condition is true.


Python doesn't support a native do-while loop, but it can be simulated using while True with a
break .

7. Functions:
Defined using the def keyword.
Example:

def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))

Functions without return default to returning None .

8. Lists:
Mutable: List elements can be changed.
Allow Duplicates:
Example:

my_list = [1, 2, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 2, 3, 4]

9. Tuples:
Immutable: Cannot be modified after creation.
Example:

my_tuple = (1, 2, 3)
print(my_tuple[1:3]) # Output: (2, 3)

10. Dictionaries:
Store key-value pairs for efficient data access.
Example:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice

11. Exception Handling:


Use try/except to handle errors safely.
Example:

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

12. List Comprehensions:


Create lists using concise syntax.
Example:

even_numbers = [x for x in range(10) if x % 2 == 0]


print(even_numbers) # Output: [0, 2, 4, 6, 8]

13. File Handling:


Opening and Closing Files
Basic file opening with open() and close() :

f = open("file.txt", "r")
content = f.read()
print(content)
f.close()

Using with for Safe File Handling


The with statement ensures files are closed properly after operations:

with open("file.txt", "w") as f:


f.write("Hello, World!")

Reading Entire Content


Read all content in a file at once using read() :
with open("file.txt", "r") as f:
content = f.read()
print(content)

Reading Line by Line


Reading each line of a file using a loop:

with open("file.txt", "r") as f:


for line in f:
print(line.strip())

Writing to a File
Writing text to a file using write() :

with open("file.txt", "w") as f:


f.write("This is a new line.\n")

Appending to a File
Adding text to the end of a file with append mode ( "a" ):

with open("file.txt", "a") as f:


f.write("This text is appended.\n")

Reading Specific Number of Characters


Using read(n) to read the first n characters of a file:

with open("file.txt", "r") as f:


content = f.read(5) # Reads first 5 characters
print(content)

14. Sorting Algorithms Overview:


Built-in Sorting Functions
Python provides in-built functions to sort lists and other iterable objects efficiently.
sorted() Function
Returns a new sorted list from the items in any iterable.
Example (Sort a list in ascending order):

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
Example (Sort in descending order using reverse=True ):

sorted_numbers_desc = sorted(numbers, reverse=True)


print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]

sort() Method
Sorts the list in place, modifying the original list directly.
Example (Sort list in ascending order):

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]

Example (Sort list in descending order):

numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]

Sorting with Custom Key


Both sorted() and sort() accept a key parameter for custom sorting.
Example (Sort strings by length):

words = ["apple", "banana", "cherry", "date"]


sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry']

Example (Sort list of dictionaries by a specific key):

students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 90},
{"name": "Charlie", "grade": 78}
]
sorted_students = sorted(students, key=lambda x: x["grade"])
print(sorted_students)
# Output: [{'name': 'Charlie', 'grade': 78}, {'name': 'Alice', 'grade': 85}, {'name

Bubble Sort
Repeatedly swap adjacent elements if they are in the wrong order.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr

Selection Sort
Find the smallest element and place it in sorted order.

def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr

Insertion Sort
Build a sorted array by inserting elements in the correct position.

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

15. Search Algorithms:


In-Built Search Functions
Python provides several in-built functions for efficient searching in lists, strings, and dictionaries.
Using in for Membership Testing
The in keyword is useful for checking if an element exists in a list, string, or any
iterable.
Example (Check if an element is in a list):
numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is found in the list")
else:
print("3 is not found in the list")

index() Method for Lists


The index() method returns the first index of a specified element in a list.
Example (Find the index of an element):

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


index = fruits.index("banana")
print("Index of banana:", index) # Output: 1

find() Method for Strings


The find() method returns the index of the first occurrence of a substring in a string. It
returns -1 if the substring is not found.
Example (Search for a substring):

text = "Hello, welcome to the world of Python"


index = text.find("welcome")
print("Index of 'welcome':", index) # Output: 7

count() Method
The count() method can count the occurrences of an element in lists or strings.
Example (Count occurrences in a list):

numbers = [1, 2, 3, 2, 2, 4, 5]
count_of_two = numbers.count(2)
print("Count of 2:", count_of_two) # Output: 3

Example (Count occurrences in a string):

text = "hello world"


count_of_l = text.count("l")
print("Count of 'l':", count_of_l) # Output: 3

Binary Search
Search efficiently in a sorted list by repeatedly dividing the range in half.
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

16. Vectors:
Vectors are mathematical objects with both magnitude (length) and direction, commonly used in
physics, computer graphics, and machine learning. Python provides powerful libraries, like numpy , to
work with vectors efficiently.

Magnitude
The magnitude (or length) of a vector represents the distance from its origin to its endpoint.
If we have a vector v = [x, y] in 2D, the magnitude is calculated as x2 + y 2 .

In Python, we can calculate the magnitude of a vector using numpy .


Example (Calculating Magnitude of a 2D Vector):

import numpy as np

vector = np.array([3, 4])


magnitude = np.linalg.norm(vector)
print("Magnitude of the vector:", magnitude) # Output: 5.0

Example (Calculating Magnitude of a 3D Vector):

vector_3d = np.array([1, 2, 2])


magnitude_3d = np.linalg.norm(vector_3d)
print("Magnitude of the 3D vector:", magnitude_3d) # Output: 3.0

Dot Product
The dot product (or scalar product) of two vectors measures the extent to which the vectors
are pointing in the same direction.
For two vectors a = [a1 , a2 , … , an ] and b = [b1 , b2 , … , bn ], the dot product is calculated
​ ​ ​ ​ ​ ​

as:
a ⋅ b = a1 ⋅ b1 + a2 ⋅ b2 + ⋯ + an ⋅ bn
​ ​ ​ ​ ​

If the dot product of two vectors is zero, they are perpendicular to each other.
Example (Calculating Dot Product in 2D):

vector_a = np.array([1, 2])


vector_b = np.array([3, 4])
dot_product = np.dot(vector_a, vector_b)
print("Dot product:", dot_product) # Output: 11

Example (Checking for Perpendicular Vectors):

vector_a = np.array([1, 0])


vector_b = np.array([0, 1])
dot_product = np.dot(vector_a, vector_b)

if dot_product == 0:
print("The vectors are perpendicular.")
else:
print("The vectors are not perpendicular.")
# Output: The vectors are perpendicular.

17. Matrices and Linear Algebra:


Identity Matrix
The identity matrix, denoted as I , is a square matrix with ones on the main diagonal (from top
left to bottom right) and zeros elsewhere. For any matrix A of size n × n, multiplying A by
the identity matrix I leaves A unchanged.
Example of a 3x3 identity matrix:

1 0 0
I= 0 1 0
​ ​ ​ ​ ​

0 0 1

If A is a matrix of size 3 × 3, then A × I = A.


Transpose of a Matrix
The transpose of a matrix A, denoted AT , is obtained by swapping its rows and columns.
If A is a matrix:

1 2
A=[ ]
3 4
​ ​

Then the transpose AT is:


1 3
AT = [ ]
2 4
​ ​

Mathematically, if A = [aij ], then AT = [aji ].


​ ​

Matrix Addition
To add two matrices, they must be of the same dimensions. Matrix addition is done by adding
corresponding elements of each matrix.
Given two matrices A and B of size m × n:

A=[ ], B=[ ]
a11 ​ a12 ​ b11 ​ b12 ​

a21 a22 b21 b22


​ ​ ​ ​

​ ​ ​ ​

Their sum A + B is:

a11 + b11 a12 + b12


A+B =[ ]
​ ​ ​ ​

a21 + b21 a22 + b22


​ ​

​ ​ ​ ​

Matrix Subtraction
Similar to addition, matrices must be of the same size. Subtraction is done by subtracting
corresponding elements.
Given matrices A and B :

a11 − b11 a12 − b12


A−B =[ ]
​ ​ ​ ​

a21 − b21 a22 − b22


​ ​

​ ​ ​ ​

Matrix Multiplication (Dot Product)


Matrix multiplication involves taking the dot product of rows of the first matrix with columns of
the second matrix. For matrix multiplication to be defined, the number of columns in the first
matrix must match the number of rows in the second.
Given matrices A of size m × n and B of size n × p:

A=[ ], B=[ ]
a11 ​ a12 ​ b11 ​ b12 ​

a21 a22 b21 b22


​ ​ ​ ​

​ ​ ​ ​

Their product C = A × B , where C is of size m × p, is calculated as:

(a11 ⋅ b11 + a12 ⋅ b21 ) (a11 ⋅ b12 + a12 ⋅ b22 )


C=[ ]
​ ​ ​ ​ ​ ​ ​ ​

(a21 ⋅ b11 + a22 ⋅ b21 ) (a21 ⋅ b12 + a22 ⋅ b22 )


​ ​

​ ​ ​ ​ ​ ​ ​ ​

Determinant of a Matrix
The determinant is a scalar value that can be calculated only for square matrices. For a 2 ×

2 matrix A = [ ], the determinant is given by:


a b
c d
​ ​
det(A) = a ⋅ d − b ⋅ c
Inverse of a Matrix
The inverse of a square matrix A, denoted A−1 , is the matrix such that A × A−1 = I,
where I is the identity matrix. Only matrices with a non-zero determinant have an inverse.

=[ ], if det(A) =
a b
For a 2 × 2 matrix A  0, the inverse is given by:
c d
​ ​

1 d −b
A−1 = [ ]
det(A) −c a
​ ​ ​

where det(A) = a ⋅ d − b ⋅ c.

18. Probability and Statistics


Probability and statistics are branches of mathematics that deal with the analysis and interpretation of
data, as well as predicting the likelihood of various outcomes.

Probability
Probability is a measure of the likelihood that a particular event will occur, represented as a
value between 0 and 1.
0 indicates an impossible event (it will not happen).
1 indicates a certain event (it will definitely happen).
Values between 0 and 1 represent varying degrees of likelihood.
The probability of an event A, denoted P (A), is calculated as:

Number of favorable outcomes


P (A) =
Total number of possible outcomes

Example: If we roll a fair six-sided die, the probability of rolling a 3 is:

1
P (rolling a 3) = ≈ 0.167
6

Mean (Average)
The mean, or average, is a measure of the central value in a data set. It is calculated by
summing all values in the data set and dividing by the number of values.
For a data set x1 , x2 , … , xn , the mean μ is:
​ ​ ​

x1 + x2 + ⋯ + xn
μ=
​ ​ ​

n
Example: For the data set [2, 4, 6, 8, 10], the mean is:
2 + 4 + 6 + 8 + 10
μ= =6
5

Median
The median is the middle value in an ordered data set. If the number of observations is odd,
the median is the center value. If it is even, the median is the average of the two middle
values.
Example: For the data set [1, 3, 3, 6, 7, 8, 9], the median is 6. For [1, 2, 3, 4, 5, 6, 8, 9], the
median is 4+5
2
​ = 4.5.
Mode
The mode is the most frequently occurring value in a data set. A data set can have more than
one mode (bimodal or multimodal) or no mode at all.
Example: For the data set [2, 3, 3, 5, 7, 8, 8], the modes are 3 and 8.

19. Data Analysis Libraries


Python offers powerful libraries for data analysis, each tailored to specific tasks in data manipulation,
numerical operations, and visualization. These libraries are essential for efficiently working with data,
from cleaning and processing to analyzing and visualizing insights.

Pandas
Pandas is a versatile library primarily used for data manipulation and analysis. It provides data
structures like DataFrames and Series, which are particularly useful for handling structured data.
Pandas is ideal for tasks such as data cleaning, transformation, aggregation, and merging datasets.

Examples:

1. Data Cleaning and Preprocessing: Removing missing values, handling duplicates, and
normalizing data.
import pandas as pd

# Sample data with missing values


data = {
'Name': ['Alice', 'Bob', None, 'David'],
'Age': [24, None, 35, 45],
'City': ['New York', 'Los Angeles', 'Chicago', None]
}
df = pd.DataFrame(data)

# Dropping rows with any missing values


df_cleaned = df.dropna()
print("Data after cleaning:")
print(df_cleaned)

2. Data Aggregation and Grouping: Calculating summary statistics across different categories.

# Sample sales data


sales_data = {
'Region': ['East', 'West', 'East', 'West'],
'Quarter': ['Q1', 'Q1', 'Q2', 'Q2'],
'Sales': [1500, 2000, 1700, 2500]
}
sales_df = pd.DataFrame(sales_data)

# Summing sales per region per quarter


aggregated_sales = sales_df.groupby(['Region', 'Quarter']).sum()
print("Aggregated sales:")
print(aggregated_sales)

3. Merging and Joining Data: Combining multiple datasets based on common columns or indices.
# Sample dataframes
customers = pd.DataFrame({
'CustomerID': [1, 2, 3],
'Name': ['Alice', 'Bob', 'Charlie']
})
transactions = pd.DataFrame({
'CustomerID': [1, 2, 1],
'PurchaseAmount': [100, 200, 300]
})

# Merging customer details with transaction history


merged_data = pd.merge(customers, transactions, on='CustomerID', how='inner')
print("Merged data:")
print(merged_data)

NumPy
NumPy is the foundation for numerical operations in Python. It offers support for large, multi-
dimensional arrays and matrices, along with an extensive library of mathematical functions. NumPy is
highly efficient and is often used for data manipulation in a way that complements Pandas.

Examples:

1. Scientific and Statistical Computations: Calculating means, medians, standard deviations, and
other statistics.

import numpy as np

# Array of daily temperatures


temperatures = np.array([23.4, 25.1, 22.8, 24.5, 26.2])

# Calculating mean temperature


average_temp = np.mean(temperatures)
print(f"Average Temperature: {average_temp}")

2. Linear Algebra Operations: Performing matrix multiplication, dot products, and other algebraic
operations.
# Matrices for multiplication
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])

# Performing matrix multiplication


result = np.dot(matrix_a, matrix_b)
print("Matrix multiplication result:")
print(result)

3. Data Transformation and Normalization: Applying mathematical transformations to datasets.

# Sample financial data


data = np.array([100, 150, 200, 250, 300])

# Normalizing data (scaling between 0 and 1)


normalized_data = (data - np.min(data)) / (np.max(data) - np.min(data))
print("Normalized data:")
print(normalized_data)

Matplotlib
Matplotlib is a powerful library for creating static, interactive, and animated visualizations in Python. It
enables users to plot data in various forms, such as line plots, bar charts, scatter plots, and
histograms, providing insights through visual representation.

Examples:

1. Trend Visualization: Creating line plots to track changes over time.

import matplotlib.pyplot as plt

# Sample monthly revenue data


months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
revenue = [3000, 3200, 2800, 3500, 3700]

# Plotting line chart for revenue trend


plt.plot(months, revenue, marker='o')
plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue ($)")
plt.show()

2. Data Distribution Analysis: Using histograms to understand data distributions.


# Sample customer ages
ages = [23, 25, 29, 30, 34, 35, 36, 40, 42, 46, 50, 55, 60]

# Plotting histogram for age distribution


plt.hist(ages, bins=5, edgecolor='black')
plt.title("Customer Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.show()

3. Comparing Categories: Employing bar charts to compare data across different categories.

# Sample product sales data


products = ['Product A', 'Product B', 'Product C']
sales = [120, 150, 100]

# Plotting bar chart for sales comparison


plt.bar(products, sales)
plt.title("Sales by Product")
plt.xlabel("Product")
plt.ylabel("Sales")
plt.show()

Each of these libraries plays a critical role in the data analysis workflow, and when combined, they
provide a comprehensive toolkit for end-to-end data processing, computation, and visualization in
Python.

20. Miscellaneous Examples:


Adding Elements to a List:
Inserting a new element increases the list size by 1.
Example:

my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]

Reading and Writing Files:


Example:

with open("data.txt", "a") as f:


f.write("New Line\n")

You might also like