1. Python Installation
Go to https://www.python.org/ Downloads -> Download the latest available version.
IDE — Integrated Development Environment. Python’s default IDE is IDLE — Integrated DeveLopment Environment.
We can verify version in command prompt (cmd) by executing ‘python –version’.
The execution of python script from cmd is ‘python give_path\file_name.py’
2. Variables and Data Type
Variables are names that store values. Variable names are case sensitive and should start with letter but not with number. They can contain numbers and underscore. In Python no need to define data type for variables as it analyses internally due to type casting.
Valid variable names:
variable_name = ‘value’
ii. variableName = ‘value’
iii. variablename = ‘value’
iv. variablename1 = ‘value’
Here value could be any string or number.
3. Working with strings
String represents text and can be enclosed in single or double quotes. i. variable = ‘string’ ii. variable = “string” iii. variable = ‘String having “double quotes” can be represented in this manner’ iv. variable = “String having ‘single quotes’ can be represented in this manner” v. variable = ‘String having both ‘Single quotes’ and “double quotes”‘ vi. variable = “String having both ‘Single quotes’ and “double quotes”” vii. sentence_in_double = “She said, “That’s a great tasting apple!”” viii. sentence_in_single = ‘She said, “That’s a great tasting apple!”‘
4. String Methods
Everything is an object in Python. • Every object has a type. Objects can have methods. Methods are functions that operate on an object • variable = ‘python’ • ‘python’ is an object of ‘str’ type. Here variable and python, both are string objects. • Methods are functions run against an object like object.method () • String Methods: i. upper() – Returns the entire string in upper case ii. lower() – Returns the entire string in lower case iii. format() – Returns the formatted version of the string • Ex: lower() string method. • variable = ‘Python’ • print(variable.lower()) — python • print(variable.uper()) — PYTHON
5. String Concatenation
print(‘Python ‘+’is ‘+’a’+’ programming’+’ language’)
Python is a programming language
print(‘Python’+’is’+’a’+’programming’+’language’)
Pythonisaprogramminglanguage
Spaces have to be defined explicitly.
>>> print('*'*10)
**********
>>> print('-'*10)
----------
>>> var = 'Python '*3
>>> print(var)
Python Python Python
>>> version = 3
>>> print('Python '+version)
TypeError: can only concatenate str (not "int") to str
>>> print('Python '+str(version))
Python 3
- Formatting Strings
- Indexing
- Working with numbers
- Boolean
- Operators
- Getting input from users
- Lists
- List Functions
- Slices
- Sorting
- Tuples
- Functions
- Print Delimiter
- Return statement
- If statement (Conditional statements)
- If statements and comparisons
- Dictionaries
- While loop
- For loop
- Exponent Function
- 2D lists and nested loop
- Comments
- Exception Handing – Try/Except
- Reading and Writing a file
- Modules and pip
- Object Function
- Inheritance
- Python interpreter
30. IPO Framework
IPO = Input-Process-Output
The three pillars of IPO are:
| Input (Gathering Data) | Process (Transforming Data) | Output (Delivering Results) |
| This phase brings external data into the program. This is typically handled by: | This phase is the core logic where the computer performs calculations, manipulations or decisions. It involves: | This phase presents the processed data back to the user or saves it for later. This involves: |
| i. input() function for keyboard entries | i. Mathematical operations (+, -, *, /) | print() function to display text on a screen |
| ii. Reading files (eg. .txt, .csv, .json) | ii. Conditional statements (if, elif, else) | Writing data to a local file |
| iii. Fetching data from databases or external APIs | iii. Loops (for, while) and data sorting | Sending data back across a network or database |
#Step 1: Input
#Get user input and convert it to a decimal number
celsius = float(input("Enter temperature in Celsius: "))
#Step 2: Process
#Apply the mathematical formula to convert units
fahrenheit = (celsius * 9/5) + 32
#Step 3: Output
#Display the formatted result to the user
print(f"{celsius} C is equal to {fahrenheit:.1f} F")
"""
Output is:
Enter temperature in Celsius: 1
1.0 C is equal to 33.8 F
"""31. Modules, Packages and Imports
| Modules | Packages | Imports |
|---|---|---|
| A single file containing Python definitions (functions, classes, variables) and statements. | A directory containing multiple Python Modules and a special ‘__init__.py’ file. | The mechanism used to bring code from external modules or packages into your current script. |
| A module is just a standard Python file. It allows to break up large codebases into manageable pieces. | A package is a collection of modules stored inside a folder to tell Python that this folder is a package rather than a regular directory, it traditionally contains a file named __init__.py (this file can be completely empty) | Imports are how you gain access to code written inside modules and packages. There are a few standard syntaxes to achieve this: |
| Example Module File (circle.py) #This file is named circle.py pi = 3.14159 def get_area(radius): return pi * (radius ** 2) | Example Package Structure: If you have a folder names shapes containing __init__.py and circle.py, shapes is the package and circle is the module inside it. | Syntax 1: Importing the entire module import shapes.circle # you must use the full path to access contents print(shapes.circle.get_area(5)) Syntax 2: Importing specific items using from from shapes.circle import get_area # you can call the function directly print(get_area(5)) Syntax 3: Aliasing with as (Great for shortening long names) import shapes.circle as c # use the short alias ‘c’ instead of the full path print(c.get_area(5)) |
my_project {folder}/ <–Root Project
|
|–main.py <–Main running script (uses Imports)
|
|–shapes {folder}/ <–Package (A directory with __init__.py)
—>|–__init__.py <– Makes the directory a package
—>|–circle.py <– Module (A single file)
—>|–square.py <– Module (A single file)
32. OOP
Object Oriented Programming
33. Classes and Objects
Classes and Objects(The Syntax)
Attributes (The “Adjectives”)
Methods (The “Verbs”)
34. __init__ method
35. The four pillars of OOP
Inheritance(Sharing)
Encapsulation(Protection)
Polymorphism(Flexibility)
Abstraction(Simplicity)
CREATE OR REPLACE PACKAGE BODY bolinf.xxhyt_file_status_monitor_pkg AS
/* ***************************************************************************/
/* Name : BOLINF.XXHYT_FILE_STATUS_MONITOR_PKG */
/* Object Type : PACKAGE BODY */
/* Description :
/* Parameters : ERRBUFF AND RETCODE */
/* Return values : None */
/* Change History: */
/* Date Name IR Modification */
/* ----------- ---------------------- ---- ------------- */
/* 20-Aug-2026 JADE 1.0 Created */
/******************************************************************************/
PROCEDURE xxhyt_file_main_prc (
errbuf OUT VARCHAR2,
retcode OUT VARCHAR2,
p_from_date IN VARCHAR2,
p_to_date IN VARCHAR2,
p_spirit_code IN VARCHAR2,
p_source IN VARCHAR2,
p_component IN VARCHAR2,
p_oracle_processed IN VARCHAR2,
p_file_status IN VARCHAR2,
p_email_id IN VARCHAR2
) IS
g_request_id NUMBER := fnd_global.conc_request_id;
g_cur_date DATE := sysdate;
v_rep_request_id NUMBER := 0;
v_rep_req_wait BOOLEAN;
v_rep_req_phase VARCHAR2(150);
v_rep_req_status VARCHAR2(150);
v_rep_dev_phase VARCHAR2(150);
v_rep_dev_status VARCHAR2(150);
v_rep_req_message VARCHAR2(250);
v_ftp_request_id NUMBER := 0;
v_ftp_req_wait BOOLEAN;
v_set_layout_option BOOLEAN;
v_ftp_req_phase VARCHAR2(150);
v_ftp_req_status VARCHAR2(150);
v_ftp_dev_phase VARCHAR2(150);
v_ftp_dev_status VARCHAR2(150);
v_ftp_req_message VARCHAR2(250);
v_file_name VARCHAR2(50);
v_from_dir VARCHAR2(150);
v_mail VARCHAR2(200);
v_cnt NUMBER;
l_req_id NUMBER;
v_user_id NUMBER := fnd_global.user_id;
v_eml_addr VARCHAR2(240);
v_email_dtls VARCHAR2(240);
BEGIN
v_rep_request_id := 0;
v_rep_req_wait := NULL;
v_rep_req_phase := NULL;
v_rep_req_status := NULL;
v_rep_dev_phase := NULL;
v_rep_dev_status := NULL;
v_rep_req_message := NULL;
v_ftp_request_id := 0;
v_ftp_req_wait := NULL;
v_ftp_req_phase := NULL;
v_ftp_req_status := NULL;
v_ftp_dev_phase := NULL;
v_ftp_dev_status := NULL;
v_ftp_req_message := NULL;
v_file_name := NULL;
v_from_dir := NULL;
fnd_file.put_line(fnd_file.log, 'Submitting the Hyatt File Monitor Check Program');
fnd_file.put_line(fnd_file.log, '');
v_rep_request_id := fnd_request.submit_request(
application => 'XBOL',
program => 'XXHYTFILEMONITOR_CHECK',
description => NULL,
start_time => NULL,
sub_request => NULL,
argument1 => 'Checkfile'
);
COMMIT;
-------------------------
-- Getting the request ID
-------------------------
fnd_file.put_line(fnd_file.log, 'The Request ID which has been retrived is :' || v_rep_request_id);
fnd_file.put_line(fnd_file.log, '');
-------------------------------------------
-- if the v_rep_request_id is 0, which means
-- that the concurrent has been failed to
-- submit
-- The request ID = 0 which means that the
-- concurrent output will be marked in red
-- which is not a normal completion
-------------------------------------------
IF ( v_rep_request_id = 0 ) THEN
retcode := 2;
fnd_file.put_line(fnd_file.log, 'The concurrent program Hyatt File Monitor Check Program has failed ');
fnd_file.put_line(fnd_file.log, '');
ELSIF ( v_rep_request_id > 0 ) THEN
fnd_file.put_line(fnd_file.log, 'Waiting for the concurrent program : Hyatt File Monitor Check Program to get complete');
v_rep_req_wait := fnd_concurrent.wait_for_request(
request_id => v_rep_request_id,
INTERVAL => 5,
phase => v_rep_req_phase,
status => v_rep_req_status,
dev_phase => v_rep_dev_phase,
dev_status => v_rep_dev_status,
message => v_rep_req_message
);
COMMIT;
fnd_file.put_line(fnd_file.log, '');
fnd_file.put_line(fnd_file.log, 'Dev Phase :' || v_rep_dev_phase);
fnd_file.put_line(fnd_file.log, 'Dev Status:' || v_rep_dev_status);
fnd_file.put_line(fnd_file.log, 'Phase :' || v_rep_req_phase);
fnd_file.put_line(fnd_file.log, 'Status :' || v_rep_req_status);
fnd_file.put_line(fnd_file.log, 'Message :' || v_rep_req_message);
fnd_file.put_line(fnd_file.log, '');
END IF;
fnd_file.put_line(fnd_file.log, 'Submitting the Hyatt File Status Monitor Report');
fnd_file.put_line(fnd_file.log, '');
v_set_layout_option := fnd_request.add_layout(
template_appl_name => 'XBOL',
template_code => 'XXHYT_FILE_STATUS_MONITOR_RPT',
template_language => 'en',
template_territory => 'US',
output_format => 'EXCEL'
);
fnd_file.put_line(fnd_file.log, 'INSIDE XXHYT_FILE_MAIN_PRC' || sqlerrm);
v_rep_request_id := fnd_request.submit_request(
application => 'XBOL',
program => 'XXHYT_FILE_STATUS_MONITOR_RPT',
description => NULL,
start_time => NULL,
sub_request => NULL,
argument1 => p_from_date,
argument2 => p_to_date,
argument3 => p_spirit_code,
argument4 => p_source,
argument5 => p_component,
argument6 => p_oracle_processed,
argument7 => p_file_status,
argument8 => p_email_id
);
COMMIT;
-------------------------
-- Getting the request ID
-------------------------
fnd_file.put_line(fnd_file.log, 'The Request ID which has been retrived is :' || v_rep_request_id);
fnd_file.put_line(fnd_file.log, '');
-------------------------------------------
-- if the v_rep_request_id is 0, which means
-- that the concurrent has been failed to
-- submit
-- The request ID = 0 which means that the
-- concurrent output will be marked in red
-- which is not a normal completion
-------------------------------------------
IF ( v_rep_request_id = 0 ) THEN
retcode := 2;
fnd_file.put_line(fnd_file.log, 'The concurrent program Hyatt File Status Monitor Report has failed ');
fnd_file.put_line(fnd_file.log, '');
ELSIF ( v_rep_request_id > 0 ) THEN
fnd_file.put_line(fnd_file.log, 'Waiting for the concurrent program : Hyatt File Status Monitor Report to get complete');
v_rep_req_wait := fnd_concurrent.wait_for_request(
request_id => v_rep_request_id,
INTERVAL => 5,
phase => v_rep_req_phase,
status => v_rep_req_status,
dev_phase => v_rep_dev_phase,
dev_status => v_rep_dev_status,
message => v_rep_req_message
);
COMMIT;
fnd_file.put_line(fnd_file.log, '');
fnd_file.put_line(fnd_file.log, 'Dev Phase :' || v_rep_dev_phase);
fnd_file.put_line(fnd_file.log, 'Dev Status:' || v_rep_dev_status);
fnd_file.put_line(fnd_file.log, 'Phase :' || v_rep_req_phase);
fnd_file.put_line(fnd_file.log, 'Status :' || v_rep_req_status);
fnd_file.put_line(fnd_file.log, 'Message :' || v_rep_req_message);
fnd_file.put_line(fnd_file.log, '');
END IF;
fnd_file.put_line(fnd_file.log, 'Getting the Report output file name and path');
BEGIN
SELECT regexp_substr(file_name, '(.+)/', 1, 1),
regexp_substr(file_name, '([^/]+)$', 1, 1)
INTO
v_from_dir,
v_file_name
FROM fnd_conc_req_outputs
WHERE concurrent_request_id = v_rep_request_id;
fnd_file.put_line(fnd_file.log, '');
fnd_file.put_line(fnd_file.log, 'File Name: ' || v_file_name);
fnd_file.put_line(fnd_file.log, 'From Path: ' || v_from_dir);
fnd_file.put_line(fnd_file.log, '');
EXCEPTION
WHEN no_data_found THEN
fnd_file.put_line(fnd_file.log, 'No Data Found While Getting The From Directory');
fnd_file.put_line(fnd_file.log, 'SQL Code :' || sqlcode);
fnd_file.put_line(fnd_file.log, 'SQL Error Message :' || sqlerrm);
WHEN OTHERS THEN
fnd_file.put_line(fnd_file.log, 'Others Error Found While Getting The From Directory');
fnd_file.put_line(fnd_file.log, 'SQL Code :' || sqlcode);
fnd_file.put_line(fnd_file.log, 'SQL Error Message :' || sqlerrm);
END;
/*
BEGIN
SELECT description
INTO v_email_dtls
FROM fnd_lookup_values_vl fvl
WHERE fvl.lookup_code = 'XXHYT_FILE_STATUS_MONITOR_RPT'
AND fvl.lookup_type = 'XXHYT_EMAIL_ENABLED_PROGRAMS'
AND fvl.enabled_flag = 'Y'
AND NVL (fvl.start_date_active, SYSDATE) <= SYSDATE
AND NVL (fvl.end_date_active, SYSDATE) >= SYSDATE;
EXCEPTION
WHEN OTHERS
THEN
v_email_dtls := NULL;
END;
*/
fnd_file.put_line(fnd_file.log, 'Submitting the Hyatt File Status Report completed');
fnd_file.put_line(fnd_file.log, '');
IF p_email_id IS NOT NULL THEN
l_req_id := fnd_request.submit_request('XBOL',
'XXHYT_GEN_MAIL_PROG',
'Hyatt File Status Monitor Report',
'',
FALSE,
'Hyatt File Status Monitor Report',
p_email_id,--v_email_dtls,
v_from_dir,
v_file_name,
'Please find the attached report. ',
v_file_name,
chr(0));
COMMIT;
END IF;
END xxhyt_file_main_prc;
END xxhyt_file_status_monitor_pkg;Assignment 1: Array Creation and Manipulation
- Create a NumPy array of shape (5, 5) filled with random integers between 1 and 20. Replace all the elements in the third column with 1.
- Create a NumPy array of shape (4, 4) with values from 1 to 16. Replace the diagonal elements with 0.
Assignment 2: Array Indexing and Slicing
- Create a NumPy array of shape (6, 6) with values from 1 to 36. Extract the sub-array consisting of the 3rd to 5th rows and 2nd to 4th columns.
- Create a NumPy array of shape (5, 5) with random integers. Extract the elements on the border.
Assignment 3: Array Operations
- Create two NumPy arrays of shape (3, 4) filled with random integers. Perform element-wise addition, subtraction, multiplication, and division.
- Create a NumPy array of shape (4, 4) with values from 1 to 16. Compute the row-wise and column-wise sum.
Assignment 4: Statistical Operations
- Create a NumPy array of shape (5, 5) filled with random integers. Compute the mean, median, standard deviation, and variance of the array.
- Create a NumPy array of shape (3, 3) with values from 1 to 9. Normalize the array (i.e., scale the values to have a mean of 0 and a standard deviation of 1).
Assignment 5: Broadcasting
- Create a NumPy array of shape (3, 3) filled with random integers. Add a 1D array of shape (3,) to each row of the 2D array using broadcasting.
- Create a NumPy array of shape (4, 4) filled with random integers. Subtract a 1D array of shape (4,) from each column of the 2D array using broadcasting.
Assignment 6: Linear Algebra
- Create a NumPy array of shape (3, 3) representing a matrix. Compute its determinant, inverse, and eigenvalues.
- Create two NumPy arrays of shape (2, 3) and (3, 2). Perform matrix multiplication on these arrays.
Assignment 7: Advanced Array Manipulation
- Create a NumPy array of shape (3, 3) with values from 1 to 9. Reshape the array to shape (1, 9) and then to shape (9, 1).
- Create a NumPy array of shape (5, 5) filled with random integers. Flatten the array and then reshape it back to (5, 5).
Assignment 8: Fancy Indexing and Boolean Indexing
- Create a NumPy array of shape (5, 5) filled with random integers. Use fancy indexing to extract the elements at the corners of the array.
- Create a NumPy array of shape (4, 4) filled with random integers. Use boolean indexing to set all elements greater than 10 to 10.
Assignment 9: Structured Arrays
- Create a structured array with fields ‘name’ (string), ‘age’ (integer), and ‘weight’ (float). Add some data and sort the array by age.
- Create a structured array with fields ‘x’ and ‘y’ (both integers). Add some data and compute the Euclidean distance between each pair of points.
Assignment 10: Masked Arrays
- Create a masked array of shape (4, 4) with random integers and mask the elements greater than 10. Compute the sum of the unmasked elements.
- Create a masked array of shape (3, 3) with random integers and mask the diagonal elements. Replace the masked elements with the mean of the unmasked elements.
import numpy as np
np.random.seed(42) # reproducible output; remove for different random values
def header(title):
print(“\n” + “=” * 60)
print(title)
print(“=” * 60)
—————————————————————
Assignment 1: Array Creation and Manipulation
—————————————————————
header(“Assignment 1.1: (5,5) random ints 1-20, third column -> 1”)
a = np.random.randint(1, 21, size=(5, 5)) # high is exclusive, so 21
print(“Original:\n”, a)
a[:, 2] = 1
print(“After replacing third column with 1:\n”, a)
header(“Assignment 1.2: (4,4) values 1-16, diagonal -> 0”)
a = np.arange(1, 17).reshape(4, 4)
print(“Original:\n”, a)
np.fill_diagonal(a, 0)
print(“After zeroing diagonal:\n”, a)
—————————————————————
Assignment 2: Array Indexing and Slicing
—————————————————————
header(“Assignment 2.1: (6,6) values 1-36, rows 3-5, cols 2-4”)
a = np.arange(1, 37).reshape(6, 6)
print(“Array:\n”, a)
print(“Sub-array (rows 3-5, cols 2-4):\n”, a[2:5, 1:4])
header(“Assignment 2.2: (5,5) random ints, border elements”)
a = np.random.randint(1, 100, size=(5, 5))
print(“Array:\n”, a)
border = np.concatenate([a[0, :], a[-1, :], a[1:-1, 0], a[1:-1, -1]])
print(“Border elements:”, border)
—————————————————————
Assignment 3: Array Operations
—————————————————————
header(“Assignment 3.1: element-wise operations on two (3,4) arrays”)
a = np.random.randint(1, 10, size=(3, 4))
b = np.random.randint(1, 10, size=(3, 4)) # >= 1 so no division by zero
print(“A:\n”, a)
print(“B:\n”, b)
print(“A + B:\n”, a + b)
print(“A – B:\n”, a – b)
print(“A * B:\n”, a * b)
print(“A / B:\n”, np.round(a / b, 3))
header(“Assignment 3.2: (4,4) values 1-16, row-wise and column-wise sums”)
a = np.arange(1, 17).reshape(4, 4)
print(“Array:\n”, a)
print(“Row-wise sum :”, a.sum(axis=1))
print(“Column-wise sum:”, a.sum(axis=0))
—————————————————————
Assignment 4: Statistical Operations
—————————————————————
header(“Assignment 4.1: (5,5) random ints, mean/median/std/var”)
a = np.random.randint(1, 100, size=(5, 5))
print(“Array:\n”, a)
print(“Mean :”, a.mean())
print(“Median :”, np.median(a))
print(“Std dev :”, a.std())
print(“Variance:”, a.var())
header(“Assignment 4.2: (3,3) values 1-9, normalize (mean 0, std 1)”)
a = np.arange(1, 10).reshape(3, 3)
norm = (a – a.mean()) / a.std()
print(“Original:\n”, a)
print(“Normalized:\n”, np.round(norm, 4))
print(“Check -> mean: %.4f, std: %.4f” % (norm.mean(), norm.std()))
—————————————————————
Assignment 5: Broadcasting
—————————————————————
header(“Assignment 5.1: add 1D (3,) to each row of (3,3)”)
a = np.random.randint(1, 10, size=(3, 3))
v = np.array([10, 20, 30])
print(“Array:\n”, a)
print(“Vector:”, v)
print(“Result (v added to every row):\n”, a + v)
header(“Assignment 5.2: subtract 1D (4,) from each column of (4,4)”)
a = np.random.randint(1, 20, size=(4, 4))
v = np.array([1, 2, 3, 4])
print(“Array:\n”, a)
print(“Vector:”, v)
To subtract from each column, the vector must run down the rows,
so reshape it to (4,1). A plain (4,) would be subtracted from each row.
print(“Result (v subtracted from every column):\n”, a – v.reshape(4, 1))
—————————————————————
Assignment 6: Linear Algebra
—————————————————————
header(“Assignment 6.1: determinant, inverse, eigenvalues of (3,3)”)
m = np.array([[4, 2, 1],
[3, 5, 2],
[1, 2, 6]])
print(“Matrix:\n”, m)
print(“Determinant:”, round(np.linalg.det(m), 4))
print(“Inverse:\n”, np.round(np.linalg.inv(m), 4))
print(“Eigenvalues:”, np.round(np.linalg.eigvals(m), 4))
header(“Assignment 6.2: matrix multiplication (2,3) x (3,2)”)
a = np.random.randint(1, 10, size=(2, 3))
b = np.random.randint(1, 10, size=(3, 2))
print(“A:\n”, a)
print(“B:\n”, b)
print(“A @ B (shape (2,2)):\n”, a @ b)
—————————————————————
Assignment 7: Advanced Array Manipulation
—————————————————————
header(“Assignment 7.1: reshape (3,3) -> (1,9) -> (9,1)”)
a = np.arange(1, 10).reshape(3, 3)
print(“Original:\n”, a)
row = a.reshape(1, 9)
print(“Shape (1,9):\n”, row)
col = row.reshape(9, 1)
print(“Shape (9,1):\n”, col)
header(“Assignment 7.2: flatten (5,5) then reshape back”)
a = np.random.randint(1, 100, size=(5, 5))
flat = a.flatten()
back = flat.reshape(5, 5)
print(“Original:\n”, a)
print(“Flattened:”, flat)
print(“Reshaped back:\n”, back)
print(“Identical to original:”, np.array_equal(a, back))
—————————————————————
Assignment 8: Fancy Indexing and Boolean Indexing
—————————————————————
header(“Assignment 8.1: corners of (5,5) using fancy indexing”)
a = np.random.randint(1, 100, size=(5, 5))
print(“Array:\n”, a)
rows = np.array([0, 0, -1, -1])
cols = np.array([0, -1, 0, -1])
print(“Corners (TL, TR, BL, BR):”, a[rows, cols])
header(“Assignment 8.2: boolean indexing, cap values at 10”)
a = np.random.randint(1, 20, size=(4, 4))
print(“Original:\n”, a)
a[a > 10] = 10
print(“After setting elements > 10 to 10:\n”, a)
—————————————————————
Assignment 9: Structured Arrays
—————————————————————
header(“Assignment 9.1: structured array sorted by age”)
people = np.array(
[(“Asha”, 29, 61.5), (“Ravi”, 24, 72.3), (“Meena”, 35, 58.0), (“Kiran”, 21, 68.9)],
dtype=[(“name”, “U10”), (“age”, “i4”), (“weight”, “f8”)],
)
print(“Original:\n”, people)
print(“Sorted by age:\n”, np.sort(people, order=”age”))
header(“Assignment 9.2: pairwise Euclidean distances”)
pts = np.array([(0, 0), (3, 4), (6, 8), (1, 1)],
dtype=[(“x”, “i4”), (“y”, “i4”)])
print(“Points:\n”, pts)
xy = np.column_stack([pts[“x”], pts[“y”]]).astype(float)
diff = xy[:, None, :] – xy[None, :, :] # shape (n, n, 2)
dist = np.sqrt((diff ** 2).sum(axis=-1)) # shape (n, n)
print(“Distance matrix:\n”, np.round(dist, 3))
—————————————————————
Assignment 10: Masked Arrays
—————————————————————
header(“Assignment 10.1: mask elements > 10, sum the unmasked”)
data = np.random.randint(1, 21, size=(4, 4))
ma = np.ma.masked_greater(data, 10)
print(“Data:\n”, data)
print(“Masked array:\n”, ma)
print(“Sum of unmasked elements:”, ma.sum())
header(“Assignment 10.2: mask diagonal, fill with mean of unmasked”)
data = np.random.randint(1, 20, size=(3, 3))
ma = np.ma.masked_array(data, mask=np.eye(3, dtype=bool))
print(“Data:\n”, data)
print(“Masked array:\n”, ma)
mean_val = ma.mean()
print(“Mean of unmasked:”, round(float(mean_val), 4))
print(“Masked elements replaced with mean:\n”, ma.astype(float).filled(mean_val))
Module: Pandas Assignments
Lesson: Pandas
Assignment 1: DataFrame Creation and Indexing
- Create a Pandas DataFrame with 4 columns and 6 rows filled with random integers. Set the index to be the first column.
- Create a Pandas DataFrame with columns ‘A’, ‘B’, ‘C’ and index ‘X’, ‘Y’, ‘Z’. Fill the DataFrame with random integers and access the element at row ‘Y’ and column ‘B’.
Assignment 2: DataFrame Operations
- Create a Pandas DataFrame with 3 columns and 5 rows filled with random integers. Add a new column that is the product of the first two columns.
- Create a Pandas DataFrame with 3 columns and 4 rows filled with random integers. Compute the row-wise and column-wise sum.
Assignment 3: Data Cleaning
- Create a Pandas DataFrame with 3 columns and 5 rows filled with random integers. Introduce some NaN values. Fill the NaN values with the mean of the respective columns.
- Create a Pandas DataFrame with 4 columns and 6 rows filled with random integers. Introduce some NaN values. Drop the rows with any NaN values.
Assignment 4: Data Aggregation
- Create a Pandas DataFrame with 2 columns: ‘Category’ and ‘Value’. Fill the ‘Category’ column with random categories (‘A’, ‘B’, ‘C’) and the ‘Value’ column with random integers. Group the DataFrame by ‘Category’ and compute the sum and mean of ‘Value’ for each category.
- Create a Pandas DataFrame with 3 columns: ‘Product’, ‘Category’, and ‘Sales’. Fill the DataFrame with random data. Group the DataFrame by ‘Category’ and compute the total sales for each category.
Assignment 5: Merging DataFrames
- Create two Pandas DataFrames with a common column. Merge the DataFrames using the common column.
- Create two Pandas DataFrames with different columns. Concatenate the DataFrames along the rows and along the columns.
Assignment 6: Time Series Analysis
- Create a Pandas DataFrame with a datetime index and one column filled with random integers. Resample the DataFrame to compute the monthly mean of the values.
- Create a Pandas DataFrame with a datetime index ranging from ‘2021-01-01’ to ‘2021-12-31’ and one column filled with random integers. Compute the rolling mean with a window of 7 days.
Assignment 7: MultiIndex DataFrame
- Create a Pandas DataFrame with a MultiIndex (hierarchical index). Perform some basic indexing and slicing operations on the MultiIndex DataFrame.
- Create a Pandas DataFrame with MultiIndex consisting of ‘Category’ and ‘SubCategory’. Fill the DataFrame with random data and compute the sum of values for each ‘Category’ and ‘SubCategory’.
Assignment 8: Pivot Tables
- Create a Pandas DataFrame with columns ‘Date’, ‘Category’, and ‘Value’. Create a pivot table to compute the sum of ‘Value’ for each ‘Category’ by ‘Date’.
- Create a Pandas DataFrame with columns ‘Year’, ‘Quarter’, and ‘Revenue’. Create a pivot table to compute the mean ‘Revenue’ for each ‘Quarter’ by ‘Year’.
Assignment 9: Applying Functions
- Create a Pandas DataFrame with 3 columns and 5 rows filled with random integers. Apply a function that doubles the values of the DataFrame.
- Create a Pandas DataFrame with 3 columns and 6 rows filled with random integers. Apply a lambda function to create a new column that is the sum of the existing columns.
Assignment 10: Working with Text Data
- Create a Pandas Series with 5 random text strings. Convert all the strings to uppercase.
- Create a Pandas Series with 5 random text strings. Extract the first three characters of each string.all dataset (Iris/Titanic): cleaning, summary stats, 3–4 plots in a Jupyter notebook
"""
Simple tests for the Pandas assignments (1-10).
Run: python test_pandas_assignments.py
Or: pytest -v test_pandas_assignments.py
Each test has the same layout:
1. TEST DATA - fixed input (no randomness), so the answer is known
2. YOUR CODE - the solution lines (paste your own version here to test it)
3. CHECK - assert statements with the hand-calculated expected result
"""
import numpy as np
import pandas as pd
# ---------------- Assignment 1: DataFrame Creation and Indexing ----------------
def test_1_1_set_index_first_column():
df = pd.DataFrame({"A": [10, 20, 30, 40, 50, 60],
"B": [1, 2, 3, 4, 5, 6],
"C": [7, 8, 9, 10, 11, 12],
"D": [0, 0, 1, 1, 2, 2]})
df = df.set_index(df.columns[0])
assert df.index.name == "A"
assert df.index.tolist() == [10, 20, 30, 40, 50, 60]
assert df.shape == (6, 3) # first column moved into the index
def test_1_2_access_element():
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
columns=["A", "B", "C"], index=["X", "Y", "Z"])
assert df.loc["Y", "B"] == 5
# ---------------- Assignment 2: DataFrame Operations ----------------
def test_2_1_product_column():
df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [2, 3, 4, 5, 6], "C": [0, 0, 0, 0, 0]})
df["A_x_B"] = df["A"] * df["B"]
assert df["A_x_B"].tolist() == [2, 6, 12, 20, 30]
def test_2_2_row_col_sum():
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=list("ABC"))
assert df.sum(axis=1).tolist() == [6, 15, 24, 33] # row-wise
assert df.sum(axis=0).tolist() == [22, 26, 30] # column-wise
# ---------------- Assignment 3: Data Cleaning ----------------
def test_3_1_fill_nan_with_mean():
df = pd.DataFrame({"A": [1, 2, np.nan, 4, 5],
"B": [10, np.nan, 30, 40, 20],
"C": [1.0, 1.0, 1.0, 1.0, 1.0]})
filled = df.fillna(df.mean())
assert filled["A"][2] == 3 # mean of 1,2,4,5
assert filled["B"][1] == 25 # mean of 10,30,40,20
assert filled.isna().sum().sum() == 0
def test_3_2_drop_rows_with_nan():
df = pd.DataFrame({"A": [1, 2, np.nan, 4, 5, 6],
"B": [1, 2, 3, np.nan, 5, 6],
"C": [1, 2, 3, 4, 5, 6],
"D": [1, 2, 3, 4, 5, 6]})
out = df.dropna()
assert out.index.tolist() == [0, 1, 4, 5] # rows 2 and 3 removed
assert len(out) == 4
# ---------------- Assignment 4: Data Aggregation ----------------
def test_4_1_group_sum_mean():
df = pd.DataFrame({"Category": ["A", "B", "A", "C", "B", "A"],
"Value": [10, 20, 30, 40, 50, 60]})
g = df.groupby("Category")["Value"].agg(["sum", "mean"])
assert g.loc["A", "sum"] == 100 and np.isclose(g.loc["A", "mean"], 100 / 3)
assert g.loc["B", "sum"] == 70 and g.loc["B", "mean"] == 35
assert g.loc["C", "sum"] == 40 and g.loc["C", "mean"] == 40
def test_4_2_total_sales_per_category():
df = pd.DataFrame({"Product": ["P1", "P2", "P3", "P4"],
"Category": ["Toys", "Food", "Toys", "Food"],
"Sales": [100, 200, 300, 400]})
total = df.groupby("Category")["Sales"].sum()
assert total["Toys"] == 400
assert total["Food"] == 600
# ---------------- Assignment 5: Merging DataFrames ----------------
def test_5_1_merge_on_common_column():
left = pd.DataFrame({"id": [1, 2, 3], "name": ["Asha", "Ravi", "Meena"]})
right = pd.DataFrame({"id": [2, 3, 4], "score": [88, 92, 65]})
inner = pd.merge(left, right, on="id")
assert inner["id"].tolist() == [2, 3]
assert inner["name"].tolist() == ["Ravi", "Meena"]
assert inner["score"].tolist() == [88, 92]
outer = pd.merge(left, right, on="id", how="outer")
assert len(outer) == 4
def test_5_2_concat_rows_and_columns():
d1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
d2 = pd.DataFrame({"C": [5, 6], "D": [7, 8]})
rows = pd.concat([d1, d2], axis=0)
assert rows.shape == (4, 4)
assert rows["A"].isna().sum() == 2 # d2 rows have no column A
cols = pd.concat([d1, d2], axis=1)
assert cols.shape == (2, 4)
assert cols.columns.tolist() == ["A", "B", "C", "D"]
# ---------------- Assignment 6: Time Series ----------------
def test_6_1_monthly_mean():
idx = pd.date_range("2021-01-01", periods=59, freq="D") # Jan (31) + Feb (28)
ts = pd.DataFrame({"value": range(1, 60)}, index=idx)
monthly = ts.resample("MS").mean()
assert len(monthly) == 2
assert monthly["value"].iloc[0] == 16 # mean of 1..31
assert monthly["value"].iloc[1] == 45.5 # mean of 32..59
def test_6_2_rolling_mean_7_days():
idx = pd.date_range("2021-01-01", "2021-12-31", freq="D")
ts = pd.DataFrame({"value": range(1, len(idx) + 1)}, index=idx)
assert len(ts) == 365
r = ts["value"].rolling(window=7).mean()
assert r.iloc[:6].isna().all() # not enough data for first 6 days
assert r.iloc[6] == 4 # mean of 1..7
assert r.iloc[-1] == 362 # mean of 359..365
# ---------------- Assignment 7: MultiIndex ----------------
def test_7_1_multiindex_indexing():
mi = pd.MultiIndex.from_product([["Fruit", "Veg"], ["Q1", "Q2"]], names=["Type", "Quarter"])
df = pd.DataFrame({"Sales": [10, 20, 30, 40]}, index=mi)
assert df.loc["Fruit"]["Sales"].tolist() == [10, 20]
assert df.loc[("Veg", "Q1"), "Sales"] == 30
assert df.xs("Q2", level="Quarter")["Sales"].tolist() == [20, 40]
def test_7_2_multiindex_sums():
mi = pd.MultiIndex.from_tuples(
[("Elec", "Phone"), ("Elec", "Phone"), ("Elec", "Laptop"), ("Cloth", "Shirt")],
names=["Category", "SubCategory"])
df = pd.DataFrame({"Value": [10, 20, 30, 40]}, index=mi)
s = df.groupby(level=["Category", "SubCategory"])["Value"].sum()
assert s[("Elec", "Phone")] == 30
assert s[("Elec", "Laptop")] == 30
assert s[("Cloth", "Shirt")] == 40
# ---------------- Assignment 8: Pivot Tables ----------------
def test_8_1_pivot_sum():
df = pd.DataFrame({"Date": ["2024-01-01", "2024-01-01", "2024-01-02", "2024-01-02"],
"Category": ["A", "B", "A", "B"],
"Value": [1, 2, 3, 4]})
p = df.pivot_table(values="Value", index="Date", columns="Category", aggfunc="sum")
assert p.loc["2024-01-01", "A"] == 1 and p.loc["2024-01-01", "B"] == 2
assert p.loc["2024-01-02", "A"] == 3 and p.loc["2024-01-02", "B"] == 4
def test_8_2_pivot_mean():
df = pd.DataFrame({"Year": [2022, 2022, 2022, 2022],
"Quarter": ["Q1", "Q1", "Q2", "Q2"],
"Revenue": [100, 200, 300, 500]})
p = df.pivot_table(values="Revenue", index="Year", columns="Quarter", aggfunc="mean")
assert p.loc[2022, "Q1"] == 150
assert p.loc[2022, "Q2"] == 400
# ---------------- Assignment 9: Applying Functions ----------------
def test_9_1_double_values():
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
out = df.apply(lambda col: col * 2) # works on every pandas version
assert out["A"].tolist() == [2, 4, 6]
assert out["C"].tolist() == [14, 16, 18]
assert df["A"].tolist() == [1, 2, 3] # original not changed
def test_9_2_lambda_sum_column():
df = pd.DataFrame({"A": [1, 2, 3], "B": [10, 20, 30], "C": [100, 200, 300]})
df["Total"] = df.apply(lambda row: row["A"] + row["B"] + row["C"], axis=1)
assert df["Total"].tolist() == [111, 222, 333]
# ---------------- Assignment 10: Text Data ----------------
def test_10_1_uppercase():
s = pd.Series(["python", "pandas", "numpy", "jupyter", "matplotlib"])
assert s.str.upper().tolist() == ["PYTHON", "PANDAS", "NUMPY", "JUPYTER", "MATPLOTLIB"]
def test_10_2_first_three_chars():
s = pd.Series(["python", "pandas", "numpy", "jupyter", "matplotlib"])
assert s.str[:3].tolist() == ["pyt", "pan", "num", "jup", "mat"]
# ---------------- tiny runner (so pytest is not required) ----------------
if __name__ == "__main__":
failed = 0
tests = [(n, f) for n, f in sorted(globals().items()) if n.startswith("test_")]
for name, fn in tests:
try:
fn()
print("PASS", name)
except Exception as e:
failed += 1
print("FAIL", name, "->", repr(e))
print(f"\n{len(tests) - failed}/{len(tests)} passed")
raise SystemExit(1 if failed else 0)import 'package:flutter/material.dart';
void main() {
runApp(const TodoApp());
}
class TodoApp extends StatelessWidget {
const TodoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'To-Do App',
theme: ThemeData(primarySwatch: Colors.blue),
home: const TodoListScreen(),
);
}
}
class TodoListScreen extends StatefulWidget {
const TodoListScreen({super.key});
@override
State<TodoListScreen> createState() => _TodoListScreenState();
}
class _TodoListScreenState extends State<TodoListScreen> {
final List<String> _todoItems = [];
final TextEditingController _textFieldController = TextEditingController();
void _addTodoItem(String task) {
if (task.isNotEmpty) {
setState(() {
_todoItems.add(task);
});
_textFieldController.clear();
}
}
void _removeTodoItem(int index) {
setState(() {
_todoItems.removeAt(index);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My To-Do List'),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
body: _todoItems.isEmpty
? const Center(child: Text('No tasks yet. Add one below!'))
: ListView.builder(
itemCount: _todoItems.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_todoItems[index]),
trailing: IconButton(
icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () => _removeTodoItem(index),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _displayDialog(),
tooltip: 'Add Task',
child: const Icon(Icons.add),
),
);
}
Future<void> _displayDialog() async {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Add a new task'),
content: TextField(
controller: _textFieldController,
decoration: const InputDecoration(hintText: 'Enter task name'),
autofocus: true,
),
actions: <Widget>[
TextButton(
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
ElevatedButton(
child: const Text('Add'),
onPressed: () {
Navigator.of(context).pop();
_addTodoItem(_textFieldController.text);
},
),
],
);
},
);
}
}