X Sa Xy CQitu ZXNBND
X Sa Xy CQitu ZXNBND
X Sa Xy CQitu ZXNBND
1. Printing Output:
Use the print() function to display messages.
Example: print("Hello, World!") will print:
Hello, World!
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)
7. Functions:
Defined using the def keyword.
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
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
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
f = open("file.txt", "r")
content = f.read()
print(content)
f.close()
Writing to a File
Writing text to a file using write() :
Appending to a File
Adding text to the end of a file with append mode ( "a" ):
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 ):
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]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]
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
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
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 .
import numpy as np
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):
if dot_product == 0:
print("The vectors are perpendicular.")
else:
print("The vectors are not perpendicular.")
# Output: The vectors are perpendicular.
1 0 0
I= 0 1 0
0 0 1
1 2
A=[ ]
3 4
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
Matrix Subtraction
Similar to addition, matrices must be of the same size. Subtraction is done by subtracting
corresponding elements.
Given matrices A and B :
A=[ ], B=[ ]
a11 a12 b11 b12
Determinant of a Matrix
The determinant is a scalar value that can be calculated only for square matrices. For a 2 ×
=[ ], 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.
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:
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.
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
2. Data Aggregation and Grouping: Calculating summary statistics across different categories.
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]
})
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
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]])
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:
3. Comparing Categories: Employing bar charts to compare data across different categories.
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.
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]