CS, IP & AI Practical Study & Project Guide 2026-27

PM SHRI KV Shalimar Bagh, Delhi (Shift-I) · Compiled by Narender Kumar, PGT (Computer Science)

Designed by NareN, PGT(Computer Science), PM SHRI K V Shalimar, Bagh Delhi-88(Shift-I) ✨ Click Here For Your Valuable Feedback✨

📥 Download Centre — Practical File & Project Documentation

For students & teachers · choose Class & Subject · PDF or Word · works offline · A4 print-ready

How to download the Practical File

  1. Select Class — IX, X, XI or XII, and Subject — Computer Science (083), Informatics Practices (065) or Artificial Intelligence (417 for IX–X, 843 for XI–XII); then choose Practical File in the What do you want to download? menu.
  2. (Optional) type your School Name, Name, Class & Section and Roll No. — they are printed on the cover page. Leave the school blank to keep the default school name.
  3. Click Download Word (editable) or Download PDF. The file is saved in your Downloads folder.
What the file contains:
Cover page → Index (Practical No., title, type, Page No., teacher's sign) → every practical on its own page(s) with Practical No., question, solution code, sample output (with charts / images for AI) & explanation.
PDF: click any index row to jump to that practical.   Word: if Word asks to update fields, click Yes so the page numbers are exact.

How to download the Project Documentation

  1. Select Class and Subject, choose Project Documentation in the What do you want to download? menu, then pick one of the 10 projects (you can also press Get Documentation on any project card below).
  2. Fill in your details: School Name, Class & Section, Name, Roll No., Project Guide and Principal's Name (Vice Principal, academic year and exam date are optional). They are placed on the cover page, certificate and acknowledgement automatically.
  3. Click Download Word to edit the report, or Download PDF to print it.
25+ page report · Cambria 14 pt · colourful chapter headings:
Cover → Certificate → Contents → 21 chapters: Acknowledgement, Introduction, Objectives, Existing & Proposed System, Feasibility Study, SDLC & Phases, Requirements, Modules & Menu, Functions Used, Data Dictionary, Flow Chart, Algorithm, Colour-coded Source Code, Output Screens (with charts), Testing, User Manual, Limitations & Future Scope, Conclusion, Viva Questions, Bibliography.
Every project was run; the output screens are from the real run.

Choose & download

Your details — printed on the cover page & page headers (optional for the practical file)

๐Ÿ“‹ Quick Practical Lists (Questions Only)

Printable, plain question lists for each class & subject โ€” click any question to jump straight to its solution

Class XI โ€” Computer Science (083)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 29 Practicals

  1. Q1 Introduction to Computer System Organization โ€” Draw & explain the functional diagram of a computer; explain Input, Output devices, Software, Hardware, Memory and Operating System. THEORY
  2. Q2 Introduction to Python Programming Language โ€” history, installation, features of Python & various Python interpreters. THEORY
  3. Q3 Write a python program to Input a welcome message and display it. PYTHON
  4. Q4 Write a python program to Input two numbers and display the larger / smaller number. PYTHON
  5. Q5 Write a python program to Input three numbers and display the largest / smallest number. PYTHON
  6. Q6 Write a python program to input two integers x and n, compute xโฟ. PYTHON
  7. Q7 Write a python program to Generate number/star patterns using nested loop. PYTHON
  8. Q8 Write a python program to input value of x and n and print the sum of the series: (i) 1+x+xยฒ+xยณ+...+xโฟ (ii) 1-x+xยฒ-xยณ+...ยฑxโฟ (iii) x+xยฒ/2-xยณ/3+...ยฑxโฟ/n (iv) x+xยฒ/2!-xยณ/3!+...ยฑxโฟ/n! PYTHON
  9. Q9 Write a python program to determine whether a number is a Perfect number, an Armstrong number or a Palindrome. PYTHON
  10. Q10 Write a python program to Input a number and check if the number is Prime or Composite. PYTHON
  11. Q11 Write a Python Program to print Fibonacci series up to the entered n positive number. PYTHON
  12. Q12 Write a Python Program to Compute GCD/HCF and LCM of two Integers. PYTHON
  13. Q13 Write a Python Program to Count and display the number of vowels, consonants, uppercase, lowercase characters in a string. PYTHON
  14. Q14 Write a Python Program to Input a string and determine whether it is a palindrome or not; convert the case of characters in a string. PYTHON
  15. Q15 Write a Python Program to find the largest/smallest number in a list/tuple and display the position of that number. PYTHON
  16. Q16 Write a Python Program to Input a list of numbers and swap elements at the even location with the elements at the odd location. PYTHON
  17. Q17 Write a Python Program to Input a list/tuple of elements, search for a given element and display its frequency and position. PYTHON
  18. Q18 Write a Python Program to Input a list of numbers and test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such number from the list. PYTHON
  19. Q19 Write a Python Program to Create a dictionary with roll number, name and marks of n students and display names of students who scored above 75. PYTHON
  20. Q20 Write a Python Program to Create a dictionary of employee information (empid, empname, empsal, empmobile), input five values and display employees getting salary <= Rs 50000. PYTHON
  21. Q21 Write a Python Program to Create a dictionary of Library information (bookid, bookname, bookprice, bookauthor), input five values, display and change some values by searching bookname. PYTHON
  22. Q22 Write a Python Program to Create a hotel dictionary (bookingid, clientname, date, roomno) and delete a value based on bookingid. PYTHON
  23. Q23 Write a Python Program to implement python math functions/methods (pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan) using the math module. PYTHON
  24. Q24 Write a Python program to implement the random function random(), randint(), randrange() using the random module. PYTHON
  25. Q25 Write a Python program to implement statistics functions (mean, median, mode) using the statistics module. PYTHON
  26. Q26 Write a python program to find the factorial of a positive number. PYTHON
  27. Q27 Write a python program to find the absolute value of a number (without and with abs()). PYTHON
  28. Q28 Write a python program to check whether a number is divisible by another number. PYTHON
  29. Q29 Write a python program to count the frequency of each character in a string using a dictionary. PYTHON

Class XI โ€” Informatics Practices (065)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 36 Practicals

  1. Q1 Introduction to Computer Systems (CPU, Input devices, Output devices, Memory, Hardware & Software etc.) THEORY
  2. Q2 Introduction to Python (History of Python, Python Modes, Python Software etc.) THEORY
  3. Q3 Write a python program to design a calculator (+, -, *, /, %, //). PYTHON
  4. Q4 Write a Python program to calculate perimeter/circumference and area of shapes: triangle, rectangle, square, circle. PYTHON
  5. Q5 Write a Python program to calculate Simple and Compound Interest. PYTHON
  6. Q6 Write a python program to find average and grade for given marks. PYTHON
  7. Q7 Write a Python program to find the sale price of an item with a given cost and discount (%). PYTHON
  8. Q8 Write a Python program to calculate profit-loss for given Cost and Sell Price. PYTHON
  9. Q9 Write a python program to calculate EMI for Amount, Period and Interest. EMI = (P*MR*(1+MR)**N)/(((1+MR)**N)-1) PYTHON
  10. Q10 Write a python program to calculate tax: (a) GST (b) Income Tax. PYTHON
  11. Q11 Write a python program to find the largest and smallest numbers in a list. PYTHON
  12. Q12 Write a python program to find the third largest/smallest number in a list. PYTHON
  13. Q13 Write a python program to find the sum of squares of the first 100 natural numbers. PYTHON
  14. Q14 Write a python program to print the first 'n' multiples of a given number. PYTHON
  15. Q15 Write a python program to count the number of vowels in a user entered string. PYTHON
  16. Q16 Write a python program to print the words starting with a given alphabet in a user entered string. PYTHON
  17. Q17 Write a python program to print the number of occurrences of a given alphabet in each string. PYTHON
  18. Q18 Write a python program to Create a dictionary to store names of states and their capitals. PYTHON
  19. Q19 Write a python program to Create a dictionary of students to store names and marks obtained in 5 subjects. PYTHON
  20. Q20 Write a python program to print the highest and lowest values in the dictionary. PYTHON
  21. Q21 Write a python program to create a student dictionary and search by using the name of the student and display the details. PYTHON
  22. Q22 SQL: To create a school database and access it. SQL
  23. Q23 SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key). SQL
  24. Q24 SQL: To insert the details of at least 10 students in the above table. SQL
  25. Q25 SQL: To display the entire content of the table. SQL
  26. Q26 SQL: To display Rno, Name and Marks of those students scoring marks more than 50. SQL
  27. Q27 SQL: To find the average of marks from the student table. SQL
  28. Q28 SQL: To find the number of students who are from section 'A'. SQL
  29. Q29 SQL: To display information of all students whose name starts with 'AN'. SQL
  30. Q30 SQL: To display Rno, Name, DOB of students born between '2005-01-01' and '2005-12-31'. SQL
  31. Q31 SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names. SQL
  32. Q32 SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks. SQL
  33. Q33 SQL: To display the unique sections available in the table. SQL
  34. Q34 SQL: To display the name and class of students whose marks are less than 33. SQL
  35. Q35 SQL: To display the structure of the student table. SQL
  36. Q36 SQL: To display the Name and DOB of students who were born in 2008. SQL

Class XII โ€” Computer Science (083)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 25 Practicals + Project

  1. Q1 Search an element in a list and display frequency & location using Linear Search (user-defined function). PYTHON
  2. Q2 Search an element in a list and display frequency & location using Binary Search (user-defined function). PYTHON
  3. Q3 Pass a list to a function; double the odd values and half the even values, then display the changed list. PYTHON
  4. Q4 Input n numbers in a tuple and pass it to a function to count how many even and odd numbers are entered. PYTHON
  5. Q5 Function with key and value updates the value at that key in a dictionary entered by the user. PYTHON
  6. Q6 Pass a string to a function and count how many vowels are present in the string. PYTHON
  7. Q7 Generate random numbers between 1 and 6 (simulate a dice) using a user-defined function. PYTHON
  8. Q8 Menu driven python program to implement 10 python mathematical functions. PYTHON
  9. Q9 Implement Python string functions (all listed in Sumita Arora book). PYTHON
  10. Q10 Menu driven program to delete a student's name from a dictionary and search phone number by student name. PYTHON
  11. Q11 Read and display file content line by line with each word separated by #. PYTHON
  12. Q12 Read a text file and display the number of vowels, consonants, uppercase, lowercase characters in the file. PYTHON
  13. Q13 Menu driven program to count spaces, digits, words and lines from text file TOY.txt. PYTHON
  14. Q14 Remove all lines that contain the character 'a' in a file and write remaining lines to another file. PYTHON
  15. Q15 Create a binary file with name and roll number; search for a given roll number and display name. PYTHON
  16. Q16 Create a dictionary with roll number, name and marks; accept 5 records and write them into a binary file. PYTHON
  17. Q17 Create a CSV file by entering user-id and password; read and search the password for a given user-id. PYTHON
  18. Q18 Menu driven program to create a CSV file with dept-id, name, city; read and search a record for given dept-id. PYTHON
  19. Q19 Implement a Stack using a list (PUSH & POP operations). PYTHON
  20. Q20 Function PUSH(Arr): from a given list push all numbers divisible by 5 into a stack implemented using a list. PYTHON
  21. Q21 Function POP(Arr): Arr is a stack implemented using a list of numbers; the function returns the value deleted from the stack. PYTHON
  22. Q22 Create a school database, create a student table and implement ALTER, UPDATE, ORDER BY, DELETE, GROUP BY, MIN/MAX/SUM/COUNT/AVG on it. SQL
  23. Q23 Integrate SQL with Python using the MySQL module โ€” insert and display employee records. PYTHON
  24. Q24 Integrate SQL with Python โ€” search an employee using empno; display the record if present, else show a message. PYTHON
  25. Q25 Integrate SQL with Python โ€” update a student using rollno and delete a record using rollno. PYTHON

Class XII โ€” Informatics Practices (065)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 45 Practicals (incl. 6 Data Visualization) + Project

  1. Q1 Create Pandas Series from (a) an ndarray (b) a List (labeled & positional index) (c) a Dictionary (d) a Scalar value. PYTHON
  2. Q2 Perform operations on a Series: (a) Slicing (minimum 5) (b) Filtering (all relational operators). PYTHON
  3. Q3 Create a Series containing a dictionary of students' results (name, class, percentage, result); print elements above 75%. PYTHON
  4. Q4 Create Pandas DataFrame & display from (a) ndarray (b) List (labeled & positional index) (c) Dictionary (d) another DataFrame. PYTHON
  5. Q5 Create a DataFrame of quarterly sales (item category, item name, expenditure); group by category and print total expenditure per category. PYTHON
  6. Q6 Create a DataFrame for examination results and display row labels, column labels, data types of each column and dimensions. PYTHON
  7. Q7 Filter out rows based on different criteria such as duplicate rows. PYTHON
  8. Q8 Importing and exporting data between pandas and a CSV file. PYTHON
  9. Q9 Given the school result data, analyse the performance of students on different parameters (e.g., subject-wise or class-wise). PYTHON
  10. Q10 For the DataFrames created above, analyse and plot appropriate charts with title and legend. PYTHON
  11. Q11 Take data of your interest from an open source (e.g. data.gov.in), aggregate & summarize it, then plot using Matplotlib. PYTHON
  12. Q12 Locate the 3 largest values in a DataFrame. PYTHON
  13. Q13 Subtract the mean of a row from each element of that row in a DataFrame. PYTHON
  14. Q14 Replace all negative values with 0 in a DataFrame. PYTHON
  15. Q15 Replace all missing values with 999 in a DataFrame. PYTHON
  16. Q16 Given df = {'Mouse':[150,200,300,400],'Keyboard':[180,200,190,300],'Scanner':[200,280,330,450]} indexed Jan-April โ€” answer 6 sub-parts. PYTHON
  17. Q17 Create a DataFrame using lists (books data); display Class XII books, books priced above 250, and plot a line chart. PYTHON
  18. Q18 Country/Population/BirthRate DataFrame โ€” display China & India data, Brazil & Pakistan columns, export CSV, plot bar chart. PYTHON
  19. Q19 SQL: To create a school database and access it. SQL
  20. Q20 SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key). SQL
  21. Q21 SQL: To insert the details of at least 10 students in the above table. SQL
  22. Q22 SQL: To display the entire content of the table. SQL
  23. Q23 SQL: To display Rno, Name and Marks of students scoring marks more than 50. SQL
  24. Q24 SQL: To find the average of marks from the student table. SQL
  25. Q25 SQL: To find the number of students who are from section 'A'. SQL
  26. Q26 SQL: To display information of all students whose name starts with 'AN'. SQL
  27. Q27 SQL: To display Rno, Name, DOB of students born between '2005-01-01' and '2005-12-31'. SQL
  28. Q28 SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names. SQL
  29. Q29 SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks. SQL
  30. Q30 SQL: To display the unique sections available in the table. SQL
  31. Q31 SQL: To display the name and class of students whose marks are less than 33. SQL
  32. Q32 SQL: To display the structure of the student table. SQL
  33. Q33 SQL: To display the Name and DOB of students who were born in 2008. SQL
  34. Q34 Write MySQL queries demonstrating: (a) Aggregate Functions (b) Mathematical Functions (c) Text Functions (d) Date & Time Functions (e) GROUP BY. SQL
  35. Q35 Data Visualization (Line Chart): The maximum temperature (in degree C) of Delhi and Shimla for one week is given below. Plot both cities on the same l PY
  36. Q36 Data Visualization (Bar Chart - CBSE SQP 2024-25 pattern): The number of books read by students in one month is given below. Draw a bar chart with a d PY
  37. Q37 Data Visualization (Multiple Bar Chart from a DataFrame): Create a DataFrame of medals won by five countries (Gold, Silver, Bronze - sample data). Plo PY
  38. Q38 Data Visualization (Histogram): The weights (in kg) of 40 students of a class are given in the program. Plot a histogram with bins [30, 35, 40, 45, 50 PY
  39. Q39 Data Visualization (Plotting a DataFrame): Zone-wise quarterly sales (in lakh) are stored in a DataFrame. Plot (a) a line chart of all zones using df. PY
  40. Q40 Data Visualization (CSV to Chart): Import the file student_data.csv (RollNo, Name, Gender, Maths, Science, AI) into a DataFrame. Display the data, the PY
  41. Q41 SQL: To delete the details of a particular student from the student table (e.g. student_id = 7). SQL
  42. Q42 SQL: To display the details of students who scored more than 80 marks. SQL
  43. Q43 SQL: To find the minimum, maximum, sum and average of the marks in the student table. SQL
  44. Q44 SQL: To find the total number of customers from each country in the table customer (customer_id, customer_name, country) using GROUP BY. SQL
  45. Q45 Create a Series and print all the elements that are above the 75th percentile. PYTHON

Class IX โ€” Artificial Intelligence (417)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 31 Practicals

  1. Q1 PRINT: Write a program to print personal information like Name, Father's Name, Class and School Name. PYTHON
  2. Q2 PRINT: Write a program to print the following patterns using multiple print commands (right-angled triangle and inverted triangle of stars). PYTHON
  3. Q3 PRINT: Write a program to find the square of number 7. PYTHON
  4. Q4 PRINT: Write a program to find the sum of two numbers 15 and 20. PYTHON
  5. Q5 PRINT: Write a program to convert length given in kilometers into meters. PYTHON
  6. Q6 PRINT: Write a program to print the table of 5 up to five terms. PYTHON
  7. Q7 PRINT: Write a program to calculate Simple Interest if principle_amount = 2000, rate_of_interest = 4.5 and time = 10. PYTHON
  8. Q8 INPUT: Write a program to calculate the Area and Perimeter of a rectangle. PYTHON
  9. Q9 INPUT: Write a program to calculate the Area of a triangle with Base and Height. PYTHON
  10. Q10 INPUT: Write a program to calculate the average marks of 3 subjects. PYTHON
  11. Q11 INPUT: Write a program to calculate the discounted amount with discount %. PYTHON
  12. Q12 INPUT: Write a program to calculate the Surface Area and Volume of a Cuboid. PYTHON
  13. Q13 LIST: Create a list of children selected for science quiz - Arjun, Sonakshi, Vikram, Sandhya, Sonal, Isha, Kartik. Perform in sequence: print the whole list, delete 'Vikram', add 'Jay' at the end, remove the item at the second position. PYTHON
  14. Q14 LIST: Create a list num=[23,12,5,9,65,44]. Print the length of the list, the elements from second to fourth position using positive indexing and the elements from third to fifth position using negative indexing. PYTHON
  15. Q15 LIST: Create a list of first 10 even numbers, add 1 to each list item and print the final list. PYTHON
  16. Q16 LIST: Create a list List_1=[10,20,30,40]. Add the elements [14,15,12] using extend function. Now sort the final list in ascending order and print it. PYTHON
  17. Q17 IF: Write a program to check if a person can vote. PYTHON
  18. Q18 IF: Write a program to check the grade of a student. PYTHON
  19. Q19 IF: Input a number and check if the number is positive, negative or zero and display an appropriate message. PYTHON
  20. Q20 FOR: Write a program to print the first 10 natural numbers. PYTHON
  21. Q21 FOR: Write a program to print the first 10 even numbers. PYTHON
  22. Q22 WHILE: Write a program to print odd numbers from 1 to n. PYTHON
  23. Q23 FOR: Write a program to print the sum of first 10 natural numbers. PYTHON
  24. Q24 LIST + FOR: Write a program to find the sum of all numbers stored in a list. PYTHON
  25. Q25 ACTIVITY (Unit 1 - AI Reflection): Play the AI Game and record how each game uses a domain of AI - Rock Paper Scissors (Data), Semantris (NLP) and Quick Draw (Computer Vision). ACTIVITY
  26. Q26 ACTIVITY (Unit 1 - Problem Scoping): Fill a 4Ws Problem Canvas for an SDG-related problem in your community and write the problem statement. ACTIVITY
  27. Q27 ACTIVITY (Unit 1 - Data Acquisition): Identify the data features for the problem scoped and draw a System Map showing the relationship between them. ACTIVITY
  28. Q28 ACTIVITY (Unit 1/2 - Data Exploration): Collect data of daily water usage for one week, store it in a spreadsheet and draw a bar graph and a line graph to interpret the data. ACTIVITY
  29. Q29 ACTIVITY (Unit 3 - Statistics): Car Spotting and Tabulating - record the colours of 30 cars passing the school gate, tabulate the data and answer questions on probability. ACTIVITY
  30. Q30 ACTIVITY (Unit 1 - Evaluation): Understand True Positive, False Positive, True Negative and False Negative using a rain-prediction example and find the accuracy of the model. ACTIVITY
  31. Q31 ACTIVITY (Unit 4 - Generative AI): Guess the Real Image vs the AI-generated image, explore a Generative AI tool and list the ethical considerations of using Generative AI. ACTIVITY

Class X โ€” Artificial Intelligence (417)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 34 Practicals

  1. Q1 Write a program to print your Bio-Data. PYTHON
  2. Q2 Write a program to convert temperature from Celsius to Fahrenheit. PYTHON
  3. Q3 Write a program to check if a number is even or odd. PYTHON
  4. Q4 Write a simple menu-driven calculator program. PYTHON
  5. Q5 Write a program to print a name 5 times. PYTHON
  6. Q6 Write a program to calculate the LCM and HCF of two numbers. PYTHON
  7. Q7 Write a program to print a right-angled triangle pattern. PYTHON
  8. Q8 Write a program to count vowels and consonants in a string. PYTHON
  9. Q9 Write a menu-driven program to insert and delete elements in a list. PYTHON
  10. Q10 Write a program to add the elements of the two lists. PYTHON
  11. Q11 Write a program to calculate the mean of a given list. PYTHON
  12. Q12 Write a program to create a 2D array using NumPy. PYTHON
  13. Q13 Write a program to convert a Python list to a NumPy array. PYTHON
  14. Q14 Write a program to create a 3x3 matrix with values from 11 to 19. PYTHON
  15. Q15 Write a program to calculate mean, median and mode using NumPy. PYTHON
  16. Q16 Write a menu-driven program to calculate mean, mode and median using the statistics module. PYTHON
  17. Q17 Write a program to calculate variance and standard deviation. PYTHON
  18. Q18 Write a program to create a DataFrame to store data of candidates who appeared in interviews. PYTHON
  19. Q19 Write a program to create a DataFrame of players and filter the players who scored more than 1000 runs. PYTHON
  20. Q20 Write a program to display a line chart from (2,5) to (9,10). PYTHON
  21. Q21 Write a program to display a scatter chart for the points (2,5), (9,10), (8,3), (5,7), (6,18). PYTHON
  22. Q22 Write a program to represent mobile game ratings on a bar chart. PYTHON
  23. Q23 Plot monthly sales data for garments on a line chart. PYTHON
  24. Q24 Read the CSV file saved in your system and display 10 rows. PYTHON
  25. Q25 Read the CSV file saved in your system and display its information. PYTHON
  26. Q26 Write a program to read an image and display it using Python. PYTHON
  27. Q27 Write a program to read an image and identify its shape using Python. PYTHON
  28. Q28 Perform various tasks using OpenCV: load an image and give it a title, open it in grey scale, print its shape, display the maximum and minimum pixel values, crop a part of the image and save the image. PYTHON
  29. Q29 Unit 3 - Evaluating Models: Write a program to build a confusion matrix from actual and predicted values and calculate Accuracy, Precision, Recall and F1 Score. PYTHON
  30. Q30 Unit 5 - Computer Vision: Apply the convolution operator (kernel) on an image matrix using NumPy. PYTHON
  31. Q31 Unit 6 - NLP: Perform text normalisation (tokenisation, lowercase, stop-word removal) and create a Bag of Words and TF-IDF for three documents. PYTHON
  32. Q32 ACTIVITY (Unit 5): Visit an RGB colour tool (https://www.w3schools.com/colors/colors_rgb.asp) and answer the colour-mixing questions. ACTIVITY
  33. Q33 ACTIVITY (Unit 5): Create your own pixel art / animated GIF using Piskel (www.piskelapp.com). ACTIVITY
  34. Q34 ACTIVITY (Unit 4/5/6 - No-Code AI): Build a classification model with Teachable Machine / Orange Data Mining (e.g. Smart Sorter - recyclable vs non-recyclable) and record the steps. ACTIVITY

Class XI โ€” Artificial Intelligence (843)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 34 Practicals

  1. Q1 Unit 1: Categorize the given applications into the three domains of AI - Data Statistics, Computer Vision and Natural Language Processing. THEORY
  2. Q2 Unit 2: Identify ten companies currently hiring employees for specific AI positions. THEORY
  3. Q3 Unit 2: Note down the technical skills and soft skills listed by any two companies for a specific AI position. THEORY
  4. Q4 Python Level 1: Write a program to input a number and check whether it is positive, negative or zero, and also whether it is even or odd (operators and if-elif-else). PYTHON
  5. Q5 Python Level 1: Write a program to input marks of 5 subjects and display total, percentage and grade. PYTHON
  6. Q6 Python Level 1: Write a program to find the sum of digits and the reverse of a number and check whether it is a palindrome (while loop). PYTHON
  7. Q7 Python Level 1: Write a program to print the multiplication table of a number and find its factorial (for loop). PYTHON
  8. Q8 Python Level 1: Write a program to print all prime numbers between two numbers and the first n terms of the Fibonacci series (nested loops). PYTHON
  9. Q9 Python Level 2 (NumPy): Create NumPy arrays and perform arithmetic, statistical and indexing operations. PYTHON
  10. Q10 Python Level 2 (NumPy - Matrices): Create two 3x3 matrices and find their sum, product, transpose and determinant. PYTHON
  11. Q11 Python Level 2 (Pandas): Create a DataFrame of students, add a new column and display statistics. PYTHON
  12. Q12 Python Level 2 (Pandas + CSV): Read rainfall.csv into a DataFrame and analyse it (head, shape, mean, maximum and minimum rainfall month). PYTHON
  13. Q13 Python Level 2 (Scikit-learn): Load the Iris dataset, split it into training and testing sets, train a classifier and find its accuracy. PYTHON
  14. Q14 Unit 5: Identification of the level of measurement (Nominal, Ordinal, Interval, Ratio) of given data. THEORY
  15. Q15 Unit 5: Python program to demonstrate the use of mean, median, mode, standard deviation and variance. PYTHON
  16. Q16 Unit 5: Python program to visualise data using a LINE graph (monthly rainfall from rainfall.csv). PYTHON
  17. Q17 Unit 5: Python program to visualise data using a BAR graph. PYTHON
  18. Q18 Unit 5: Python program to visualise data using a HISTOGRAM. PYTHON
  19. Q19 Unit 5: Python program to visualise data using a SCATTER graph. PYTHON
  20. Q20 Unit 5: Python program to visualise data using a PIE chart. PYTHON
  21. Q21 Unit 4: Create an Empathy Map for a given scenario - 'Elderly people in the colony find it difficult to use digital payment apps'. THEORY
  22. Q22 Unit 4: Project Abstract Creation using the Design Thinking Framework (5W1H and SDG alignment). THEORY
  23. Q23 Unit 6: Calculation of Pearson's correlation coefficient in MS Excel. ACTIVITY
  24. Q24 Unit 6: Demonstration of Linear Regression in MS Excel. ACTIVITY
  25. Q25 Unit 6 (Advanced learners): Demonstration of Linear Regression using a Python program. PYTHON
  26. Q26 Unit 6 (Advanced learners): Demonstration of k-Nearest Neighbour (KNN) classification using a Python program. PYTHON
  27. Q27 Unit 6 (Advanced learners): Demonstration of k-Means clustering using a Python program. PYTHON
  28. Q28 Unit 7: Create a chatbot for ordering ice-creams using Google Dialogflow (or Botsify / Botpress). ACTIVITY
  29. Q29 Unit 7 (Advanced learners): Creating a simple rule-based chatbot using Python. PYTHON
  30. Q30 Unit 7 (Advanced learners): Program to print the POS (Parts of Speech) tags of a statement. PYTHON
  31. Q31 Unit 7: Write an article on 'IBM Project Debater - Interesting facts'. THEORY
  32. Q32 Unit 8: Summarize your insights and interpretations from the video 'Humans Need Not Apply'. THEORY
  33. Q33 Unit 8: Comparative study of AI policies (guidelines and principles) established by various organisations and regulatory bodies. THEORY
  34. Q34 Unit 8: Understanding ethical dilemmas using Moral Machine and Survival of the Best Fit. ACTIVITY

Class XII โ€” Artificial Intelligence (843)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 25 Practicals

  1. Q1 Python 1: Write Python code to create a Pandas DataFrame using any sequence data type. (a) Display the DataFrame (b) Display first 5 records (c) Display last 10 records (d) Display the number of missing values in the dataset. PYTHON
  2. Q2 Python 2: Download a dataset in CSV form from any public open-source website. (a) Read the CSV file and convert it into a Pandas DataFrame (b) Perform statistical functions to check the data, check missing values and fill the missing data. PYTHON
  3. Q3 Python 3: Import data from a CSV file into a DataFrame, process it and export the result to a new CSV file. PYTHON
  4. Q4 Python 4: Handle missing values in a dataset using dropna(), fillna() and interpolate(). PYTHON
  5. Q5 Python 5: Python code to evaluate a classification model - confusion matrix, accuracy, precision, recall and F1 score. PYTHON
  6. Q6 Python 6: Python code to evaluate a regression model using MAE, MSE, RMSE and R-squared. PYTHON
  7. Q7 Python 7 (Optional): Demonstration of train-test split in Linear Regression using Python. PYTHON
  8. Q8 Python 8: Build a TensorFlow model to convert Celsius to Fahrenheit (a single-neuron neural network that learns the formula from data). PYTHON
  9. Q9 Python 9 (Advanced learners): Working with OpenCV to load, display and resize images. PYTHON
  10. Q10 Unit 3 Activity: Binary Art - recreate an image with 0s and 1s using Python. PYTHON
  11. Q11 Python 10 (Advanced learners): Write Python code to initialise the Gemini API and create a chatbot. PYTHON
  12. Q12 Unit 2 Activity: Calculate MSE and RMSE values for the given data using MS Excel. ACTIVITY
  13. Q13 Unit 2 Activity: Calculate Precision, Recall, F1 score and Accuracy from the given confusion matrix. ACTIVITY
  14. Q14 Orange 1: Perform the step-wise procedure of Data Visualization using the Orange Data Mining tool (Iris dataset - Scatter Plot, Box Plot, Distributions). ACTIVITY
  15. Q15 Orange 2: Perform Classification with the Orange Data Mining tool. ACTIVITY
  16. Q16 Orange 3: Evaluate the Classification Model with Orange (Test and Score, Confusion Matrix). ACTIVITY
  17. Q17 Orange 4: Perform Image Analytics using the Orange Data Mining tool. ACTIVITY
  18. Q18 Orange 5: Write down the steps to visualise word frequencies with a Word Cloud using the Orange Data Mining tool. ACTIVITY
  19. Q19 Orange 6 (Unit 5): Perform Big Data analytics with the Orange Data Mining tool. ACTIVITY
  20. Q20 Unit 6 Activity: Explore Machine Learning for Kids to create a neural network for identifying animals and birds. ACTIVITY
  21. Q21 Unit 6 Activity: Classification problem using TensorFlow Playground. ACTIVITY
  22. Q22 Unit 6 Activity: Regression problem using TensorFlow Playground. ACTIVITY
  23. Q23 Unit 7 Activity: Generative AI tools - craft prompts in Google Gemini / ChatGPT, design with Canva Magic Studio and create a video with Animaker AI. ACTIVITY
  24. Q24 Unit 3 Activity: Creating a website containing an ML model (Teachable Machine + website). ACTIVITY
  25. Q25 Data Storytelling: Using data on student enrolment, attendance and dropout rates, create a data story exploring the impact of the Mid-Day Meal Scheme (MDMS) on dropout rates. PYTHON

๐Ÿš€ Live Project Titles (80 = 40 CS/IP + 40 AI)

๐Ÿ“˜ CBSE Syllabus 2026-27 — All Classes & Subjects

AI (417) IX & X · AI (843) XI & XII · Computer Science (083) XI & XII · Informatics Practices (065) XI & XII — unit-wise marks, topics with progress tick-list, practical scheme, CBSE practical list linked to solved practicals, and PDF / Word download

Class XI โ€” Computer Science (083)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 29 Practicals

๐Ÿ“˜ View Syllabus 2026-27 0%
๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

Q1 THEORY / VIVA

Introduction to Computer System Organization โ€” Draw & explain the functional diagram of a computer; explain Input, Output devices, Software, Hardware, Memory and Operating System.

FUNCTIONAL DIAGRAM (describe in file, draw neatly with a scale/computer generated diagram):

        +----------------+        +----------------+
        |  INPUT UNIT    | -----> |      CPU        |
        | Keyboard,Mouse |        |  CU + ALU + Reg |
        +----------------+        +--------+-------+
                                            |
                                   +--------v-------+
                                   |  MEMORY UNIT   |
                                   | Primary(RAM/ROM)|
                                   | Secondary(HDD) |
                                   +--------+-------+
                                            |
        +----------------+        +--------v-------+
        |  OUTPUT UNIT   | <----- |      CPU        |
        | Monitor,Printer|        +----------------+
        +----------------+

Key points to write:
1. Hardware   -> Physical parts (CPU, RAM, Keyboard, Monitor, Printer)
2. Software   -> Programs & instructions (System SW - OS; Application SW - MS Word, Python)
3. Input Devices  -> Keyboard, Mouse, Scanner, Mic, Joystick
4. Output Devices -> Monitor, Printer, Speaker, Plotter
5. Memory     -> Primary(RAM-volatile, ROM-non volatile), Secondary(HDD, SSD, Pen drive)
6. Operating System -> System software that manages hardware & software resources
   and acts as an interface between user and computer (e.g. Windows, Ubuntu Linux).
โ–ถ Sample Output
(Diagram-based theory answer โ€” no program output; draw the diagram neatly in the practical file.)
๐Ÿ’ก Explanation: Viva-friendly theory practical. Draw the block diagram: Input Unit โ†’ CPU (CU + ALU + Registers) โ†’ Memory Unit โ†’ Output Unit, with a two-way bus connecting CPU and Memory.
Q2 THEORY / VIVA

Introduction to Python Programming Language โ€” history, installation, features of Python & various Python interpreters.

1. HISTORY
   - Created by Guido van Rossum, released 1991 (Netherlands).
   - Named after 'Monty Python's Flying Circus' (not the snake!).
   - Python 3.x is the current standard (CBSE uses Python 3).

2. INSTALLATION (Windows)
   Step 1: Download from https://www.python.org/downloads/
   Step 2: Run installer -> tick 'Add Python to PATH' -> Install Now
   Step 3: Verify: open cmd -> type  python --version
   Step 4: Open IDLE (Python's built-in editor) from Start Menu

3. FEATURES OF PYTHON
   - Easy to learn & read (simple English-like syntax)
   - Interpreted (executes line by line, no separate compile step)
   - Free and Open Source
   - Portable / Platform Independent (runs on Windows, Linux, Mac)
   - Dynamically Typed (no need to declare variable type)
   - Extensive standard library (math, random, statistics, pandas...)
   - Supports OOP as well as procedural programming

4. PYTHON INTERPRETERS / MODES
   - Interactive Mode : >>> prompt, executes one statement at a time
   - Script Mode       : write .py file, run complete program at once
   - IDEs/Interpreters : IDLE, PyCharm, Jupyter Notebook, Anaconda, VS Code
โ–ถ Sample Output
(Theory answer โ€” no program output; write in practical file for viva preparation.)
๐Ÿ’ก Explanation: Cover: Guido van Rossum (1991), interpreted/high-level/open-source language, IDLE installation steps, and interpreter types.
Q3 PYTHON

Write a python program to Input a welcome message and display it.

msg = input("Enter your welcome message: ")
print(msg)
โ–ถ Sample Output
Enter your welcome message: Welcome to KV Shalimar Bagh!
Welcome to KV Shalimar Bagh!
๐Ÿ’ก Explanation: input() always returns a string; print() displays it as-is on screen.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ msg
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Welcome to KV Shalimar Bagh! (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output
LineCodeWhat it does
1
msg = input("Enter your welcome message: ")
โŒจ๏ธ Input Shows the message "Enter your welcome message: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable msg
2
print(msg)
๐Ÿ–ฅ๏ธ Output Displays the value of msg on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
msg = input("Enter your welcome message: ")
msg = 'Welcome to KV Shalimar Bagh!'
Enter your welcome message: Welcome to KV Shalimar Bagh!
22
print(msg)
Welcome to KV Shalimar Bagh!
Q4 PYTHON

Write a python program to Input two numbers and display the larger / smaller number.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
    print(a, "is larger and", b, "is smaller")
elif b > a:
    print(b, "is larger and", a, "is smaller")
else:
    print("Both numbers are equal")
โ–ถ Sample Output
Enter first number: 45
Enter second number: 78
78 is larger and 45 is smaller
๐Ÿ’ก Explanation: Basic if-elif-else comparison. Real life: comparing marks of two students to decide rank.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ a, b
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 45, 78 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision
LineCodeWhat it does
1
a = int(input("Enter first number: "))
โŒจ๏ธ Input Shows "Enter first number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable a
2
b = int(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable b
4
if a > b:
๐Ÿ”€ Decision CHECKS whether a is greater than b. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
print(a, "is larger and", b, "is smaller")
๐Ÿ–ฅ๏ธ Output Displays the value of a, then the text "is larger and", then the value of b, then the text "is smaller" on the screen
6
elif b > a:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether b is greater than a
7
print(b, "is larger and", a, "is smaller")
๐Ÿ–ฅ๏ธ Output Displays the value of b, then the text "is larger and", then the value of a, then the text "is smaller" on the screen
8
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
9
print("Both numbers are equal")
๐Ÿ–ฅ๏ธ Output Displays the text "Both numbers are equal" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
a = int(input("Enter first number: "))
a = 45
Enter first number: 45
22
b = int(input("Enter second number: "))
b = 78
Enter second number: 78
34
if a > b:
condition is FALSE โ†’ skips this block
46
elif b > a:
condition is TRUE โ†’ enters the block
57
print(b, "is larger and", a, "is smaller")
78 is larger and 45 is smaller
Q5 PYTHON

Write a python program to Input three numbers and display the largest / smallest number.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

largest = max(a, b, c)
smallest = min(a, b, c)
print("Largest number =", largest)
print("Smallest number =", smallest)

# Without built-in functions (for exam - manual logic)
if a >= b and a >= c:
    largest = a
elif b >= a and b >= c:
    largest = b
else:
    largest = c
print("Largest (manual method) =", largest)
โ–ถ Sample Output
Enter first number: 12
Enter second number: 45
Enter third number: 30
Largest number = 45
Smallest number = 12
Largest (manual method) = 45
๐Ÿ’ก Explanation: Show both max()/min() (quick) and nested-if (exam-preferred logic) methods.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ a, b, c
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 12, 45, 30 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
1
a = int(input("Enter first number: "))
โŒจ๏ธ Input Shows "Enter first number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable a
2
b = int(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable b
3
c = int(input("Enter third number: "))
โŒจ๏ธ Input Shows "Enter third number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable c
5
largest = max(a, b, c)
๐Ÿงฎ Store / Calculate Finds the largest value among a, b, c; the result is stored in variable largest
6
smallest = min(a, b, c)
๐Ÿงฎ Store / Calculate Finds the smallest value among a, b, c; the result is stored in variable smallest
7
print("Largest number =", largest)
๐Ÿ–ฅ๏ธ Output Displays the text "Largest number =", then the value of largest on the screen
8
print("Smallest number =", smallest)
๐Ÿ–ฅ๏ธ Output Displays the text "Smallest number =", then the value of smallest on the screen
๐Ÿ“Œ Without built-in functions (for exam - manual logic)
11
if a >= b and a >= c:
๐Ÿ”€ Decision CHECKS whether (a is greater than or equal to b AND a is greater than or equal to c). If True, the indented lines below run; otherwise Python jumps to the elif/else part
12
largest = a
๐Ÿงฎ Store / Calculate Stores the value of a in variable largest
13
elif b >= a and b >= c:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (b is greater than or equal to a AND b is greater than or equal to c)
14
largest = b
๐Ÿงฎ Store / Calculate Stores the value of b in variable largest
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
largest = c
๐Ÿงฎ Store / Calculate Stores the value of c in variable largest
17
print("Largest (manual method) =", largest)
๐Ÿ–ฅ๏ธ Output Displays the text "Largest (manual method) =", then the value of largest on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
a = int(input("Enter first number: "))
a = 12
Enter first number: 12
22
b = int(input("Enter second number: "))
b = 45
Enter second number: 45
33
c = int(input("Enter third number: "))
c = 30
Enter third number: 30
45
largest = max(a, b, c)
largest = 45
56
smallest = min(a, b, c)
smallest = 12
67
print("Largest number =", largest)
Largest number = 45
78
print("Smallest number =", smallest)
Smallest number = 12
811
if a >= b and a >= c:
condition is FALSE โ†’ skips this block
913
elif b >= a and b >= c:
condition is TRUE โ†’ enters the block
1014
largest = b
1117
print("Largest (manual method) =", largest)
Largest (manual method) = 45
Q6 PYTHON

Write a python program to input two integers x and n, compute xโฟ.

x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))

# Method 1: built-in operator
print("x^n using ** operator =", x ** n)

# Method 2: manual loop (exam favourite)
result = 1
for i in range(n):
    result = result * x
print("x^n using loop =", result)
โ–ถ Sample Output
Enter value of x: 2
Enter value of n: 5
x^n using ** operator = 32
x^n using loop = 32
๐Ÿ’ก Explanation: Demonstrates exponent operator ** and manual iterative computation using a for loop.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ x, n
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
1
x = int(input("Enter value of x: "))
โŒจ๏ธ Input Shows "Enter value of x: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable x
2
n = int(input("Enter value of n: "))
โŒจ๏ธ Input Shows "Enter value of n: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
๐Ÿ“Œ Method 1: built-in operator
5
print("x^n using ** operator =", x ** n)
๐Ÿ–ฅ๏ธ Output Displays the text "x^n using ** operator =", then the value of x ** n on the screen
๐Ÿ“Œ Method 2: manual loop (exam favourite)
8
result = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable result
9
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
10
result = result * x
๐Ÿงฎ Store / Calculate Stores the value of result * x (calculated using ร—) in variable result
11
print("x^n using loop =", result)
๐Ÿ–ฅ๏ธ Output Displays the text "x^n using loop =", then the value of result on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
x = int(input("Enter value of x: "))
x = 2
Enter value of x: 2
22
n = int(input("Enter value of n: "))
n = 5
Enter value of n: 5
35
print("x^n using ** operator =", x ** n)
x^n using ** operator = 32
48
result = 1
result = 1
59
for i in range(n):
next item taken
i = 0
610
result = result * x
result = 2
79
for i in range(n):
next item taken
i = 1
810
result = result * x
result = 4
99
for i in range(n):
next item taken
i = 2
1010
result = result * x
result = 8
119
for i in range(n):
next item taken
i = 3
1210
result = result * x
result = 16
139
for i in range(n):
next item taken
i = 4
1410
result = result * x
result = 32
159
for i in range(n):
no items left โ†’ loop ends
1611
print("x^n using loop =", result)
x^n using loop = 32
Q7 PYTHON

Write a python program to Generate number/star patterns using nested loop.

n = int(input("Enter number of rows: "))

# Pattern 1: Right triangle of stars
for i in range(1, n + 1):
    print("*" * i)

print()
# Pattern 2: Number triangle
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

print()
# Pattern 3: Inverted star triangle
for i in range(n, 0, -1):
    print("*" * i)
โ–ถ Sample Output
Enter number of rows: 4
*
**
***
****

1 
1 2 
1 2 3 
1 2 3 4 

****
***
**
*
๐Ÿ’ก Explanation: Outer loop controls rows, inner loop controls columns โ€” the core idea behind all nested-loop patterns.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 4 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
1
n = int(input("Enter number of rows: "))
โŒจ๏ธ Input Shows "Enter number of rows: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
๐Ÿ“Œ Pattern 1: Right triangle of stars
4
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
5
print("*" * i)
๐Ÿ–ฅ๏ธ Output Displays the value of "*" * i on the screen
7
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
๐Ÿ“Œ Pattern 2: Number triangle
9
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
10
for j in range(1, i + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to i + 1 - 1; for each number, j takes that value and the indented block runs once
11
print(j, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of j on the screen (ends with " " instead of a new line)
12
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
14
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
๐Ÿ“Œ Pattern 3: Inverted star triangle
16
for i in range(n, 0, -1):
๐Ÿ” Loop LOOP: gives the numbers from n up to (not including) 0, jumping by -1; for each number, i takes that value and the indented block runs once
17
print("*" * i)
๐Ÿ–ฅ๏ธ Output Displays the value of "*" * i on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("Enter number of rows: "))
n = 4
Enter number of rows: 4
24
for i in range(1, n + 1):
next item taken
i = 1
35
print("*" * i)
*
44
for i in range(1, n + 1):
next item taken
i = 2
55
print("*" * i)
**
64
for i in range(1, n + 1):
next item taken
i = 3
75
print("*" * i)
***
84
for i in range(1, n + 1):
next item taken
i = 4
95
print("*" * i)
****
104
for i in range(1, n + 1):
no items left โ†’ loop ends
117
print()
129
for i in range(1, n + 1):
next item taken
i = 1
1310
for j in range(1, i + 1):
next item taken
j = 1
1411
print(j, end=" ")
1 
1510
for j in range(1, i + 1):
no items left โ†’ loop ends
1612
print()
179
for i in range(1, n + 1):
next item taken
i = 2
1810
for j in range(1, i + 1):
next item taken
1911
print(j, end=" ")
1 
2010
for j in range(1, i + 1):
next item taken
j = 2
2111
print(j, end=" ")
2 
2210
for j in range(1, i + 1):
no items left โ†’ loop ends
2312
print()
249
for i in range(1, n + 1):
next item taken
i = 3
2510
for j in range(1, i + 1):
next item taken
j = 1
2611
print(j, end=" ")
1 
2710
for j in range(1, i + 1):
next item taken
j = 2
2811
print(j, end=" ")
2 
2910
for j in range(1, i + 1):
next item taken
j = 3
3011
print(j, end=" ")
3 
3110
for j in range(1, i + 1):
no items left โ†’ loop ends
3212
print()

โ€ฆ Python runs 22 more line-steps in the same way (loops repeat the same lines). Final values: n = 4, i = 1, j = 4

Q8 PYTHON

Write a python program to input value of x and n and print the sum of the series: (i) 1+x+xยฒ+xยณ+...+xโฟ (ii) 1-x+xยฒ-xยณ+...ยฑxโฟ (iii) x+xยฒ/2-xยณ/3+...ยฑxโฟ/n (iv) x+xยฒ/2!-xยณ/3!+...ยฑxโฟ/n!

import math

x = float(input("Enter value of x: "))
n = int(input("Enter value of n: "))

# (i) 1 + x + x^2 + ... + x^n
s1 = 0
for i in range(0, n + 1):
    s1 += x ** i
print("(i)  Sum =", s1)

# (ii) 1 - x + x^2 - x^3 + ... (alternating, starts +1)
s2 = 0
sign = 1
for i in range(0, n + 1):
    s2 += sign * (x ** i)
    sign *= -1
print("(ii) Sum =", s2)

# (iii) x + x^2/2 - x^3/3 + x^4/4 - ...
s3 = 0
sign = 1
for i in range(1, n + 1):
    s3 += sign * (x ** i) / i
    sign *= -1
print("(iii) Sum =", s3)

# (iv) x + x^2/2! - x^3/3! + x^4/4! - ...
s4 = 0
sign = 1
for i in range(1, n + 1):
    s4 += sign * (x ** i) / math.factorial(i)
    sign *= -1
print("(iv) Sum =", s4)
โ–ถ Sample Output
Enter value of x: 2
Enter value of n: 3
(i)  Sum = 15.0
(ii) Sum = -5.0
(iii) Sum = 2.6666666666666665
(iv) Sum = 1.3333333333333333
๐Ÿ’ก Explanation: Each series uses a running 'sign' variable (+1/-1) to alternate terms. Series (iv) needs math.factorial().
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ x, n
โžœ
โ‘ก PROCESSuses a for loop; module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2, 3 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
3
x = float(input("Enter value of x: "))
โŒจ๏ธ Input Shows "Enter value of x: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable x
4
n = int(input("Enter value of n: "))
โŒจ๏ธ Input Shows "Enter value of n: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
๐Ÿ“Œ (i) 1 + x + x^2 + ... + x^n
7
s1 = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s1
8
for i in range(0, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 0 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
9
s1 += x ** i
๐Ÿงฎ Store / Calculate Adds x ** i to s1 (same as s1 = s1 + x ** i)
10
print("(i)  Sum =", s1)
๐Ÿ–ฅ๏ธ Output Displays the text "(i) Sum =", then the value of s1 on the screen
๐Ÿ“Œ (ii) 1 - x + x^2 - x^3 + ... (alternating, starts +1)
13
s2 = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s2
14
sign = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable sign
15
for i in range(0, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 0 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
16
s2 += sign * (x ** i)
๐Ÿงฎ Store / Calculate Adds sign * (x ** i) to s2 (same as s2 = s2 + sign * (x ** i))
17
sign *= -1
๐Ÿงฎ Store / Calculate Multiplies sign by -1 (same as sign = sign ร— -1)
18
print("(ii) Sum =", s2)
๐Ÿ–ฅ๏ธ Output Displays the text "(ii) Sum =", then the value of s2 on the screen
๐Ÿ“Œ (iii) x + x^2/2 - x^3/3 + x^4/4 - ...
21
s3 = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s3
22
sign = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable sign
23
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
24
s3 += sign * (x ** i) / i
๐Ÿงฎ Store / Calculate Adds sign * (x ** i) / i to s3 (same as s3 = s3 + sign * (x ** i) / i)
25
sign *= -1
๐Ÿงฎ Store / Calculate Multiplies sign by -1 (same as sign = sign ร— -1)
26
print("(iii) Sum =", s3)
๐Ÿ–ฅ๏ธ Output Displays the text "(iii) Sum =", then the value of s3 on the screen
๐Ÿ“Œ (iv) x + x^2/2! - x^3/3! + x^4/4! - ...
29
s4 = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s4
30
sign = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable sign
31
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
32
s4 += sign * (x ** i) / math.factorial(i)
๐Ÿงฎ Store / Calculate Adds sign * (x ** i) / math.factorial(i) to s4 (same as s4 = s4 + sign * (x ** i) / math.fโ€ฆ)
33
sign *= -1
๐Ÿงฎ Store / Calculate Multiplies sign by -1 (same as sign = sign ร— -1)
34
print("(iv) Sum =", s4)
๐Ÿ–ฅ๏ธ Output Displays the text "(iv) Sum =", then the value of s4 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import math
23
x = float(input("Enter value of x: "))
x = 2.0
Enter value of x: 2
34
n = int(input("Enter value of n: "))
n = 3
Enter value of n: 3
47
s1 = 0
s1 = 0
58
for i in range(0, n + 1):
next item taken
i = 0
69
s1 += x ** i
s1 = 1.0
78
for i in range(0, n + 1):
next item taken
i = 1
89
s1 += x ** i
s1 = 3.0
98
for i in range(0, n + 1):
next item taken
i = 2
109
s1 += x ** i
s1 = 7.0
118
for i in range(0, n + 1):
next item taken
i = 3
129
s1 += x ** i
s1 = 15.0
138
for i in range(0, n + 1):
no items left โ†’ loop ends
1410
print("(i)  Sum =", s1)
(i)  Sum = 15.0
1513
s2 = 0
s2 = 0
1614
sign = 1
sign = 1
1715
for i in range(0, n + 1):
next item taken
i = 0
1816
s2 += sign * (x ** i)
s2 = 1.0
1917
sign *= -1
sign = -1
2015
for i in range(0, n + 1):
next item taken
i = 1
2116
s2 += sign * (x ** i)
s2 = -1.0
2217
sign *= -1
sign = 1
2315
for i in range(0, n + 1):
next item taken
i = 2
2416
s2 += sign * (x ** i)
s2 = 3.0
2517
sign *= -1
sign = -1
2615
for i in range(0, n + 1):
next item taken
i = 3
2716
s2 += sign * (x ** i)
s2 = -5.0
2817
sign *= -1
sign = 1
2915
for i in range(0, n + 1):
no items left โ†’ loop ends
3018
print("(ii) Sum =", s2)
(ii) Sum = -5.0
3121
s3 = 0
s3 = 0
3222
sign = 1

โ€ฆ Python runs 24 more line-steps in the same way (loops repeat the same lines). Final values: x = 2.0, n = 3, s1 = 15.0, i = 3, s2 = -5.0, sign = -1, s3 = 2.6666666666666665, s4 = 1.3333333333333333

Q9 PYTHON

Write a python program to determine whether a number is a Perfect number, an Armstrong number or a Palindrome.

n = int(input("Enter a number: "))
orig = n

# Perfect number: sum of proper divisors == number  (e.g. 6 = 1+2+3)
s = 0
for i in range(1, n):
    if n % i == 0:
        s += i
if s == n:
    print(n, "is a Perfect number")
else:
    print(n, "is NOT a Perfect number")

# Armstrong number: sum of (digits ^ number_of_digits) == number  (e.g. 153)
temp = n
digits = len(str(n))
s2 = 0
while temp > 0:
    d = temp % 10
    s2 += d ** digits
    temp //= 10
if s2 == orig:
    print(n, "is an Armstrong number")
else:
    print(n, "is NOT an Armstrong number")

# Palindrome: reads same forward & backward (e.g. 121)
temp = n
rev = 0
while temp > 0:
    rev = rev * 10 + temp % 10
    temp //= 10
if rev == orig:
    print(n, "is a Palindrome")
else:
    print(n, "is NOT a Palindrome")
โ–ถ Sample Output
Enter a number: 153
153 is NOT a Perfect number
153 is an Armstrong number
153 is NOT a Palindrome
๐Ÿ’ก Explanation: Three independent checks in one program โ€” a very common CBSE board question, asked separately too.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else; a while loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 153 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
1
n = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
2
orig = n
๐Ÿงฎ Store / Calculate Stores the value of n in variable orig
๐Ÿ“Œ Perfect number: sum of proper divisors == number (e.g. 6 = 1+2+3)
5
s = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s
6
for i in range(1, n):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n - 1; for each number, i takes that value and the indented block runs once
7
if n % i == 0:
๐Ÿ”€ Decision CHECKS whether n % i is equal to 0. If True, the indented lines below run; otherwise they are skipped
8
s += i
๐Ÿงฎ Store / Calculate Adds i to s (same as s = s + i)
9
if s == n:
๐Ÿ”€ Decision CHECKS whether s is equal to n. If True, the indented lines below run; otherwise Python jumps to the elif/else part
10
print(n, "is a Perfect number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a Perfect number" on the screen
11
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
12
print(n, "is NOT a Perfect number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is NOT a Perfect number" on the screen
๐Ÿ“Œ Armstrong number: sum of (digits ^ number_of_digits) == number (e.g. 153)
15
temp = n
๐Ÿงฎ Store / Calculate Stores the value of n in variable temp
16
digits = len(str(n))
๐Ÿงฎ Store / Calculate Counts the number of items / characters in str(n); the result is stored in variable digits
17
s2 = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s2
18
while temp > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as temp is greater than 0; checks the condition before every round
19
d = temp % 10
๐Ÿงฎ Store / Calculate Stores the value of temp % 10 (calculated using % (remainder)) in variable d
20
s2 += d ** digits
๐Ÿงฎ Store / Calculate Adds d ** digits to s2 (same as s2 = s2 + d ** digits)
21
temp //= 10
๐Ÿงฎ Store / Calculate Updates temp using temp //= 10
22
if s2 == orig:
๐Ÿ”€ Decision CHECKS whether s2 is equal to orig. If True, the indented lines below run; otherwise Python jumps to the elif/else part
23
print(n, "is an Armstrong number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is an Armstrong number" on the screen
24
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
25
print(n, "is NOT an Armstrong number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is NOT an Armstrong number" on the screen
๐Ÿ“Œ Palindrome: reads same forward & backward (e.g. 121)
28
temp = n
๐Ÿงฎ Store / Calculate Stores the value of n in variable temp
29
rev = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable rev
30
while temp > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as temp is greater than 0; checks the condition before every round
31
rev = rev * 10 + temp % 10
๐Ÿงฎ Store / Calculate Stores the value of rev * 10 + temp % 10 (calculated using +) in variable rev
32
temp //= 10
๐Ÿงฎ Store / Calculate Updates temp using temp //= 10
33
if rev == orig:
๐Ÿ”€ Decision CHECKS whether rev is equal to orig. If True, the indented lines below run; otherwise Python jumps to the elif/else part
34
print(n, "is a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a Palindrome" on the screen
35
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
36
print(n, "is NOT a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is NOT a Palindrome" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("Enter a number: "))
n = 153
Enter a number: 153
22
orig = n
orig = 153
35
s = 0
s = 0
46
for i in range(1, n):
next item taken
i = 1
57
if n % i == 0:
condition is TRUE โ†’ enters the block
68
s += i
s = 1
76
for i in range(1, n):
next item taken
i = 2
87
if n % i == 0:
condition is FALSE โ†’ skips this block
96
for i in range(1, n):
next item taken
i = 3
107
if n % i == 0:
condition is TRUE โ†’ enters the block
118
s += i
s = 4
126
for i in range(1, n):
next item taken
i = 4
137
if n % i == 0:
condition is FALSE โ†’ skips this block
146
for i in range(1, n):
next item taken
i = 5
157
if n % i == 0:
condition is FALSE โ†’ skips this block
166
for i in range(1, n):
next item taken
i = 6
177
if n % i == 0:
condition is FALSE โ†’ skips this block
186
for i in range(1, n):
next item taken
i = 7
197
if n % i == 0:
condition is FALSE โ†’ skips this block
206
for i in range(1, n):
next item taken
i = 8
217
if n % i == 0:
condition is FALSE โ†’ skips this block
226
for i in range(1, n):
next item taken
i = 9
237
if n % i == 0:
condition is TRUE โ†’ enters the block
248
s += i
s = 13
256
for i in range(1, n):
next item taken
i = 10
267
if n % i == 0:
condition is FALSE โ†’ skips this block
276
for i in range(1, n):
next item taken
i = 11
287
if n % i == 0:
condition is FALSE โ†’ skips this block
296
for i in range(1, n):
next item taken
i = 12
307
if n % i == 0:
condition is FALSE โ†’ skips this block
316
for i in range(1, n):
next item taken
i = 13
327
if n % i == 0:
condition is FALSE โ†’ skips this block

โ€ฆ Python runs 315 more line-steps in the same way (loops repeat the same lines). Final values: n = 153, orig = 153, s = 81, i = 152, temp = 0, digits = 3, s2 = 153, d = 1, rev = 351

Q10 PYTHON

Write a python program to Input a number and check if the number is Prime or Composite.

n = int(input("Enter a number: "))
is_prime = True

if n <= 1:
    is_prime = False
else:
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            is_prime = False
            break

if is_prime:
    print(n, "is a Prime number")
else:
    print(n, "is a Composite number")
โ–ถ Sample Output
Enter a number: 17
17 is a Prime number
๐Ÿ’ก Explanation: Checking divisibility only up to โˆšn is the efficient method โ€” mention this optimisation in viva.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 17 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
n = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
2
is_prime = True
๐Ÿงฎ Store / Calculate Stores True in variable is_prime
4
if n <= 1:
๐Ÿ”€ Decision CHECKS whether n is less than or equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
is_prime = False
๐Ÿงฎ Store / Calculate Stores False in variable is_prime
6
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
7
for i in range(2, int(n ** 0.5) + 1):
๐Ÿ” Loop LOOP: gives the numbers from 2 up to int(n ** 0.5) + 1 - 1; for each number, i takes that value and the indented block runs once
8
if n % i == 0:
๐Ÿ”€ Decision CHECKS whether n % i is equal to 0. If True, the indented lines below run; otherwise they are skipped
9
is_prime = False
๐Ÿงฎ Store / Calculate Stores False in variable is_prime
10
break
๐Ÿ” Loop BREAK - leaves the loop immediately
12
if is_prime:
๐Ÿ”€ Decision CHECKS whether is_prime is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
13
print(n, "is a Prime number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a Prime number" on the screen
14
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
15
print(n, "is a Composite number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a Composite number" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("Enter a number: "))
n = 17
Enter a number: 17
22
is_prime = True
is_prime = True
34
if n <= 1:
condition is FALSE โ†’ skips this block
47
for i in range(2, int(n ** 0.5) + 1):
next item taken
i = 2
58
if n % i == 0:
condition is FALSE โ†’ skips this block
67
for i in range(2, int(n ** 0.5) + 1):
next item taken
i = 3
78
if n % i == 0:
condition is FALSE โ†’ skips this block
87
for i in range(2, int(n ** 0.5) + 1):
next item taken
i = 4
98
if n % i == 0:
condition is FALSE โ†’ skips this block
107
for i in range(2, int(n ** 0.5) + 1):
no items left โ†’ loop ends
1112
if is_prime:
condition is TRUE โ†’ enters the block
1213
print(n, "is a Prime number")
17 is a Prime number
Q11 PYTHON

Write a Python Program to print Fibonacci series up to the entered n positive number.

n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
    print(a, end=" ")
    a, b = b, a + b
โ–ถ Sample Output
Enter number of terms: 7
Fibonacci Series:
0 1 1 2 3 5 8 
๐Ÿ’ก Explanation: Fibonacci: each term = sum of previous two (0,1,1,2,3,5,8...). Python's tuple-swap a,b=b,a+b avoids a temp variable.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 7 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop
LineCodeWhat it does
1
n = int(input("Enter number of terms: "))
โŒจ๏ธ Input Shows "Enter number of terms: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
2
a, b = 0, 1
๐Ÿงฎ Store / Calculate Stores 0, 1 into a, b respectively
3
print("Fibonacci Series:")
๐Ÿ–ฅ๏ธ Output Displays the text "Fibonacci Series:" on the screen
4
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
5
print(a, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of a on the screen (ends with " " instead of a new line)
6
a, b = b, a + b
๐Ÿงฎ Store / Calculate Stores b, a + b into a, b respectively
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("Enter number of terms: "))
n = 7
Enter number of terms: 7
22
a, b = 0, 1
a = 0, b = 1
33
print("Fibonacci Series:")
Fibonacci Series:
44
for i in range(n):
next item taken
i = 0
55
print(a, end=" ")
0 
66
a, b = b, a + b
a = 1
74
for i in range(n):
next item taken
i = 1
85
print(a, end=" ")
1 
96
a, b = b, a + b
b = 2
104
for i in range(n):
next item taken
i = 2
115
print(a, end=" ")
1 
126
a, b = b, a + b
a = 2, b = 3
134
for i in range(n):
next item taken
i = 3
145
print(a, end=" ")
2 
156
a, b = b, a + b
a = 3, b = 5
164
for i in range(n):
next item taken
i = 4
175
print(a, end=" ")
3 
186
a, b = b, a + b
a = 5, b = 8
194
for i in range(n):
next item taken
i = 5
205
print(a, end=" ")
5 
216
a, b = b, a + b
a = 8, b = 13
224
for i in range(n):
next item taken
i = 6
235
print(a, end=" ")
8 
246
a, b = b, a + b
a = 13, b = 21
254
for i in range(n):
no items left โ†’ loop ends
Q12 PYTHON

Write a Python Program to Compute GCD/HCF and LCM of two Integers.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

x, y = a, b
while y:
    x, y = y, x % y
gcd = x
lcm = (a * b) // gcd

print("GCD/HCF =", gcd)
print("LCM =", lcm)
โ–ถ Sample Output
Enter first number: 12
Enter second number: 18
GCD/HCF = 6
LCM = 36
๐Ÿ’ก Explanation: Uses Euclid's Algorithm for GCD (fast method); LCM formula: (a*b)/GCD.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ a, b
โžœ
โ‘ก PROCESSuses a while loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 12, 18 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop
LineCodeWhat it does
1
a = int(input("Enter first number: "))
โŒจ๏ธ Input Shows "Enter first number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable a
2
b = int(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable b
4
x, y = a, b
๐Ÿงฎ Store / Calculate Stores a, b into x, y respectively
5
while y:
๐Ÿ” Loop LOOP: repeats the indented block as long as y is True (not empty / not zero); checks the condition before every round
6
x, y = y, x % y
๐Ÿงฎ Store / Calculate Stores y, x % y into x, y respectively
7
gcd = x
๐Ÿงฎ Store / Calculate Stores the value of x in variable gcd
8
lcm = (a * b) // gcd
๐Ÿงฎ Store / Calculate Stores the value of (a * b) // gcd (calculated using // (integer division)) in variable lcm
10
print("GCD/HCF =", gcd)
๐Ÿ–ฅ๏ธ Output Displays the text "GCD/HCF =", then the value of gcd on the screen
11
print("LCM =", lcm)
๐Ÿ–ฅ๏ธ Output Displays the text "LCM =", then the value of lcm on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
a = int(input("Enter first number: "))
a = 12
Enter first number: 12
22
b = int(input("Enter second number: "))
b = 18
Enter second number: 18
34
x, y = a, b
x = 12, y = 18
45
while y:
condition is TRUE โ†’ enters the block
56
x, y = y, x % y
x = 18, y = 12
65
while y:
condition is TRUE โ†’ enters the block
76
x, y = y, x % y
x = 12, y = 6
85
while y:
condition is TRUE โ†’ enters the block
96
x, y = y, x % y
x = 6, y = 0
105
while y:
condition is FALSE โ†’ loop ends
117
gcd = x
gcd = 6
128
lcm = (a * b) // gcd
lcm = 36
1310
print("GCD/HCF =", gcd)
GCD/HCF = 6
1411
print("LCM =", lcm)
LCM = 36
Q13 PYTHON

Write a Python Program to Count and display the number of vowels, consonants, uppercase, lowercase characters in a string.

s = input("Enter a string: ")
vowels = consonants = upper = lower = 0

for ch in s:
    if ch.isalpha():
        if ch.lower() in 'aeiou':
            vowels += 1
        else:
            consonants += 1
        if ch.isupper():
            upper += 1
        elif ch.islower():
            lower += 1

print("Vowels     :", vowels)
print("Consonants :", consonants)
print("Uppercase  :", upper)
print("Lowercase  :", lower)
โ–ถ Sample Output
Enter a string: Hello World 123
Vowels     : 3
Consonants : 7
Uppercase  : 2
Lowercase  : 8
๐Ÿ’ก Explanation: String methods isalpha(), isupper(), islower() do the heavy lifting; no need to hardcode A-Z ranges.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ s
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Hello World 123 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
s = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
2
vowels = consonants = upper = lower = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable vowels
4
for ch in s:
๐Ÿ” Loop LOOP: takes each item of s one-by-one into ch and runs the indented block for it
5
if ch.isalpha():
๐Ÿ”€ Decision CHECKS whether ch.isalpha() is True. If True, the indented lines below run; otherwise they are skipped
6
if ch.lower() in 'aeiou':
๐Ÿ”€ Decision CHECKS whether ch.lower() is present in 'aeiou'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
vowels += 1
๐Ÿงฎ Store / Calculate Adds 1 to vowels (same as vowels = vowels + 1)
8
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
9
consonants += 1
๐Ÿงฎ Store / Calculate Adds 1 to consonants (same as consonants = consonants + 1)
10
if ch.isupper():
๐Ÿ”€ Decision CHECKS whether ch.isupper() is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
11
upper += 1
๐Ÿงฎ Store / Calculate Adds 1 to upper (same as upper = upper + 1)
12
elif ch.islower():
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch.islower() is True
13
lower += 1
๐Ÿงฎ Store / Calculate Adds 1 to lower (same as lower = lower + 1)
15
print("Vowels     :", vowels)
๐Ÿ–ฅ๏ธ Output Displays the text "Vowels :", then the value of vowels on the screen
16
print("Consonants :", consonants)
๐Ÿ–ฅ๏ธ Output Displays the text "Consonants :", then the value of consonants on the screen
17
print("Uppercase  :", upper)
๐Ÿ–ฅ๏ธ Output Displays the text "Uppercase :", then the value of upper on the screen
18
print("Lowercase  :", lower)
๐Ÿ–ฅ๏ธ Output Displays the text "Lowercase :", then the value of lower on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
s = input("Enter a string: ")
s = 'Hello World 123'
Enter a string: Hello World 123
22
vowels = consonants = upper = lower = 0
vowels = 0, consonants = 0, upper = 0, lower = 0
34
for ch in s:
next item taken
ch = 'H'
45
if ch.isalpha():
condition is TRUE โ†’ enters the block
56
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
69
consonants += 1
consonants = 1
710
if ch.isupper():
condition is TRUE โ†’ enters the block
811
upper += 1
upper = 1
94
for ch in s:
next item taken
ch = 'e'
105
if ch.isalpha():
condition is TRUE โ†’ enters the block
116
if ch.lower() in 'aeiou':
condition is TRUE โ†’ enters the block
127
vowels += 1
vowels = 1
1310
if ch.isupper():
condition is FALSE โ†’ skips this block
1412
elif ch.islower():
condition is TRUE โ†’ enters the block
1513
lower += 1
lower = 1
164
for ch in s:
next item taken
ch = 'l'
175
if ch.isalpha():
condition is TRUE โ†’ enters the block
186
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
199
consonants += 1
consonants = 2
2010
if ch.isupper():
condition is FALSE โ†’ skips this block
2112
elif ch.islower():
condition is TRUE โ†’ enters the block
2213
lower += 1
lower = 2
234
for ch in s:
next item taken
245
if ch.isalpha():
condition is TRUE โ†’ enters the block
256
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
269
consonants += 1
consonants = 3
2710
if ch.isupper():
condition is FALSE โ†’ skips this block
2812
elif ch.islower():
condition is TRUE โ†’ enters the block
2913
lower += 1
lower = 3
304
for ch in s:
next item taken
ch = 'o'
315
if ch.isalpha():
condition is TRUE โ†’ enters the block
326
if ch.lower() in 'aeiou':
condition is TRUE โ†’ enters the block

โ€ฆ Python runs 53 more line-steps in the same way (loops repeat the same lines). Final values: s = 'Hello World 123', vowels = 3, consonants = 7, upper = 2, lower = 8, ch = '3'

Q14 PYTHON

Write a Python Program to Input a string and determine whether it is a palindrome or not; convert the case of characters in a string.

s = input("Enter a string: ")

if s == s[::-1]:
    print(s, "is a Palindrome")
else:
    print(s, "is NOT a Palindrome")

# Case conversion
print("UPPER CASE :", s.upper())
print("lower case :", s.lower())
print("Swap Case  :", s.swapcase())
print("Title Case :", s.title())
โ–ถ Sample Output
Enter a string: madam
madam is a Palindrome
UPPER CASE : MADAM
lower case : madam
Swap Case  : MADAM
Title Case : Madam
๐Ÿ’ก Explanation: s[::-1] reverses a string using slicing. upper/lower/swapcase/title are built-in string methods.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ s
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type madam (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
1
s = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
3
if s == s[::-1]:
๐Ÿ”€ Decision CHECKS whether s is equal to s[::-1]. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
print(s, "is a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of s, then the text "is a Palindrome" on the screen
5
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
6
print(s, "is NOT a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of s, then the text "is NOT a Palindrome" on the screen
๐Ÿ“Œ Case conversion
9
print("UPPER CASE :", s.upper())
๐Ÿ–ฅ๏ธ Output Displays the text "UPPER CASE :", then the value of s.upper() on the screen
10
print("lower case :", s.lower())
๐Ÿ–ฅ๏ธ Output Displays the text "lower case :", then the value of s.lower() on the screen
11
print("Swap Case  :", s.swapcase())
๐Ÿ–ฅ๏ธ Output Displays the text "Swap Case :", then the value of s.swapcase() on the screen
12
print("Title Case :", s.title())
๐Ÿ–ฅ๏ธ Output Displays the text "Title Case :", then the value of s.title() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
s = input("Enter a string: ")
s = 'madam'
Enter a string: madam
23
if s == s[::-1]:
condition is TRUE โ†’ enters the block
34
print(s, "is a Palindrome")
madam is a Palindrome
49
print("UPPER CASE :", s.upper())
UPPER CASE : MADAM
510
print("lower case :", s.lower())
lower case : madam
611
print("Swap Case  :", s.swapcase())
Swap Case  : MADAM
712
print("Title Case :", s.title())
Title Case : Madam
Q15 PYTHON

Write a Python Program to find the largest/smallest number in a list/tuple and display the position of that number.

lst = list(map(int, input("Enter numbers separated by space: ").split()))

largest = max(lst)
smallest = min(lst)

print("Largest number  :", largest, "at position", lst.index(largest))
print("Smallest number :", smallest, "at position", lst.index(smallest))
โ–ถ Sample Output
Enter numbers separated by space: 12 45 3 78 22
Largest number  : 78 at position 3
Smallest number : 3 at position 2
๐Ÿ’ก Explanation: list.index() returns the first matching position (0-based index).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 12 45 3 78 22 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
3
largest = max(lst)
๐Ÿงฎ Store / Calculate Finds the largest value among lst; the result is stored in variable largest
4
smallest = min(lst)
๐Ÿงฎ Store / Calculate Finds the smallest value among lst; the result is stored in variable smallest
6
print("Largest number  :", largest, "at position", lst.index(largest))
๐Ÿ–ฅ๏ธ Output Displays the text "Largest number :", then the value of largest, then the text "at position", then the value of lst.index(largest) on the screen
7
print("Smallest number :", smallest, "at position", lst.index(smallest))
๐Ÿ–ฅ๏ธ Output Displays the text "Smallest number :", then the value of smallest, then the text "at position", then the value of lst.index(smallest) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [12, 45, 3, 78, 22]
Enter numbers separated by space: 12 45 3 78 22
23
largest = max(lst)
largest = 78
34
smallest = min(lst)
smallest = 3
46
print("Largest number  :", largest, "at position", lst.index(largest))
Largest number  : 78 at position 3
57
print("Smallest number :", smallest, "at position", lst.index(smallest))
Smallest number : 3 at position 2
Q16 PYTHON

Write a Python Program to Input a list of numbers and swap elements at the even location with the elements at the odd location.

lst = list(map(int, input("Enter numbers separated by space: ").split()))

for i in range(0, len(lst) - 1, 2):
    lst[i], lst[i + 1] = lst[i + 1], lst[i]

print("List after swapping:", lst)
โ–ถ Sample Output
Enter numbers separated by space: 10 20 30 40 50
List after swapping: [20, 10, 40, 30, 50]
๐Ÿ’ก Explanation: Steps through the list two elements at a time (step=2) and swaps each pair.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10 20 30 40 50 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
3
for i in range(0, len(lst) - 1, 2):
๐Ÿ” Loop LOOP: gives the numbers from 0 up to (not including) len(lst) - 1, jumping by 2; for each number, i takes that value and the indented block runs once
4
lst[i], lst[i + 1] = lst[i + 1], lst[i]
๐Ÿงฎ Store / Calculate Stores the tuple lst[i + 1], lst[i] in variables lst[i], lst[i + 1]
6
print("List after swapping:", lst)
๐Ÿ–ฅ๏ธ Output Displays the text "List after swapping:", then the value of lst on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [10, 20, 30, 40, 50]
Enter numbers separated by space: 10 20 30 40 50
23
for i in range(0, len(lst) - 1, 2):
next item taken
i = 0
34
lst[i], lst[i + 1] = lst[i + 1], lst[i]
lst = [20, 10, 30, 40, 50]
43
for i in range(0, len(lst) - 1, 2):
next item taken
i = 2
54
lst[i], lst[i + 1] = lst[i + 1], lst[i]
lst = [20, 10, 40, 30, 50]
63
for i in range(0, len(lst) - 1, 2):
no items left โ†’ loop ends
76
print("List after swapping:", lst)
List after swapping: [20, 10, 40, 30, 50]
Q17 PYTHON

Write a Python Program to Input a list/tuple of elements, search for a given element and display its frequency and position.

lst = list(map(int, input("Enter numbers separated by space: ").split()))
n = int(input("Enter number to search: "))

count = lst.count(n)
if count > 0:
    positions = [i for i in range(len(lst)) if lst[i] == n]
    print(n, "found", count, "time(s) at position(s):", positions)
else:
    print(n, "not found in the list")
โ–ถ Sample Output
Enter numbers separated by space: 10 20 30 20 10
Enter number to search: 20
20 found 2 time(s) at position(s): [1, 3]
๐Ÿ’ก Explanation: list.count() gives frequency; a list comprehension collects all matching indices in one line.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ lst, n
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10 20 30 20 10, 20 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
2
n = int(input("Enter number to search: "))
โŒจ๏ธ Input Shows "Enter number to search: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
4
count = lst.count(n)
๐Ÿงฎ Store / Calculate Counts how many times n occurs in lst; the result is stored in variable count
5
if count > 0:
๐Ÿ”€ Decision CHECKS whether count is greater than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
6
positions = [i for i in range(len(lst)) if lst[i] == n]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [i for i in range(len(lst)) if lst[i] == n] in variable positions
7
print(n, "found", count, "time(s) at position(s):", positions)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "found", then the value of count, then the text "time(s) at position(s):", then the value of positions on the screen
8
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
9
print(n, "not found in the list")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "not found in the list" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [10, 20, 30, 20, 10]
Enter numbers separated by space: 10 20 30 20 10
22
n = int(input("Enter number to search: "))
n = 20
Enter number to search: 20
34
count = lst.count(n)
count = 2
45
if count > 0:
condition is TRUE โ†’ enters the block
56
positions = [i for i in range(len(lst)) if lst[i] == n]
66
positions = [i for i in range(len(lst)) if lst[i] == n]
76
positions = [i for i in range(len(lst)) if lst[i] == n]
86
positions = [i for i in range(len(lst)) if lst[i] == n]
96
positions = [i for i in range(len(lst)) if lst[i] == n]
106
positions = [i for i in range(len(lst)) if lst[i] == n]
positions = [1, 3]
117
print(n, "found", count, "time(s) at position(s):", positions)
20 found 2 time(s) at position(s): [1, 3]
Q18 PYTHON

Write a Python Program to Input a list of numbers and test if a number is equal to the sum of the cubes of its digits. Find the smallest and largest such number from the list.

lst = list(map(int, input("Enter numbers separated by space: ").split()))
special = []

for num in lst:
    temp = num
    s = 0
    while temp > 0:
        d = temp % 10
        s += d ** 3
        temp //= 10
    if s == num:
        special.append(num)

if special:
    print("Numbers equal to sum of cubes of their digits:", special)
    print("Smallest such number:", min(special))
    print("Largest such number :", max(special))
else:
    print("No such number found in the list")
โ–ถ Sample Output
Enter numbers separated by space: 153 370 20 371
Numbers equal to sum of cubes of their digits: [153, 370, 371]
Smallest such number: 153
Largest such number : 371
๐Ÿ’ก Explanation: These are called Armstrong numbers for base-10, power-3 (e.g. 153 = 1ยณ+5ยณ+3ยณ).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else; a while loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 153 370 20 371 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
2
special = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable special
4
for num in lst:
๐Ÿ” Loop LOOP: takes each item of lst one-by-one into num and runs the indented block for it
5
temp = num
๐Ÿงฎ Store / Calculate Stores the value of num in variable temp
6
s = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s
7
while temp > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as temp is greater than 0; checks the condition before every round
8
d = temp % 10
๐Ÿงฎ Store / Calculate Stores the value of temp % 10 (calculated using % (remainder)) in variable d
9
s += d ** 3
๐Ÿงฎ Store / Calculate Adds d ** 3 to s (same as s = s + d ** 3)
10
temp //= 10
๐Ÿงฎ Store / Calculate Updates temp using temp //= 10
11
if s == num:
๐Ÿ”€ Decision CHECKS whether s is equal to num. If True, the indented lines below run; otherwise they are skipped
12
special.append(num)
๐Ÿงฎ Store / Calculate Adds num at the end of list special
14
if special:
๐Ÿ”€ Decision CHECKS whether special is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
15
print("Numbers equal to sum of cubes of their digits:", special)
๐Ÿ–ฅ๏ธ Output Displays the text "Numbers equal to sum of cubes of โ€ฆ", then the value of special on the screen
16
print("Smallest such number:", min(special))
๐Ÿ–ฅ๏ธ Output Displays the text "Smallest such number:", then the value of min(special) on the screen
17
print("Largest such number :", max(special))
๐Ÿ–ฅ๏ธ Output Displays the text "Largest such number :", then the value of max(special) on the screen
18
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
19
print("No such number found in the list")
๐Ÿ–ฅ๏ธ Output Displays the text "No such number found in the list" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [153, 370, 20, 371]
Enter numbers separated by space: 153 370 20 371
22
special = []
special = []
34
for num in lst:
next item taken
num = 153
45
temp = num
temp = 153
56
s = 0
s = 0
67
while temp > 0:
condition is TRUE โ†’ enters the block
78
d = temp % 10
d = 3
89
s += d ** 3
s = 27
910
temp //= 10
temp = 15
107
while temp > 0:
condition is TRUE โ†’ enters the block
118
d = temp % 10
d = 5
129
s += d ** 3
s = 152
1310
temp //= 10
temp = 1
147
while temp > 0:
condition is TRUE โ†’ enters the block
158
d = temp % 10
d = 1
169
s += d ** 3
s = 153
1710
temp //= 10
temp = 0
187
while temp > 0:
condition is FALSE โ†’ loop ends
1911
if s == num:
condition is TRUE โ†’ enters the block
2012
special.append(num)
special = [153]
214
for num in lst:
next item taken
num = 370
225
temp = num
temp = 370
236
s = 0
s = 0
247
while temp > 0:
condition is TRUE โ†’ enters the block
258
d = temp % 10
d = 0
269
s += d ** 3
2710
temp //= 10
temp = 37
287
while temp > 0:
condition is TRUE โ†’ enters the block
298
d = temp % 10
d = 7
309
s += d ** 3
s = 343
3110
temp //= 10
temp = 3
327
while temp > 0:
condition is TRUE โ†’ enters the block

โ€ฆ Python runs 42 more line-steps in the same way (loops repeat the same lines). Final values: lst = [153, 370, 20, 371], special = [153, 370, 371], num = 371, temp = 0, s = 371, d = 3

Q19 PYTHON

Write a Python Program to Create a dictionary with roll number, name and marks of n students and display names of students who scored above 75.

students = {}
n = int(input("How many students? "))

for i in range(n):
    roll = int(input("Enter roll number: "))
    name = input("Enter name: ")
    marks = float(input("Enter marks: "))
    students[roll] = (name, marks)

print("\nStudents scoring above 75:")
for roll, (name, marks) in students.items():
    if marks > 75:
        print("Roll:", roll, "Name:", name, "Marks:", marks)
โ–ถ Sample Output
How many students? 3
Enter roll number: 1
Enter name: Amit
Enter marks: 88
Enter roll number: 2
Enter name: Sara
Enter marks: 92
Enter roll number: 3
Enter name: Rahul
Enter marks: 65

Students scoring above 75:
Roll: 1 Name: Amit Marks: 88.0
Roll: 2 Name: Sara Marks: 92.0
๐Ÿ’ก Explanation: Dictionary key = roll number, value = tuple(name, marks). items() unpacks key & value together.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ n, roll, name, marks
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 3, 1, Amit, 88, 2, Sara, 92, 3, Rahul, 65 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
students = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable students
2
n = int(input("How many students? "))
โŒจ๏ธ Input Shows "How many students? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
4
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
5
roll = int(input("Enter roll number: "))
โŒจ๏ธ Input Shows "Enter roll number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
6
name = input("Enter name: ")
โŒจ๏ธ Input Shows the message "Enter name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
7
marks = float(input("Enter marks: "))
โŒจ๏ธ Input Shows "Enter marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable marks
8
students[roll] = (name, marks)
๐Ÿงฎ Store / Calculate Puts the tuple (name, marks) into students[roll] (item roll of students)
10
print("\nStudents scoring above 75:")
๐Ÿ–ฅ๏ธ Output Displays the text "Students scoring above 75:" on the screen
11
for roll, (name, marks) in students.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary students; roll, (name, marks) get one pair each round
12
if marks > 75:
๐Ÿ”€ Decision CHECKS whether marks is greater than 75. If True, the indented lines below run; otherwise they are skipped
13
print("Roll:", roll, "Name:", name, "Marks:", marks)
๐Ÿ–ฅ๏ธ Output Displays the text "Roll:", then the value of roll, then the text "Name:", then the value of name, then the text "Marks:", then the value of marks on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
students = {}
students = {}
22
n = int(input("How many students? "))
n = 3
How many students? 3
34
for i in range(n):
next item taken
i = 0
45
roll = int(input("Enter roll number: "))
roll = 1
Enter roll number: 1
56
name = input("Enter name: ")
name = 'Amit'
Enter name: Amit
67
marks = float(input("Enter marks: "))
marks = 88.0
Enter marks: 88
78
students[roll] = (name, marks)
students = {1: ('Amit', 88.0)}
84
for i in range(n):
next item taken
i = 1
95
roll = int(input("Enter roll number: "))
roll = 2
Enter roll number: 2
106
name = input("Enter name: ")
name = 'Sara'
Enter name: Sara
117
marks = float(input("Enter marks: "))
marks = 92.0
Enter marks: 92
128
students[roll] = (name, marks)
students = {1: ('Amit', 88.0), 2: ('Sara', 92.0)}
134
for i in range(n):
next item taken
i = 2
145
roll = int(input("Enter roll number: "))
roll = 3
Enter roll number: 3
156
name = input("Enter name: ")
name = 'Rahul'
Enter name: Rahul
167
marks = float(input("Enter marks: "))
marks = 65.0
Enter marks: 65
178
students[roll] = (name, marks)
students = {1: ('Amit', 88.0), 2: ('Sara', 92.0), 3: ('Rahul', 65.0)}
184
for i in range(n):
no items left โ†’ loop ends
1910
print("\nStudents scoring above 75:")
Students scoring above 75:
2011
for roll, (name, marks) in students.items():
next item taken
roll = 1, name = 'Amit', marks = 88.0
2112
if marks > 75:
condition is TRUE โ†’ enters the block
2213
print("Roll:", roll, "Name:", name, "Marks:", marks)
Roll: 1 Name: Amit Marks: 88.0
2311
for roll, (name, marks) in students.items():
next item taken
roll = 2, name = 'Sara', marks = 92.0
2412
if marks > 75:
condition is TRUE โ†’ enters the block
2513
print("Roll:", roll, "Name:", name, "Marks:", marks)
Roll: 2 Name: Sara Marks: 92.0
2611
for roll, (name, marks) in students.items():
next item taken
roll = 3, name = 'Rahul', marks = 65.0
2712
if marks > 75:
condition is FALSE โ†’ skips this block
2811
for roll, (name, marks) in students.items():
no items left โ†’ loop ends
Q20 PYTHON

Write a Python Program to Create a dictionary of employee information (empid, empname, empsal, empmobile), input five values and display employees getting salary <= Rs 50000.

employees = {}

for i in range(5):
    empid = int(input("Enter Employee ID: "))
    empname = input("Enter Employee Name: ")
    empsal = float(input("Enter Salary: "))
    empmobile = input("Enter Mobile: ")
    employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}

print("\nEmployees with salary <= 50000:")
for empid, info in employees.items():
    if info["salary"] <= 50000:
        print(empid, info["name"], info["salary"], info["mobile"])
โ–ถ Sample Output
Enter Employee ID: 201
Enter Employee Name: Rahul
Enter Salary: 45000
Enter Mobile: 9876543210
Enter Employee ID: 202
Enter Employee Name: Priya
Enter Salary: 62000
Enter Mobile: 9811122233
Enter Employee ID: 203
Enter Employee Name: Karan
Enter Salary: 38000
Enter Mobile: 9899001122
Enter Employee ID: 204
Enter Employee Name: Neha
Enter Salary: 75000
Enter Mobile: 9810098100
Enter Employee ID: 205
Enter Employee Name: Vivek
Enter Salary: 50000
Enter Mobile: 9876501234

Employees with salary <= 50000:
201 Rahul 45000.0 9876543210
203 Karan 38000.0 9899001122
205 Vivek 50000.0 9876501234
๐Ÿ’ก Explanation: A nested dictionary (dictionary of dictionaries) neatly models a real employee record.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ empid, empname, empsal, empmobile
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 201, Rahul, 45000, 9876543210, 202, Priya, 62000, 9811122233, 203, Karan โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
employees = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable employees
3
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
4
empid = int(input("Enter Employee ID: "))
โŒจ๏ธ Input Shows "Enter Employee ID: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable empid
5
empname = input("Enter Employee Name: ")
โŒจ๏ธ Input Shows the message "Enter Employee Name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable empname
6
empsal = float(input("Enter Salary: "))
โŒจ๏ธ Input Shows "Enter Salary: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable empsal
7
empmobile = input("Enter Mobile: ")
โŒจ๏ธ Input Shows the message "Enter Mobile: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable empmobile
8
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
๐Ÿงฎ Store / Calculate Puts a dictionary {"name": empname, "salary": empsal, "mobile":โ€ฆ into employees[empid] (item empid of employees)
10
print("\nEmployees with salary <= 50000:")
๐Ÿ–ฅ๏ธ Output Displays the text "Employees with salary <= 50000:" on the screen
11
for empid, info in employees.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary employees; empid, info get one pair each round
12
if info["salary"] <= 50000:
๐Ÿ”€ Decision CHECKS whether info["salary"] is less than or equal to 50000. If True, the indented lines below run; otherwise they are skipped
13
print(empid, info["name"], info["salary"], info["mobile"])
๐Ÿ–ฅ๏ธ Output Displays the value of empid, then the value of info["name"], then the value of info["salary"], then the value of info["mobile"] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
employees = {}
employees = {}
23
for i in range(5):
next item taken
i = 0
34
empid = int(input("Enter Employee ID: "))
empid = 201
Enter Employee ID: 201
45
empname = input("Enter Employee Name: ")
empname = 'Rahul'
Enter Employee Name: Rahul
56
empsal = float(input("Enter Salary: "))
empsal = 45000.0
Enter Salary: 45000
67
empmobile = input("Enter Mobile: ")
empmobile = '9876543210'
Enter Mobile: 9876543210
78
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
employees = {201: {'name': 'Rahul', 'salary': 45000.0, 'mobile': '9876543210'}}
83
for i in range(5):
next item taken
i = 1
94
empid = int(input("Enter Employee ID: "))
empid = 202
Enter Employee ID: 202
105
empname = input("Enter Employee Name: ")
empname = 'Priya'
Enter Employee Name: Priya
116
empsal = float(input("Enter Salary: "))
empsal = 62000.0
Enter Salary: 62000
127
empmobile = input("Enter Mobile: ")
empmobile = '9811122233'
Enter Mobile: 9811122233
138
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
employees = {201: {'name': 'Rahul', 'salary': 45000.0, 'mobile': '9876543210'},โ€ฆ
143
for i in range(5):
next item taken
i = 2
154
empid = int(input("Enter Employee ID: "))
empid = 203
Enter Employee ID: 203
165
empname = input("Enter Employee Name: ")
empname = 'Karan'
Enter Employee Name: Karan
176
empsal = float(input("Enter Salary: "))
empsal = 38000.0
Enter Salary: 38000
187
empmobile = input("Enter Mobile: ")
empmobile = '9899001122'
Enter Mobile: 9899001122
198
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
203
for i in range(5):
next item taken
i = 3
214
empid = int(input("Enter Employee ID: "))
empid = 204
Enter Employee ID: 204
225
empname = input("Enter Employee Name: ")
empname = 'Neha'
Enter Employee Name: Neha
236
empsal = float(input("Enter Salary: "))
empsal = 75000.0
Enter Salary: 75000
247
empmobile = input("Enter Mobile: ")
empmobile = '9810098100'
Enter Mobile: 9810098100
258
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
263
for i in range(5):
next item taken
i = 4
274
empid = int(input("Enter Employee ID: "))
empid = 205
Enter Employee ID: 205
285
empname = input("Enter Employee Name: ")
empname = 'Vivek'
Enter Employee Name: Vivek
296
empsal = float(input("Enter Salary: "))
empsal = 50000.0
Enter Salary: 50000
307
empmobile = input("Enter Mobile: ")
empmobile = '9876501234'
Enter Mobile: 9876501234
318
employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile}
323
for i in range(5):
no items left โ†’ loop ends

โ€ฆ Python runs 15 more line-steps in the same way (loops repeat the same lines). Final values: employees = {201: {'name': 'Rahul', 'salary': 45000.0, 'mobile': '9876543210'},โ€ฆ, i = 4, empid = 205, empname = 'Vivek', empsal = 50000.0, empmobile = '9876501234', info = {'name': 'Vivek', 'salary': 50000.0, 'mobile': '9876501234'}

Q21 PYTHON

Write a Python Program to Create a dictionary of Library information (bookid, bookname, bookprice, bookauthor), input five values, display and change some values by searching bookname.

library = {}

for i in range(5):
    bookid = int(input("Enter Book ID: "))
    bookname = input("Enter Book Name: ")
    bookprice = float(input("Enter Book Price: "))
    bookauthor = input("Enter Author: ")
    library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}

print("\nLibrary records:")
for bookid, info in library.items():
    print(bookid, info)

search_name = input("\nEnter book name to update price: ")
for bookid, info in library.items():
    if info["name"] == search_name:
        new_price = float(input("Enter new price: "))
        info["price"] = new_price
        print("Price updated!")
        break
else:
    print("Book not found")
โ–ถ Sample Output
Enter Book ID: 1
Enter Book Name: Python Basics
Enter Book Price: 350
Enter Author: Sumita Arora
Enter Book ID: 2
Enter Book Name: Data Structures
Enter Book Price: 420
Enter Author: Reema Thareja
Enter Book ID: 3
Enter Book Name: Let Us C
Enter Book Price: 300
Enter Author: Y. Kanetkar
Enter Book ID: 4
Enter Book Name: AI for All
Enter Book Price: 280
Enter Author: NITI Aayog
Enter Book ID: 5
Enter Book Name: Computer Networks
Enter Book Price: 510
Enter Author: A. Tanenbaum

Library records:
1 {'name': 'Python Basics', 'price': 350.0, 'author': 'Sumita Arora'}
2 {'name': 'Data Structures', 'price': 420.0, 'author': 'Reema Thareja'}
3 {'name': 'Let Us C', 'price': 300.0, 'author': 'Y. Kanetkar'}
4 {'name': 'AI for All', 'price': 280.0, 'author': 'NITI Aayog'}
5 {'name': 'Computer Networks', 'price': 510.0, 'author': 'A. Tanenbaum'}

Enter book name to update price: Python Basics
Enter new price: 450
Price updated!
๐Ÿ’ก Explanation: The for...else on the loop prints 'Book not found' only if the break never executed (book wasn't found).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 6 values from the keyboard โ†’ search_name, bookid, bookname, bookprice, bookauthor, new_price
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q21.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, Python Basics, 350, Sumita Arora, 2, Data Structures, 420, Reema Thareja, 3, Let Us C โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
library = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable library
3
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
4
bookid = int(input("Enter Book ID: "))
โŒจ๏ธ Input Shows "Enter Book ID: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable bookid
5
bookname = input("Enter Book Name: ")
โŒจ๏ธ Input Shows the message "Enter Book Name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable bookname
6
bookprice = float(input("Enter Book Price: "))
โŒจ๏ธ Input Shows "Enter Book Price: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable bookprice
7
bookauthor = input("Enter Author: ")
โŒจ๏ธ Input Shows the message "Enter Author: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable bookauthor
8
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
๐Ÿงฎ Store / Calculate Puts a dictionary {"name": bookname, "price": bookprice, "authoโ€ฆ into library[bookid] (item bookid of library)
10
print("\nLibrary records:")
๐Ÿ–ฅ๏ธ Output Displays the text "Library records:" on the screen
11
for bookid, info in library.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary library; bookid, info get one pair each round
12
print(bookid, info)
๐Ÿ–ฅ๏ธ Output Displays the value of bookid, then the value of info on the screen
14
search_name = input("\nEnter book name to update price: ")
โŒจ๏ธ Input Shows the message "\nEnter book name to update price: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable search_name
15
for bookid, info in library.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary library; bookid, info get one pair each round
16
if info["name"] == search_name:
๐Ÿ”€ Decision CHECKS whether info["name"] is equal to search_name. If True, the indented lines below run; otherwise they are skipped
17
new_price = float(input("Enter new price: "))
โŒจ๏ธ Input Shows "Enter new price: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable new_price
18
info["price"] = new_price
๐Ÿงฎ Store / Calculate Puts the value of new_price into info["price"] (item "price" of info)
19
print("Price updated!")
๐Ÿ–ฅ๏ธ Output Displays the text "Price updated!" on the screen
20
break
๐Ÿ” Loop BREAK - leaves the loop immediately
21
else:
๐Ÿ” Loop ELSE of the loop: runs when the loop finishes WITHOUT a break
22
print("Book not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Book not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
library = {}
library = {}
23
for i in range(5):
next item taken
i = 0
34
bookid = int(input("Enter Book ID: "))
bookid = 1
Enter Book ID: 1
45
bookname = input("Enter Book Name: ")
bookname = 'Python Basics'
Enter Book Name: Python Basics
56
bookprice = float(input("Enter Book Price: "))
bookprice = 350.0
Enter Book Price: 350
67
bookauthor = input("Enter Author: ")
bookauthor = 'Sumita Arora'
Enter Author: Sumita Arora
78
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
library = {1: {'name': 'Python Basics', 'price': 350.0, 'author': 'Sumita Aroโ€ฆ
83
for i in range(5):
next item taken
i = 1
94
bookid = int(input("Enter Book ID: "))
bookid = 2
Enter Book ID: 2
105
bookname = input("Enter Book Name: ")
bookname = 'Data Structures'
Enter Book Name: Data Structures
116
bookprice = float(input("Enter Book Price: "))
bookprice = 420.0
Enter Book Price: 420
127
bookauthor = input("Enter Author: ")
bookauthor = 'Reema Thareja'
Enter Author: Reema Thareja
138
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
143
for i in range(5):
next item taken
i = 2
154
bookid = int(input("Enter Book ID: "))
bookid = 3
Enter Book ID: 3
165
bookname = input("Enter Book Name: ")
bookname = 'Let Us C'
Enter Book Name: Let Us C
176
bookprice = float(input("Enter Book Price: "))
bookprice = 300.0
Enter Book Price: 300
187
bookauthor = input("Enter Author: ")
bookauthor = 'Y. Kanetkar'
Enter Author: Y. Kanetkar
198
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
203
for i in range(5):
next item taken
i = 3
214
bookid = int(input("Enter Book ID: "))
bookid = 4
Enter Book ID: 4
225
bookname = input("Enter Book Name: ")
bookname = 'AI for All'
Enter Book Name: AI for All
236
bookprice = float(input("Enter Book Price: "))
bookprice = 280.0
Enter Book Price: 280
247
bookauthor = input("Enter Author: ")
bookauthor = 'NITI Aayog'
Enter Author: NITI Aayog
258
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
263
for i in range(5):
next item taken
i = 4
274
bookid = int(input("Enter Book ID: "))
bookid = 5
Enter Book ID: 5
285
bookname = input("Enter Book Name: ")
bookname = 'Computer Networks'
Enter Book Name: Computer Networks
296
bookprice = float(input("Enter Book Price: "))
bookprice = 510.0
Enter Book Price: 510
307
bookauthor = input("Enter Author: ")
bookauthor = 'A. Tanenbaum'
Enter Author: A. Tanenbaum
318
library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor}
323
for i in range(5):
no items left โ†’ loop ends

โ€ฆ Python runs 19 more line-steps in the same way (loops repeat the same lines). Final values: library = {1: {'name': 'Python Basics', 'price': 450.0, 'author': 'Sumita Aroโ€ฆ, i = 4, bookid = 1, bookname = 'Computer Networks', bookprice = 510.0, bookauthor = 'A. Tanenbaum', info = {'name': 'Python Basics', 'price': 450.0, 'author': 'Sumita Arora'}, search_name = 'Python Basics', new_price = 450.0

Q22 PYTHON

Write a Python Program to Create a hotel dictionary (bookingid, clientname, date, roomno) and delete a value based on bookingid.

hotel = {
    101: {"client": "Amit", "date": "01-07-2026", "room": 201},
    102: {"client": "Sara", "date": "02-07-2026", "room": 105},
    103: {"client": "Rahul", "date": "03-07-2026", "room": 310},
}

print("Booking records:")
for bid, info in hotel.items():
    print(bid, info)

del_id = int(input("\nEnter Booking ID to cancel/delete: "))
if del_id in hotel:
    del hotel[del_id]
    print("Booking", del_id, "deleted successfully")
else:
    print("Booking ID not found")

print("\nRecords after deletion:")
for bid, info in hotel.items():
    print(bid, info)
โ–ถ Sample Output
Booking records:
101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
102 {'client': 'Sara', 'date': '02-07-2026', 'room': 105}
103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}

Enter Booking ID to cancel/delete: 102
Booking 102 deleted successfully

Records after deletion:
101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}
๐Ÿ’ก Explanation: del dictionary[key] removes an entry permanently โ€” always check 'key in dict' first to avoid KeyError.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ del_id
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q22.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 102 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
hotel = {
    101: {"client": "Amit", "date": "01-07-2026", "room": 201},
    102: {"client": "Sara", "date": "02-07-2026", "room": 105},
    103: {"client":โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { 101: {"client": "Amit", "date": "01-07-2026โ€ฆ in variable hotel
7
print("Booking records:")
๐Ÿ–ฅ๏ธ Output Displays the text "Booking records:" on the screen
8
for bid, info in hotel.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary hotel; bid, info get one pair each round
9
print(bid, info)
๐Ÿ–ฅ๏ธ Output Displays the value of bid, then the value of info on the screen
11
del_id = int(input("\nEnter Booking ID to cancel/delete: "))
โŒจ๏ธ Input Shows "\nEnter Booking ID to cancel/delete: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable del_id
12
if del_id in hotel:
๐Ÿ”€ Decision CHECKS whether del_id is present in hotel. If True, the indented lines below run; otherwise Python jumps to the elif/else part
13
del hotel[del_id]
๐Ÿงฎ Store / Calculate Deletes hotel[del_id]
14
print("Booking", del_id, "deleted successfully")
๐Ÿ–ฅ๏ธ Output Displays the text "Booking", then the value of del_id, then the text "deleted successfully" on the screen
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
print("Booking ID not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Booking ID not found" on the screen
18
print("\nRecords after deletion:")
๐Ÿ–ฅ๏ธ Output Displays the text "Records after deletion:" on the screen
19
for bid, info in hotel.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary hotel; bid, info get one pair each round
20
print(bid, info)
๐Ÿ–ฅ๏ธ Output Displays the value of bid, then the value of info on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
101: {"client": "Amit", "date": "01-07-2026", "room": 201},
23
102: {"client": "Sara", "date": "02-07-2026", "room": 105},
34
103: {"client": "Rahul", "date": "03-07-2026", "room": 310},
41
hotel = {
hotel = {101: {'client': 'Amit', 'date': '01-07-2026', 'room': 201}, 102: {โ€ฆ
57
print("Booking records:")
Booking records:
68
for bid, info in hotel.items():
next item taken
bid = 101, info = {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
79
print(bid, info)
101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
88
for bid, info in hotel.items():
next item taken
bid = 102, info = {'client': 'Sara', 'date': '02-07-2026', 'room': 105}
99
print(bid, info)
102 {'client': 'Sara', 'date': '02-07-2026', 'room': 105}
108
for bid, info in hotel.items():
next item taken
bid = 103, info = {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}
119
print(bid, info)
103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}
128
for bid, info in hotel.items():
no items left โ†’ loop ends
1311
del_id = int(input("\nEnter Booking ID to cancel/delete: "))
del_id = 102
Enter Booking ID to cancel/delete: 102
1412
if del_id in hotel:
condition is TRUE โ†’ enters the block
1513
del hotel[del_id]
hotel = {101: {'client': 'Amit', 'date': '01-07-2026', 'room': 201}, 103: {โ€ฆ
1614
print("Booking", del_id, "deleted successfully")
Booking 102 deleted successfully
1718
print("\nRecords after deletion:")
Records after deletion:
1819
for bid, info in hotel.items():
next item taken
bid = 101, info = {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
1920
print(bid, info)
101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201}
2019
for bid, info in hotel.items():
next item taken
bid = 103, info = {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}
2120
print(bid, info)
103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310}
2219
for bid, info in hotel.items():
no items left โ†’ loop ends
Q23 PYTHON

Write a Python Program to implement python math functions/methods (pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan) using the math module.

import math

print("Value of pi   :", math.pi)
print("Value of e    :", math.e)
print("sqrt(25)      :", math.sqrt(25))
print("ceil(4.2)     :", math.ceil(4.2))
print("floor(4.8)    :", math.floor(4.8))
print("pow(2,3)      :", math.pow(2, 3))
print("fabs(-7.5)    :", math.fabs(-7.5))
print("sin(0)        :", math.sin(0))
print("cos(0)        :", math.cos(0))
print("tan(0)        :", math.tan(0))
โ–ถ Sample Output
Value of pi   : 3.141592653589793
Value of e    : 2.718281828459045
sqrt(25)      : 5.0
ceil(4.2)     : 5
floor(4.8)    : 4
pow(2,3)      : 8.0
fabs(-7.5)    : 7.5
sin(0)        : 0.0
cos(0)        : 1.0
tan(0)        : 0.0
๐Ÿ’ก Explanation: math module constants (pi, e) and functions must be imported first โ€” trigonometric functions take radians.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q23.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
3
print("Value of pi   :", math.pi)
๐Ÿ–ฅ๏ธ Output Displays the text "Value of pi :", then the value of math.pi on the screen
4
print("Value of e    :", math.e)
๐Ÿ–ฅ๏ธ Output Displays the text "Value of e :", then the value of math.e on the screen
5
print("sqrt(25)      :", math.sqrt(25))
๐Ÿ–ฅ๏ธ Output Displays the text "sqrt(25) :", then the value of math.sqrt(25) on the screen
6
print("ceil(4.2)     :", math.ceil(4.2))
๐Ÿ–ฅ๏ธ Output Displays the text "ceil(4.2) :", then the value of math.ceil(4.2) on the screen
7
print("floor(4.8)    :", math.floor(4.8))
๐Ÿ–ฅ๏ธ Output Displays the text "floor(4.8) :", then the value of math.floor(4.8) on the screen
8
print("pow(2,3)      :", math.pow(2, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "pow(2,3) :", then the value of math.pow(2, 3) on the screen
9
print("fabs(-7.5)    :", math.fabs(-7.5))
๐Ÿ–ฅ๏ธ Output Displays the text "fabs(-7.5) :", then the value of math.fabs(-7.5) on the screen
10
print("sin(0)        :", math.sin(0))
๐Ÿ–ฅ๏ธ Output Displays the text "sin(0) :", then the value of math.sin(0) on the screen
11
print("cos(0)        :", math.cos(0))
๐Ÿ–ฅ๏ธ Output Displays the text "cos(0) :", then the value of math.cos(0) on the screen
12
print("tan(0)        :", math.tan(0))
๐Ÿ–ฅ๏ธ Output Displays the text "tan(0) :", then the value of math.tan(0) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import math
23
print("Value of pi   :", math.pi)
Value of pi   : 3.141592653589793
34
print("Value of e    :", math.e)
Value of e    : 2.718281828459045
45
print("sqrt(25)      :", math.sqrt(25))
sqrt(25)      : 5.0
56
print("ceil(4.2)     :", math.ceil(4.2))
ceil(4.2)     : 5
67
print("floor(4.8)    :", math.floor(4.8))
floor(4.8)    : 4
78
print("pow(2,3)      :", math.pow(2, 3))
pow(2,3)      : 8.0
89
print("fabs(-7.5)    :", math.fabs(-7.5))
fabs(-7.5)    : 7.5
910
print("sin(0)        :", math.sin(0))
sin(0)        : 0.0
1011
print("cos(0)        :", math.cos(0))
cos(0)        : 1.0
1112
print("tan(0)        :", math.tan(0))
tan(0)        : 0.0
Q24 PYTHON

Write a Python program to implement the random function random(), randint(), randrange() using the random module.

import random

print("random()          :", random.random())          # float between 0 and 1
print("randint(1,6)      :", random.randint(1, 6))      # dice simulation, both ends inclusive
print("randrange(0,10,2) :", random.randrange(0, 10, 2)) # even numbers 0,2,4,6,8
โ–ถ Sample Output
random()          : 0.11911988496396309
randint(1,6)      : 5
randrange(0,10,2) : 8
๐Ÿ’ก Explanation: random() gives 0<=x<1; randint(a,b) is inclusive of b; randrange(start,stop,step) excludes stop.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module random
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q24.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import random
๐Ÿ“ฆ Library / Data Loads the module random - random number functions
3
print("random()          :", random.random())          # float between 0 and 1
๐Ÿ–ฅ๏ธ Output Displays the text "random() :", then the value of random.random() on the screen
4
print("randint(1,6)      :", random.randint(1, 6))      # dice simulation, both ends inclusive
๐Ÿ–ฅ๏ธ Output Displays the text "randint(1,6) :", then the value of random.randint(1, 6) on the screen
5
print("randrange(0,10,2) :", random.randrange(0, 10, 2)) # even numbers 0,2,4,6,8
๐Ÿ–ฅ๏ธ Output Displays the text "randrange(0,10,2) :", then the value of random.randrange(0, 10, 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import random
23
print("random()          :", random.random())          # float between 0 and 1
random()          : 0.11911988496396309
34
print("randint(1,6)      :", random.randint(1, 6))      # dice simulation, both ends inclu
randint(1,6)      : 5
45
print("randrange(0,10,2) :", random.randrange(0, 10, 2)) # even numbers 0,2,4,6,8
randrange(0,10,2) : 8
Q25 PYTHON

Write a Python program to implement statistics functions (mean, median, mode) using the statistics module.

import statistics as st

data = [10, 20, 20, 30, 40, 20, 50]

print("Data  :", data)
print("Mean  :", st.mean(data))
print("Median:", st.median(data))
print("Mode  :", st.mode(data))
โ–ถ Sample Output
Data  : [10, 20, 20, 30, 40, 20, 50]
Mean  : 27.142857142857142
Median: 20
Mode  : 20
๐Ÿ’ก Explanation: statistics.mean/median/mode give quick descriptive-stats results without writing manual formulas.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module statistics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q25.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import statistics as st
๐Ÿ“ฆ Library / Data Loads the module statistics (nick-name st) - mean, median, mode functions
3
data = [10, 20, 20, 30, 40, 20, 50]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 20, 30, 40, 20, 50] in variable data
5
print("Data  :", data)
๐Ÿ–ฅ๏ธ Output Displays the text "Data :", then the value of data on the screen
6
print("Mean  :", st.mean(data))
๐Ÿ–ฅ๏ธ Output Displays the text "Mean :", then the value of st.mean(data) on the screen
7
print("Median:", st.median(data))
๐Ÿ–ฅ๏ธ Output Displays the text "Median:", then the value of st.median(data) on the screen
8
print("Mode  :", st.mode(data))
๐Ÿ–ฅ๏ธ Output Displays the text "Mode :", then the value of st.mode(data) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import statistics as st
23
data = [10, 20, 20, 30, 40, 20, 50]
data = [10, 20, 20, 30, 40, 20, 50]
35
print("Data  :", data)
Data  : [10, 20, 20, 30, 40, 20, 50]
46
print("Mean  :", st.mean(data))
Mean  : 27.142857142857142
57
print("Median:", st.median(data))
Median: 20
68
print("Mode  :", st.mode(data))
Mode  : 20
Q26 PYTHON NEW 2026-27

Write a python program to find the factorial of a positive number.

n = int(input("Enter a positive number: "))

if n < 0:
    print("Factorial is not defined for negative numbers.")
else:
    fact = 1
    for i in range(1, n + 1):
        fact = fact * i
    print("Factorial of", n, "is", fact)
    # Verify with the math module
    import math
    print("Using math.factorial():", math.factorial(n))
โ–ถ Sample Output
Enter a positive number: 6
Factorial of 6 is 720
Using math.factorial(): 720
๐Ÿ’ก Explanation: Factorial n! = 1 ร— 2 ร— โ€ฆ ร— n. A running product inside a for loop builds it step by step; 0! = 1 because the loop does not run and fact stays 1.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; a for loop; module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q26.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 6 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
n = int(input("Enter a positive number: "))
โŒจ๏ธ Input Shows "Enter a positive number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
3
if n < 0:
๐Ÿ”€ Decision CHECKS whether n is less than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
print("Factorial is not defined for negative numbers.")
๐Ÿ–ฅ๏ธ Output Displays the text "Factorial is not defined for negaโ€ฆ" on the screen
5
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
6
fact = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable fact
7
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
8
fact = fact * i
๐Ÿงฎ Store / Calculate Stores the value of fact * i (calculated using ร—) in variable fact
9
print("Factorial of", n, "is", fact)
๐Ÿ–ฅ๏ธ Output Displays the text "Factorial of", then the value of n, then the text "is", then the value of fact on the screen
๐Ÿ“Œ Verify with the math module
11
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
12
print("Using math.factorial():", math.factorial(n))
๐Ÿ–ฅ๏ธ Output Displays the text "Using math.factorial():", then the value of math.factorial(n) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("Enter a positive number: "))
n = 6
Enter a positive number: 6
23
if n < 0:
condition is FALSE โ†’ skips this block
36
fact = 1
fact = 1
47
for i in range(1, n + 1):
next item taken
i = 1
58
fact = fact * i
67
for i in range(1, n + 1):
next item taken
i = 2
78
fact = fact * i
fact = 2
87
for i in range(1, n + 1):
next item taken
i = 3
98
fact = fact * i
fact = 6
107
for i in range(1, n + 1):
next item taken
i = 4
118
fact = fact * i
fact = 24
127
for i in range(1, n + 1):
next item taken
i = 5
138
fact = fact * i
fact = 120
147
for i in range(1, n + 1):
next item taken
i = 6
158
fact = fact * i
fact = 720
167
for i in range(1, n + 1):
no items left โ†’ loop ends
179
print("Factorial of", n, "is", fact)
Factorial of 6 is 720
1811
import math
1912
print("Using math.factorial():", math.factorial(n))
Using math.factorial(): 720
Q27 PYTHON NEW 2026-27

Write a python program to find the absolute value of a number (without and with abs()).

num = float(input("Enter a number: "))

# Method 1: using if-else
if num < 0:
    absolute = -num
else:
    absolute = num
print("Absolute value (if-else) :", absolute)

# Method 2: using built-in abs()
print("Absolute value (abs())   :", abs(num))
โ–ถ Sample Output
Enter a number: -17.5
Absolute value (if-else) : 17.5
Absolute value (abs())   : 17.5
๐Ÿ’ก Explanation: Absolute value is the distance from zero, so it is never negative. If the number is negative we multiply by โˆ’1; Python's built-in abs() does the same work.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ num
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q27.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type -17.5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
1
num = float(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable num
๐Ÿ“Œ Method 1: using if-else
4
if num < 0:
๐Ÿ”€ Decision CHECKS whether num is less than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
absolute = -num
๐Ÿงฎ Store / Calculate Stores -num in variable absolute
6
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
7
absolute = num
๐Ÿงฎ Store / Calculate Stores the value of num in variable absolute
8
print("Absolute value (if-else) :", absolute)
๐Ÿ–ฅ๏ธ Output Displays the text "Absolute value (if-else) :", then the value of absolute on the screen
๐Ÿ“Œ Method 2: using built-in abs()
11
print("Absolute value (abs())   :", abs(num))
๐Ÿ–ฅ๏ธ Output Displays the text "Absolute value (abs()) :", then the value of abs(num) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
num = float(input("Enter a number: "))
num = -17.5
Enter a number: -17.5
24
if num < 0:
condition is TRUE โ†’ enters the block
35
absolute = -num
absolute = 17.5
48
print("Absolute value (if-else) :", absolute)
Absolute value (if-else) : 17.5
511
print("Absolute value (abs())   :", abs(num))
Absolute value (abs())   : 17.5
Q28 PYTHON NEW 2026-27

Write a python program to check whether a number is divisible by another number.

a = int(input("Enter the number  : "))
b = int(input("Enter the divisor : "))

if b == 0:
    print("Division by zero is not allowed.")
elif a % b == 0:
    print(a, "is divisible by", b, "| Quotient =", a // b)
else:
    print(a, "is NOT divisible by", b, "| Remainder =", a % b)

# Bonus: list all numbers from 1 to 50 divisible by b
print("Numbers from 1 to 50 divisible by", b, ":")
print([x for x in range(1, 51) if x % b == 0])
โ–ถ Sample Output
Enter the number  : 84
Enter the divisor : 7
84 is divisible by 7 | Quotient = 12
Numbers from 1 to 50 divisible by 7 :
[7, 14, 21, 28, 35, 42, 49]
๐Ÿ’ก Explanation: The modulus operator % gives the remainder. If a % b == 0 there is no remainder, so a is exactly divisible by b. Checking b == 0 first avoids a ZeroDivisionError.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ a, b
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q28.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 84, 7 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
1
a = int(input("Enter the number  : "))
โŒจ๏ธ Input Shows "Enter the number : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable a
2
b = int(input("Enter the divisor : "))
โŒจ๏ธ Input Shows "Enter the divisor : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable b
4
if b == 0:
๐Ÿ”€ Decision CHECKS whether b is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
print("Division by zero is not allowed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Division by zero is not allowed." on the screen
6
elif a % b == 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether a % b is equal to 0
7
print(a, "is divisible by", b, "| Quotient =", a // b)
๐Ÿ–ฅ๏ธ Output Displays the value of a, then the text "is divisible by", then the value of b, then the text "| Quotient =", then the value of a // b on the screen
8
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
9
print(a, "is NOT divisible by", b, "| Remainder =", a % b)
๐Ÿ–ฅ๏ธ Output Displays the value of a, then the text "is NOT divisible by", then the value of b, then the text "| Remainder =", then the value of a % b on the screen
๐Ÿ“Œ Bonus: list all numbers from 1 to 50 divisible by b
12
print("Numbers from 1 to 50 divisible by", b, ":")
๐Ÿ–ฅ๏ธ Output Displays the text "Numbers from 1 to 50 divisible by", then the value of b, then the text ":" on the screen
13
print([x for x in range(1, 51) if x % b == 0])
๐Ÿ–ฅ๏ธ Output Displays the value of [x for x in range(1, 51) if x % b == 0] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
a = int(input("Enter the number  : "))
a = 84
Enter the number  : 84
22
b = int(input("Enter the divisor : "))
b = 7
Enter the divisor : 7
34
if b == 0:
condition is FALSE โ†’ skips this block
46
elif a % b == 0:
condition is TRUE โ†’ enters the block
57
print(a, "is divisible by", b, "| Quotient =", a // b)
84 is divisible by 7 | Quotient = 12
612
print("Numbers from 1 to 50 divisible by", b, ":")
Numbers from 1 to 50 divisible by 7 :
713
print([x for x in range(1, 51) if x % b == 0])
813
print([x for x in range(1, 51) if x % b == 0])
913
print([x for x in range(1, 51) if x % b == 0])
1013
print([x for x in range(1, 51) if x % b == 0])
1113
print([x for x in range(1, 51) if x % b == 0])
1213
print([x for x in range(1, 51) if x % b == 0])
1313
print([x for x in range(1, 51) if x % b == 0])
1413
print([x for x in range(1, 51) if x % b == 0])
1513
print([x for x in range(1, 51) if x % b == 0])
1613
print([x for x in range(1, 51) if x % b == 0])
1713
print([x for x in range(1, 51) if x % b == 0])
1813
print([x for x in range(1, 51) if x % b == 0])
1913
print([x for x in range(1, 51) if x % b == 0])
2013
print([x for x in range(1, 51) if x % b == 0])
2113
print([x for x in range(1, 51) if x % b == 0])
2213
print([x for x in range(1, 51) if x % b == 0])
2313
print([x for x in range(1, 51) if x % b == 0])
2413
print([x for x in range(1, 51) if x % b == 0])
2513
print([x for x in range(1, 51) if x % b == 0])
2613
print([x for x in range(1, 51) if x % b == 0])
2713
print([x for x in range(1, 51) if x % b == 0])
2813
print([x for x in range(1, 51) if x % b == 0])
2913
print([x for x in range(1, 51) if x % b == 0])
3013
print([x for x in range(1, 51) if x % b == 0])
3113
print([x for x in range(1, 51) if x % b == 0])
3213
print([x for x in range(1, 51) if x % b == 0])

โ€ฆ Python runs 25 more line-steps in the same way (loops repeat the same lines). Final values: a = 84, b = 7

Q29 PYTHON NEW 2026-27

Write a python program to count the frequency of each character in a string using a dictionary.

text = input("Enter a string: ")

freq = {}                       # empty dictionary
for ch in text:
    if ch in freq:
        freq[ch] = freq[ch] + 1
    else:
        freq[ch] = 1

print("Character frequency:")
for ch, count in freq.items():
    print(repr(ch), ":", count)

# Most frequent character (ignoring spaces)
letters = {k: v for k, v in freq.items() if k != " "}
top = max(letters, key=letters.get)
print("Most frequent character:", repr(top), "appears", letters[top], "times")
โ–ถ Sample Output
Enter a string: hello world
Character frequency:
'h' : 1
'e' : 1
'l' : 3
'o' : 2
' ' : 1
'w' : 1
'r' : 1
'd' : 1
Most frequent character: 'l' appears 3 times
๐Ÿ’ก Explanation: Each character is a key and its count is the value. The first time we see a character we set its count to 1; afterwards we add 1. dict.get(ch, 0) + 1 is a one-line alternative.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ text
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_cs_q29.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type hello world (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
1
text = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable text
3
freq = {}                       # empty dictionary
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable freq
4
for ch in text:
๐Ÿ” Loop LOOP: takes each item of text one-by-one into ch and runs the indented block for it
5
if ch in freq:
๐Ÿ”€ Decision CHECKS whether ch is present in freq. If True, the indented lines below run; otherwise Python jumps to the elif/else part
6
freq[ch] = freq[ch] + 1
๐Ÿงฎ Store / Calculate Puts the value of freq[ch] + 1 (calculated using +) into freq[ch] (item ch of freq)
7
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
8
freq[ch] = 1
๐Ÿงฎ Store / Calculate Puts the number 1 into freq[ch] (item ch of freq)
10
print("Character frequency:")
๐Ÿ–ฅ๏ธ Output Displays the text "Character frequency:" on the screen
11
for ch, count in freq.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary freq; ch, count get one pair each round
12
print(repr(ch), ":", count)
๐Ÿ–ฅ๏ธ Output Displays the value of repr(ch), then the text ":", then the value of count on the screen
๐Ÿ“Œ Most frequent character (ignoring spaces)
15
letters = {k: v for k, v in freq.items() if k != " "}
๐Ÿงฎ Store / Calculate Stores a new dictionary made by a comprehension in variable letters
16
top = max(letters, key=letters.get)
๐Ÿงฎ Store / Calculate Finds the largest value among letters; the result is stored in variable top
17
print("Most frequent character:", repr(top), "appears", letters[top], "times")
๐Ÿ–ฅ๏ธ Output Displays the text "Most frequent character:", then the value of repr(top), then the text "appears", then the value of letters[top], then the text "times" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
text = input("Enter a string: ")
text = 'hello world'
Enter a string: hello world
23
freq = {}                       # empty dictionary
freq = {}
34
for ch in text:
next item taken
ch = 'h'
45
if ch in freq:
condition is FALSE โ†’ skips this block
58
freq[ch] = 1
freq = {'h': 1}
64
for ch in text:
next item taken
ch = 'e'
75
if ch in freq:
condition is FALSE โ†’ skips this block
88
freq[ch] = 1
freq = {'h': 1, 'e': 1}
94
for ch in text:
next item taken
ch = 'l'
105
if ch in freq:
condition is FALSE โ†’ skips this block
118
freq[ch] = 1
freq = {'h': 1, 'e': 1, 'l': 1}
124
for ch in text:
next item taken
135
if ch in freq:
condition is TRUE โ†’ enters the block
146
freq[ch] = freq[ch] + 1
freq = {'h': 1, 'e': 1, 'l': 2}
154
for ch in text:
next item taken
ch = 'o'
165
if ch in freq:
condition is FALSE โ†’ skips this block
178
freq[ch] = 1
freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1}
184
for ch in text:
next item taken
ch = ' '
195
if ch in freq:
condition is FALSE โ†’ skips this block
208
freq[ch] = 1
freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1, ' ': 1}
214
for ch in text:
next item taken
ch = 'w'
225
if ch in freq:
condition is FALSE โ†’ skips this block
238
freq[ch] = 1
freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1, ' ': 1, 'w': 1}
244
for ch in text:
next item taken
ch = 'o'
255
if ch in freq:
condition is TRUE โ†’ enters the block
266
freq[ch] = freq[ch] + 1
freq = {'h': 1, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'w': 1}
274
for ch in text:
next item taken
ch = 'r'
285
if ch in freq:
condition is FALSE โ†’ skips this block
298
freq[ch] = 1
freq = {'h': 1, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'w': 1, 'r': 1}
304
for ch in text:
next item taken
ch = 'l'
315
if ch in freq:
condition is TRUE โ†’ enters the block
326
freq[ch] = freq[ch] + 1
freq = {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1}

โ€ฆ Python runs 33 more line-steps in the same way (loops repeat the same lines). Final values: text = 'hello world', freq = {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}, ch = 'd', count = 1, letters = {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}, top = 'l'

Class XI โ€” Informatics Practices (065)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 36 Practicals

๐Ÿ“˜ View Syllabus 2026-27 0%
๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

Q1 THEORY / VIVA

Introduction to Computer Systems (CPU, Input devices, Output devices, Memory, Hardware & Software etc.)

1. CPU (Central Processing Unit) - 'brain' of computer
   - Control Unit (CU): directs operation of processor
   - Arithmetic Logic Unit (ALU): performs calculations & comparisons
   - Registers: small, fast temporary storage inside CPU

2. Input Devices  : Keyboard, Mouse, Scanner, Microphone, Joystick, Webcam
3. Output Devices : Monitor, Printer, Speaker, Plotter, Projector
4. Memory
   - Primary  : RAM (volatile, temporary), ROM (non-volatile, permanent)
   - Secondary: Hard Disk, SSD, Pen Drive, CD/DVD (permanent storage)
5. Hardware : Physical, touchable components (CPU, RAM, Monitor, Keyboard)
6. Software : Set of instructions/programs
   - System Software (OS - Windows/Linux)
   - Application Software (MS Word, Python IDLE, Browser)
โ–ถ Sample Output
(Theory answer โ€” draw diagram in file for viva marks.)
๐Ÿ’ก Explanation: Theory practical โ€” draw a labelled diagram of the CPU + I/O devices in the practical file for full marks.
Q2 THEORY / VIVA

Introduction to Python (History of Python, Python Modes, Python Software etc.)

HISTORY: Created by Guido van Rossum, first released in 1991.
          Free, open source, high-level, interpreted language.

PYTHON MODES:
  1. Interactive Mode - statements typed & executed one at a time at >>> prompt
  2. Script Mode      - a .py file with many statements, executed together

PYTHON SOFTWARE/IDEs: IDLE (comes with Python), PyCharm, Jupyter Notebook,
                       Anaconda, VS Code, Google Colab

INSTALLING PYTHON:
  Step 1: Visit python.org/downloads and download the installer
  Step 2: Run installer, check 'Add Python to PATH'
  Step 3: Click 'Install Now'
  Step 4: Confirm via cmd -> python --version
โ–ถ Sample Output
(Theory answer โ€” write in practical file for viva preparation.)
๐Ÿ’ก Explanation: Keep this short and factual for viva โ€” examiners often ask 'What is the difference between interactive and script mode?'
Q3 PYTHON

Write a python program to design a calculator (+, -, *, /, %, //).

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operator (+,-,*,/,%,//): ")

if op == '+':
    print("Result =", a + b)
elif op == '-':
    print("Result =", a - b)
elif op == '*':
    print("Result =", a * b)
elif op == '/':
    print("Result =", a / b)
elif op == '%':
    print("Result =", a % b)
elif op == '//':
    print("Result =", a // b)
else:
    print("Invalid Operator")
โ–ถ Sample Output
Enter first number: 20
Enter second number: 4
Enter operator (+,-,*,/,%,//): *
Result = 80.0
๐Ÿ’ก Explanation: Real-life link: this is exactly how a physical calculator app / billing counter machine works.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ a, b, op
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 20, 4, * (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision
LineCodeWhat it does
1
a = float(input("Enter first number: "))
โŒจ๏ธ Input Shows "Enter first number: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable a
2
b = float(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable b
3
op = input("Enter operator (+,-,*,/,%,//): ")
โŒจ๏ธ Input Shows the message "Enter operator (+,-,*,/,%,//): " and waits; whatever the user types comes back as TEXT (string); it is stored in variable op
5
if op == '+':
๐Ÿ”€ Decision CHECKS whether op is equal to '+'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
6
print("Result =", a + b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a + b on the screen
7
elif op == '-':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether op is equal to '-'
8
print("Result =", a - b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a - b on the screen
9
elif op == '*':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether op is equal to '*'
10
print("Result =", a * b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a * b on the screen
11
elif op == '/':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether op is equal to '/'
12
print("Result =", a / b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a / b on the screen
13
elif op == '%':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether op is equal to '%'
14
print("Result =", a % b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a % b on the screen
15
elif op == '//':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether op is equal to '//'
16
print("Result =", a // b)
๐Ÿ–ฅ๏ธ Output Displays the text "Result =", then the value of a // b on the screen
17
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
18
print("Invalid Operator")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid Operator" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
a = float(input("Enter first number: "))
a = 20.0
Enter first number: 20
22
b = float(input("Enter second number: "))
b = 4.0
Enter second number: 4
33
op = input("Enter operator (+,-,*,/,%,//): ")
op = '*'
Enter operator (+,-,*,/,%,//): *
45
if op == '+':
condition is FALSE โ†’ skips this block
57
elif op == '-':
condition is FALSE โ†’ skips this block
69
elif op == '*':
condition is TRUE โ†’ enters the block
710
print("Result =", a * b)
Result = 80.0
Q4 PYTHON

Write a Python program to calculate perimeter/circumference and area of shapes: triangle, rectangle, square, circle.

import math

print("1.Triangle 2.Rectangle 3.Square 4.Circle")
ch = int(input("Choose shape: "))

if ch == 1:
    a = float(input("Side a: ")); b = float(input("Side b: ")); c = float(input("Side c: "))
    s = (a + b + c) / 2
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))   # Heron's formula
    print("Perimeter =", a + b + c, " Area =", area)
elif ch == 2:
    l = float(input("Length: ")); w = float(input("Width: "))
    print("Perimeter =", 2 * (l + w), " Area =", l * w)
elif ch == 3:
    side = float(input("Side: "))
    print("Perimeter =", 4 * side, " Area =", side ** 2)
elif ch == 4:
    r = float(input("Radius: "))
    print("Circumference =", 2 * math.pi * r, " Area =", math.pi * r ** 2)
else:
    print("Invalid choice")
โ–ถ Sample Output
1.Triangle 2.Rectangle 3.Square 4.Circle
Choose shape: 4
Radius: 7
Circumference = 43.982297150257104  Area = 153.93804002589985
๐Ÿ’ก Explanation: Menu-based shape calculator โ€” Heron's formula for triangle area is the key formula to remember.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 8 values from the keyboard โ†’ ch, a, b, c, l, w, side, r
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 4, 7 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
3
print("1.Triangle 2.Rectangle 3.Square 4.Circle")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Triangle 2.Rectangle 3.Square 4โ€ฆ" on the screen
4
ch = int(input("Choose shape: "))
โŒจ๏ธ Input Shows "Choose shape: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
6
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
a = float(input("Side a: ")); b = float(input("Side b: ")); c = float(input("Side c: "))
โŒจ๏ธ Input Shows "Side a: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable a
7
a = float(input("Side a: ")); b = float(input("Side b: ")); c = float(input("Side c: "))
โŒจ๏ธ Input Shows "Side b: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable b
7
a = float(input("Side a: ")); b = float(input("Side b: ")); c = float(input("Side c: "))
โŒจ๏ธ Input Shows "Side c: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable c
8
s = (a + b + c) / 2
๐Ÿงฎ Store / Calculate Stores the value of (a + b + c) / 2 (calculated using รท) in variable s
9
area = math.sqrt(s * (s - a) * (s - b) * (s - c))   # Heron's formula
๐Ÿงฎ Store / Calculate Finds the square root of s * (s - a) * (s - b) * (s - c); the result is stored in variable area
10
print("Perimeter =", a + b + c, " Area =", area)
๐Ÿ–ฅ๏ธ Output Displays the text "Perimeter =", then the value of a + b + c, then the text "Area =", then the value of area on the screen
11
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
12
l = float(input("Length: ")); w = float(input("Width: "))
โŒจ๏ธ Input Shows "Length: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable l
12
l = float(input("Length: ")); w = float(input("Width: "))
โŒจ๏ธ Input Shows "Width: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable w
13
print("Perimeter =", 2 * (l + w), " Area =", l * w)
๐Ÿ–ฅ๏ธ Output Displays the text "Perimeter =", then the value of 2 * (l + w), then the text "Area =", then the value of l * w on the screen
14
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
15
side = float(input("Side: "))
โŒจ๏ธ Input Shows "Side: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable side
16
print("Perimeter =", 4 * side, " Area =", side ** 2)
๐Ÿ–ฅ๏ธ Output Displays the text "Perimeter =", then the value of 4 * side, then the text "Area =", then the value of side ** 2 on the screen
17
elif ch == 4:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 4
18
r = float(input("Radius: "))
โŒจ๏ธ Input Shows "Radius: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable r
19
print("Circumference =", 2 * math.pi * r, " Area =", math.pi * r ** 2)
๐Ÿ–ฅ๏ธ Output Displays the text "Circumference =", then the value of 2 * math.pi * r, then the text "Area =", then the value of math.pi * r ** 2 on the screen
20
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
21
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import math
23
print("1.Triangle 2.Rectangle 3.Square 4.Circle")
1.Triangle 2.Rectangle 3.Square 4.Circle
34
ch = int(input("Choose shape: "))
ch = 4
Choose shape: 4
46
if ch == 1:
condition is FALSE โ†’ skips this block
511
elif ch == 2:
condition is FALSE โ†’ skips this block
614
elif ch == 3:
condition is FALSE โ†’ skips this block
717
elif ch == 4:
condition is TRUE โ†’ enters the block
818
r = float(input("Radius: "))
r = 7.0
Radius: 7
919
print("Circumference =", 2 * math.pi * r, " Area =", math.pi * r ** 2)
Circumference = 43.982297150257104  Area = 153.93804002589985
Q5 PYTHON

Write a Python program to calculate Simple and Compound Interest.

p = float(input("Enter Principal: "))
r = float(input("Enter Rate of Interest: "))
t = float(input("Enter Time (years): "))

si = (p * r * t) / 100
ci = p * ((1 + r / 100) ** t) - p

print("Simple Interest   = Rs.", round(si, 2))
print("Compound Interest = Rs.", round(ci, 2))
โ–ถ Sample Output
Enter Principal: 10000
Enter Rate of Interest: 8
Enter Time (years): 2
Simple Interest   = Rs. 1600.0
Compound Interest = Rs. 1664.0
๐Ÿ’ก Explanation: SI = PRT/100; CI = P(1+R/100)^T - P. Real life: bank fixed-deposit / loan calculators.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ p, r, t
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10000, 8, 2 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
p = float(input("Enter Principal: "))
โŒจ๏ธ Input Shows "Enter Principal: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable p
2
r = float(input("Enter Rate of Interest: "))
โŒจ๏ธ Input Shows "Enter Rate of Interest: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable r
3
t = float(input("Enter Time (years): "))
โŒจ๏ธ Input Shows "Enter Time (years): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable t
5
si = (p * r * t) / 100
๐Ÿงฎ Store / Calculate Stores the value of (p * r * t) / 100 (calculated using รท) in variable si
6
ci = p * ((1 + r / 100) ** t) - p
๐Ÿงฎ Store / Calculate Stores the value of p * ((1 + r / 100) ** t) - p (calculated using -) in variable ci
8
print("Simple Interest   = Rs.", round(si, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Simple Interest = Rs.", then the value of round(si, 2) on the screen
9
print("Compound Interest = Rs.", round(ci, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Compound Interest = Rs.", then the value of round(ci, 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
p = float(input("Enter Principal: "))
p = 10000.0
Enter Principal: 10000
22
r = float(input("Enter Rate of Interest: "))
r = 8.0
Enter Rate of Interest: 8
33
t = float(input("Enter Time (years): "))
t = 2.0
Enter Time (years): 2
45
si = (p * r * t) / 100
si = 1600.0
56
ci = p * ((1 + r / 100) ** t) - p
ci = 1664.0000000000018
68
print("Simple Interest   = Rs.", round(si, 2))
Simple Interest   = Rs. 1600.0
79
print("Compound Interest = Rs.", round(ci, 2))
Compound Interest = Rs. 1664.0
Q6 PYTHON

Write a python program to find average and grade for given marks.

subjects = int(input("Enter number of subjects: "))
total = 0

for i in range(subjects):
    marks = float(input(f"Enter marks of subject {i+1}: "))
    total += marks

avg = total / subjects
print("Average =", avg)

if avg >= 90:
    grade = 'A+'
elif avg >= 75:
    grade = 'A'
elif avg >= 60:
    grade = 'B'
elif avg >= 40:
    grade = 'C'
else:
    grade = 'Fail'
print("Grade =", grade)
โ–ถ Sample Output
Enter number of subjects: 3
Enter marks of subject 1: 80
Enter marks of subject 2: 90
Enter marks of subject 3: 85
Average = 85.0
Grade = A
๐Ÿ’ก Explanation: A report-card style program โ€” exactly the logic used in a school result generator.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ subjects, marks
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 3, 80, 90, 85 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
subjects = int(input("Enter number of subjects: "))
โŒจ๏ธ Input Shows "Enter number of subjects: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable subjects
2
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
4
for i in range(subjects):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to subjects - 1; for each number, i takes that value and the indented block runs once
5
marks = float(input(f"Enter marks of subject {i+1}: "))
โŒจ๏ธ Input Shows f"Enter marks of subject {i+1}: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable marks
6
total += marks
๐Ÿงฎ Store / Calculate Adds marks to total (same as total = total + marks)
8
avg = total / subjects
๐Ÿงฎ Store / Calculate Stores the value of total / subjects (calculated using รท) in variable avg
9
print("Average =", avg)
๐Ÿ–ฅ๏ธ Output Displays the text "Average =", then the value of avg on the screen
11
if avg >= 90:
๐Ÿ”€ Decision CHECKS whether avg is greater than or equal to 90. If True, the indented lines below run; otherwise Python jumps to the elif/else part
12
grade = 'A+'
๐Ÿงฎ Store / Calculate Stores the text 'A+' in variable grade
13
elif avg >= 75:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether avg is greater than or equal to 75
14
grade = 'A'
๐Ÿงฎ Store / Calculate Stores the text 'A' in variable grade
15
elif avg >= 60:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether avg is greater than or equal to 60
16
grade = 'B'
๐Ÿงฎ Store / Calculate Stores the text 'B' in variable grade
17
elif avg >= 40:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether avg is greater than or equal to 40
18
grade = 'C'
๐Ÿงฎ Store / Calculate Stores the text 'C' in variable grade
19
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
20
grade = 'Fail'
๐Ÿงฎ Store / Calculate Stores the text 'Fail' in variable grade
21
print("Grade =", grade)
๐Ÿ–ฅ๏ธ Output Displays the text "Grade =", then the value of grade on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
subjects = int(input("Enter number of subjects: "))
subjects = 3
Enter number of subjects: 3
22
total = 0
total = 0
34
for i in range(subjects):
next item taken
i = 0
45
marks = float(input(f"Enter marks of subject {i+1}: "))
marks = 80.0
Enter marks of subject 1: 80
56
total += marks
total = 80.0
64
for i in range(subjects):
next item taken
i = 1
75
marks = float(input(f"Enter marks of subject {i+1}: "))
marks = 90.0
Enter marks of subject 2: 90
86
total += marks
total = 170.0
94
for i in range(subjects):
next item taken
i = 2
105
marks = float(input(f"Enter marks of subject {i+1}: "))
marks = 85.0
Enter marks of subject 3: 85
116
total += marks
total = 255.0
124
for i in range(subjects):
no items left โ†’ loop ends
138
avg = total / subjects
avg = 85.0
149
print("Average =", avg)
Average = 85.0
1511
if avg >= 90:
condition is FALSE โ†’ skips this block
1613
elif avg >= 75:
condition is TRUE โ†’ enters the block
1714
grade = 'A'
grade = 'A'
1821
print("Grade =", grade)
Grade = A
Q7 PYTHON

Write a Python program to find the sale price of an item with a given cost and discount (%).

cost = float(input("Enter Cost Price: "))
discount = float(input("Enter Discount %: "))

discount_amt = (cost * discount) / 100
sale_price = cost - discount_amt

print("Discount Amount =", discount_amt)
print("Sale Price      =", sale_price)
โ–ถ Sample Output
Enter Cost Price: 1000
Enter Discount %: 20
Discount Amount = 200.0
Sale Price      = 800.0
๐Ÿ’ก Explanation: Real life: e-commerce sites (Flipkart/Amazon) show MRP, discount % and final sale price using this exact formula.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ cost, discount
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1000, 20 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
cost = float(input("Enter Cost Price: "))
โŒจ๏ธ Input Shows "Enter Cost Price: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable cost
2
discount = float(input("Enter Discount %: "))
โŒจ๏ธ Input Shows "Enter Discount %: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable discount
4
discount_amt = (cost * discount) / 100
๐Ÿงฎ Store / Calculate Stores the value of (cost * discount) / 100 (calculated using รท) in variable discount_amt
5
sale_price = cost - discount_amt
๐Ÿงฎ Store / Calculate Stores the value of cost - discount_amt (calculated using -) in variable sale_price
7
print("Discount Amount =", discount_amt)
๐Ÿ–ฅ๏ธ Output Displays the text "Discount Amount =", then the value of discount_amt on the screen
8
print("Sale Price      =", sale_price)
๐Ÿ–ฅ๏ธ Output Displays the text "Sale Price =", then the value of sale_price on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
cost = float(input("Enter Cost Price: "))
cost = 1000.0
Enter Cost Price: 1000
22
discount = float(input("Enter Discount %: "))
discount = 20.0
Enter Discount %: 20
34
discount_amt = (cost * discount) / 100
discount_amt = 200.0
45
sale_price = cost - discount_amt
sale_price = 800.0
57
print("Discount Amount =", discount_amt)
Discount Amount = 200.0
68
print("Sale Price      =", sale_price)
Sale Price      = 800.0
Q8 PYTHON

Write a Python program to calculate profit-loss for given Cost and Sell Price.

cp = float(input("Enter Cost Price: "))
sp = float(input("Enter Selling Price: "))

if sp > cp:
    profit = sp - cp
    print("Profit =", profit, " (", round((profit/cp)*100, 2), "% )")
elif cp > sp:
    loss = cp - sp
    print("Loss =", loss, " (", round((loss/cp)*100, 2), "% )")
else:
    print("No Profit No Loss")
โ–ถ Sample Output
Enter Cost Price: 500
Enter Selling Price: 650
Profit = 150.0  ( 30.0 % )
๐Ÿ’ก Explanation: Used by every shopkeeper/business โ€” profit% = (profit/CP)*100.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ cp, sp
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 500, 650 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision
LineCodeWhat it does
1
cp = float(input("Enter Cost Price: "))
โŒจ๏ธ Input Shows "Enter Cost Price: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable cp
2
sp = float(input("Enter Selling Price: "))
โŒจ๏ธ Input Shows "Enter Selling Price: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable sp
4
if sp > cp:
๐Ÿ”€ Decision CHECKS whether sp is greater than cp. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
profit = sp - cp
๐Ÿงฎ Store / Calculate Stores the value of sp - cp (calculated using -) in variable profit
6
print("Profit =", profit, " (", round((profit/cp)*100, 2), "% )")
๐Ÿ–ฅ๏ธ Output Displays the text "Profit =", then the value of profit, then the text "(", then the value of round((profit/cp)*100, 2), then the text "% )" on the screen
7
elif cp > sp:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether cp is greater than sp
8
loss = cp - sp
๐Ÿงฎ Store / Calculate Stores the value of cp - sp (calculated using -) in variable loss
9
print("Loss =", loss, " (", round((loss/cp)*100, 2), "% )")
๐Ÿ–ฅ๏ธ Output Displays the text "Loss =", then the value of loss, then the text "(", then the value of round((loss/cp)*100, 2), then the text "% )" on the screen
10
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
11
print("No Profit No Loss")
๐Ÿ–ฅ๏ธ Output Displays the text "No Profit No Loss" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
cp = float(input("Enter Cost Price: "))
cp = 500.0
Enter Cost Price: 500
22
sp = float(input("Enter Selling Price: "))
sp = 650.0
Enter Selling Price: 650
34
if sp > cp:
condition is TRUE โ†’ enters the block
45
profit = sp - cp
profit = 150.0
56
print("Profit =", profit, " (", round((profit/cp)*100, 2), "% )")
Profit = 150.0  ( 30.0 % )
Q9 PYTHON

Write a python program to calculate EMI for Amount, Period and Interest. EMI = (P*MR*(1+MR)**N)/(((1+MR)**N)-1)

p = float(input("Enter Loan Amount (P): "))
annual_rate = float(input("Enter Annual Interest Rate %: "))
years = int(input("Enter Loan Period (years): "))

mr = annual_rate / (12 * 100)      # monthly interest rate
n = years * 12                     # number of monthly installments

emi = (p * mr * (1 + mr) ** n) / (((1 + mr) ** n) - 1)
print("Monthly EMI = Rs.", round(emi, 2))
print("Total Payment = Rs.", round(emi * n, 2))
โ–ถ Sample Output
Enter Loan Amount (P): 500000
Enter Annual Interest Rate %: 9
Enter Loan Period (years): 5
Monthly EMI = Rs. 10379.18
Total Payment = Rs. 622750.66
๐Ÿ’ก Explanation: This is the exact formula banks use for Home Loan / Car Loan EMI calculators.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ p, annual_rate, years
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 500000, 9, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
p = float(input("Enter Loan Amount (P): "))
โŒจ๏ธ Input Shows "Enter Loan Amount (P): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable p
2
annual_rate = float(input("Enter Annual Interest Rate %: "))
โŒจ๏ธ Input Shows "Enter Annual Interest Rate %: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable annual_rate
3
years = int(input("Enter Loan Period (years): "))
โŒจ๏ธ Input Shows "Enter Loan Period (years): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable years
5
mr = annual_rate / (12 * 100)      # monthly interest rate
๐Ÿงฎ Store / Calculate Stores the value of annual_rate / (12 * 100) (calculated using รท) in variable mr
6
n = years * 12                     # number of monthly installments
๐Ÿงฎ Store / Calculate Stores the value of years * 12 (calculated using ร—) in variable n
8
emi = (p * mr * (1 + mr) ** n) / (((1 + mr) ** n) - 1)
๐Ÿงฎ Store / Calculate Stores the value of (p * mr * (1 + mr) ** n) / (((1 + mr) ** n) -โ€ฆ (calculated using รท) in variable emi
9
print("Monthly EMI = Rs.", round(emi, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Monthly EMI = Rs.", then the value of round(emi, 2) on the screen
10
print("Total Payment = Rs.", round(emi * n, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Total Payment = Rs.", then the value of round(emi * n, 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
p = float(input("Enter Loan Amount (P): "))
p = 500000.0
Enter Loan Amount (P): 500000
22
annual_rate = float(input("Enter Annual Interest Rate %: "))
annual_rate = 9.0
Enter Annual Interest Rate %: 9
33
years = int(input("Enter Loan Period (years): "))
years = 5
Enter Loan Period (years): 5
45
mr = annual_rate / (12 * 100)      # monthly interest rate
mr = 0.0075
56
n = years * 12                     # number of monthly installments
n = 60
68
emi = (p * mr * (1 + mr) ** n) / (((1 + mr) ** n) - 1)
emi = 10379.177613176937
79
print("Monthly EMI = Rs.", round(emi, 2))
Monthly EMI = Rs. 10379.18
810
print("Total Payment = Rs.", round(emi * n, 2))
Total Payment = Rs. 622750.66
Q10 PYTHON

Write a python program to calculate tax: (a) GST (b) Income Tax.

print("1. GST   2. Income Tax")
ch = int(input("Choose: "))

if ch == 1:
    amount = float(input("Enter amount: "))
    rate = float(input("Enter GST rate %: "))
    gst = amount * rate / 100
    print("GST =", gst, " Total Amount =", amount + gst)

elif ch == 2:
    income = float(input("Enter Annual Income: "))
    tax = 0
    if income <= 300000:
        tax = 0
    elif income <= 600000:
        tax = (income - 300000) * 0.05
    elif income <= 900000:
        tax = 15000 + (income - 600000) * 0.10
    elif income <= 1200000:
        tax = 45000 + (income - 900000) * 0.15
    else:
        tax = 90000 + (income - 1200000) * 0.20
    print("Income Tax payable = Rs.", round(tax, 2))
else:
    print("Invalid choice")
โ–ถ Sample Output
1. GST   2. Income Tax
Choose: 1
Enter amount: 1000
Enter GST rate %: 18
GST = 180.0  Total Amount = 1180.0
๐Ÿ’ก Explanation: GST is a flat percentage; Income Tax uses slab-style calculation โ€” mention these slabs are for practice, actual rates follow the current Union Budget.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ ch, amount, rate, income
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 1000, 18 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision
LineCodeWhat it does
1
print("1. GST   2. Income Tax")
๐Ÿ–ฅ๏ธ Output Displays the text "1. GST 2. Income Tax" on the screen
2
ch = int(input("Choose: "))
โŒจ๏ธ Input Shows "Choose: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
4
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
amount = float(input("Enter amount: "))
โŒจ๏ธ Input Shows "Enter amount: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable amount
6
rate = float(input("Enter GST rate %: "))
โŒจ๏ธ Input Shows "Enter GST rate %: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable rate
7
gst = amount * rate / 100
๐Ÿงฎ Store / Calculate Stores the value of amount * rate / 100 (calculated using รท) in variable gst
8
print("GST =", gst, " Total Amount =", amount + gst)
๐Ÿ–ฅ๏ธ Output Displays the text "GST =", then the value of gst, then the text "Total Amount =", then the value of amount + gst on the screen
10
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
11
income = float(input("Enter Annual Income: "))
โŒจ๏ธ Input Shows "Enter Annual Income: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable income
12
tax = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable tax
13
if income <= 300000:
๐Ÿ”€ Decision CHECKS whether income is less than or equal to 300000. If True, the indented lines below run; otherwise Python jumps to the elif/else part
14
tax = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable tax
15
elif income <= 600000:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether income is less than or equal to 600000
16
tax = (income - 300000) * 0.05
๐Ÿงฎ Store / Calculate Stores the value of (income - 300000) * 0.05 (calculated using ร—) in variable tax
17
elif income <= 900000:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether income is less than or equal to 900000
18
tax = 15000 + (income - 600000) * 0.10
๐Ÿงฎ Store / Calculate Stores the value of 15000 + (income - 600000) * 0.10 (calculated using +) in variable tax
19
elif income <= 1200000:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether income is less than or equal to 1200000
20
tax = 45000 + (income - 900000) * 0.15
๐Ÿงฎ Store / Calculate Stores the value of 45000 + (income - 900000) * 0.15 (calculated using +) in variable tax
21
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
22
tax = 90000 + (income - 1200000) * 0.20
๐Ÿงฎ Store / Calculate Stores the value of 90000 + (income - 1200000) * 0.20 (calculated using +) in variable tax
23
print("Income Tax payable = Rs.", round(tax, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Income Tax payable = Rs.", then the value of round(tax, 2) on the screen
24
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
25
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
print("1. GST   2. Income Tax")
1. GST   2. Income Tax
22
ch = int(input("Choose: "))
ch = 1
Choose: 1
34
if ch == 1:
condition is TRUE โ†’ enters the block
45
amount = float(input("Enter amount: "))
amount = 1000.0
Enter amount: 1000
56
rate = float(input("Enter GST rate %: "))
rate = 18.0
Enter GST rate %: 18
67
gst = amount * rate / 100
gst = 180.0
78
print("GST =", gst, " Total Amount =", amount + gst)
GST = 180.0  Total Amount = 1180.0
Q11 PYTHON

Write a python program to find the largest and smallest numbers in a list.

lst = list(map(int, input("Enter numbers separated by space: ").split()))
print("Largest  :", max(lst))
print("Smallest :", min(lst))
โ–ถ Sample Output
Enter numbers separated by space: 34 12 89 5 67
Largest  : 89
Smallest : 5
๐Ÿ’ก Explanation: max()/min() built-ins are the fastest approach for a simple list.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 34 12 89 5 67 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
2
print("Largest  :", max(lst))
๐Ÿ–ฅ๏ธ Output Displays the text "Largest :", then the value of max(lst) on the screen
3
print("Smallest :", min(lst))
๐Ÿ–ฅ๏ธ Output Displays the text "Smallest :", then the value of min(lst) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [34, 12, 89, 5, 67]
Enter numbers separated by space: 34 12 89 5 67
22
print("Largest  :", max(lst))
Largest  : 89
33
print("Smallest :", min(lst))
Smallest : 5
Q12 PYTHON

Write a python program to find the third largest/smallest number in a list.

lst = list(map(int, input("Enter numbers separated by space: ").split()))
unique_sorted_desc = sorted(set(lst), reverse=True)
unique_sorted_asc = sorted(set(lst))

print("Third Largest  :", unique_sorted_desc[2])
print("Third Smallest :", unique_sorted_asc[2])
โ–ถ Sample Output
Enter numbers separated by space: 10 40 20 40 30
Third Largest  : 20
Third Smallest : 30
๐Ÿ’ก Explanation: set() removes duplicates first, then sorted() with reverse=True gets a descending list โ€” index [2] is the 3rd largest.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10 40 20 40 30 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
lst = list(map(int, input("Enter numbers separated by space: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter numbers separated by spโ€ฆ; the result is stored in variable lst
2
unique_sorted_desc = sorted(set(lst), reverse=True)
๐Ÿงฎ Store / Calculate Makes a new sorted list from set(lst); the result is stored in variable unique_sorted_desc
3
unique_sorted_asc = sorted(set(lst))
๐Ÿงฎ Store / Calculate Makes a new sorted list from set(lst); the result is stored in variable unique_sorted_asc
5
print("Third Largest  :", unique_sorted_desc[2])
๐Ÿ–ฅ๏ธ Output Displays the text "Third Largest :", then the value of unique_sorted_desc[2] on the screen
6
print("Third Smallest :", unique_sorted_asc[2])
๐Ÿ–ฅ๏ธ Output Displays the text "Third Smallest :", then the value of unique_sorted_asc[2] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
lst = list(map(int, input("Enter numbers separated by space: ").split()))
lst = [10, 40, 20, 40, 30]
Enter numbers separated by space: 10 40 20 40 30
22
unique_sorted_desc = sorted(set(lst), reverse=True)
unique_sorted_desc = [40, 30, 20, 10]
33
unique_sorted_asc = sorted(set(lst))
unique_sorted_asc = [10, 20, 30, 40]
45
print("Third Largest  :", unique_sorted_desc[2])
Third Largest  : 20
56
print("Third Smallest :", unique_sorted_asc[2])
Third Smallest : 30
Q13 PYTHON

Write a python program to find the sum of squares of the first 100 natural numbers.

total = 0
for i in range(1, 101):
    total += i ** 2
print("Sum of squares of first 100 natural numbers =", total)

# Direct formula check: n(n+1)(2n+1)/6
n = 100
formula = n * (n + 1) * (2 * n + 1) // 6
print("Using formula =", formula)
โ–ถ Sample Output
Sum of squares of first 100 natural numbers = 338350
Using formula = 338350
๐Ÿ’ก Explanation: Shows both loop-based and mathematical-formula methods โ€” good to mention both in viva.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
1
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
2
for i in range(1, 101):
๐Ÿ” Loop LOOP: gives the numbers 1 to 100; for each number, i takes that value and the indented block runs once
3
total += i ** 2
๐Ÿงฎ Store / Calculate Adds i ** 2 to total (same as total = total + i ** 2)
4
print("Sum of squares of first 100 natural numbers =", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum of squares of first 100 naturโ€ฆ", then the value of total on the screen
๐Ÿ“Œ Direct formula check: n(n+1)(2n+1)/6
7
n = 100
๐Ÿงฎ Store / Calculate Stores the number 100 in variable n
8
formula = n * (n + 1) * (2 * n + 1) // 6
๐Ÿงฎ Store / Calculate Stores the value of n * (n + 1) * (2 * n + 1) // 6 (calculated using // (integer division)) in variable formula
9
print("Using formula =", formula)
๐Ÿ–ฅ๏ธ Output Displays the text "Using formula =", then the value of formula on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
total = 0
total = 0
22
for i in range(1, 101):
next item taken
i = 1
33
total += i ** 2
total = 1
42
for i in range(1, 101):
next item taken
i = 2
53
total += i ** 2
total = 5
62
for i in range(1, 101):
next item taken
i = 3
73
total += i ** 2
total = 14
82
for i in range(1, 101):
next item taken
i = 4
93
total += i ** 2
total = 30
102
for i in range(1, 101):
next item taken
i = 5
113
total += i ** 2
total = 55
122
for i in range(1, 101):
next item taken
i = 6
133
total += i ** 2
total = 91
142
for i in range(1, 101):
next item taken
i = 7
153
total += i ** 2
total = 140
162
for i in range(1, 101):
next item taken
i = 8
173
total += i ** 2
total = 204
182
for i in range(1, 101):
next item taken
i = 9
193
total += i ** 2
total = 285
202
for i in range(1, 101):
next item taken
i = 10
213
total += i ** 2
total = 385
222
for i in range(1, 101):
next item taken
i = 11
233
total += i ** 2
total = 506
242
for i in range(1, 101):
next item taken
i = 12
253
total += i ** 2
total = 650
262
for i in range(1, 101):
next item taken
i = 13
273
total += i ** 2
total = 819
282
for i in range(1, 101):
next item taken
i = 14
293
total += i ** 2
total = 1015
302
for i in range(1, 101):
next item taken
i = 15
313
total += i ** 2
total = 1240
322
for i in range(1, 101):
next item taken
i = 16

โ€ฆ Python runs 174 more line-steps in the same way (loops repeat the same lines). Final values: total = 338350, i = 100, n = 100, formula = 338350

Q14 PYTHON

Write a python program to print the first 'n' multiples of a given number.

num = int(input("Enter a number: "))
n = int(input("How many multiples? "))

for i in range(1, n + 1):
    print(num, "x", i, "=", num * i)
โ–ถ Sample Output
Enter a number: 7
How many multiples? 5
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
๐Ÿ’ก Explanation: Prints a simple multiplication table โ€” foundational looping practice.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ num, n
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 7, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop
LineCodeWhat it does
1
num = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable num
2
n = int(input("How many multiples? "))
โŒจ๏ธ Input Shows "How many multiples? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
4
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
5
print(num, "x", i, "=", num * i)
๐Ÿ–ฅ๏ธ Output Displays the value of num, then the text "x", then the value of i, then the text "=", then the value of num * i on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
num = int(input("Enter a number: "))
num = 7
Enter a number: 7
22
n = int(input("How many multiples? "))
n = 5
How many multiples? 5
34
for i in range(1, n + 1):
next item taken
i = 1
45
print(num, "x", i, "=", num * i)
7 x 1 = 7
54
for i in range(1, n + 1):
next item taken
i = 2
65
print(num, "x", i, "=", num * i)
7 x 2 = 14
74
for i in range(1, n + 1):
next item taken
i = 3
85
print(num, "x", i, "=", num * i)
7 x 3 = 21
94
for i in range(1, n + 1):
next item taken
i = 4
105
print(num, "x", i, "=", num * i)
7 x 4 = 28
114
for i in range(1, n + 1):
next item taken
i = 5
125
print(num, "x", i, "=", num * i)
7 x 5 = 35
134
for i in range(1, n + 1):
no items left โ†’ loop ends
Q15 PYTHON

Write a python program to count the number of vowels in a user entered string.

s = input("Enter a string: ")
count = 0
for ch in s.lower():
    if ch in 'aeiou':
        count += 1
print("Number of vowels =", count)
โ–ถ Sample Output
Enter a string: Computer Education
Number of vowels = 8
๐Ÿ’ก Explanation: .lower() first, so both 'A' and 'a' are matched correctly.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ s
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Computer Education (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
s = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
2
count = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable count
3
for ch in s.lower():
๐Ÿ” Loop LOOP: takes each item of s.lower() one-by-one into ch and runs the indented block for it
4
if ch in 'aeiou':
๐Ÿ”€ Decision CHECKS whether ch is present in 'aeiou'. If True, the indented lines below run; otherwise they are skipped
5
count += 1
๐Ÿงฎ Store / Calculate Adds 1 to count (same as count = count + 1)
6
print("Number of vowels =", count)
๐Ÿ–ฅ๏ธ Output Displays the text "Number of vowels =", then the value of count on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
s = input("Enter a string: ")
s = 'Computer Education'
Enter a string: Computer Education
22
count = 0
count = 0
33
for ch in s.lower():
next item taken
ch = 'c'
44
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
53
for ch in s.lower():
next item taken
ch = 'o'
64
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
75
count += 1
count = 1
83
for ch in s.lower():
next item taken
ch = 'm'
94
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
103
for ch in s.lower():
next item taken
ch = 'p'
114
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
123
for ch in s.lower():
next item taken
ch = 'u'
134
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
145
count += 1
count = 2
153
for ch in s.lower():
next item taken
ch = 't'
164
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
173
for ch in s.lower():
next item taken
ch = 'e'
184
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
195
count += 1
count = 3
203
for ch in s.lower():
next item taken
ch = 'r'
214
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
223
for ch in s.lower():
next item taken
ch = ' '
234
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
243
for ch in s.lower():
next item taken
ch = 'e'
254
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
265
count += 1
count = 4
273
for ch in s.lower():
next item taken
ch = 'd'
284
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
293
for ch in s.lower():
next item taken
ch = 'u'
304
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
315
count += 1
count = 5
323
for ch in s.lower():
next item taken
ch = 'c'

โ€ฆ Python runs 16 more line-steps in the same way (loops repeat the same lines). Final values: s = 'Computer Education', count = 8, ch = 'n'

Q16 PYTHON

Write a python program to print the words starting with a given alphabet in a user entered string.

s = input("Enter a sentence: ")
letter = input("Enter starting alphabet: ").lower()

words = s.split()
print("Words starting with '" + letter + "':")
for w in words:
    if w.lower().startswith(letter):
        print(w)
โ–ถ Sample Output
Enter a sentence: Amit Angad Rahul Anjali
Enter starting alphabet: a
Words starting with 'a':
Amit
Angad
Anjali
๐Ÿ’ก Explanation: split() breaks the sentence into a list of words; startswith() checks the first character(s).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ s, letter
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Amit Angad Rahul Anjali, a (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
s = input("Enter a sentence: ")
โŒจ๏ธ Input Shows the message "Enter a sentence: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
2
letter = input("Enter starting alphabet: ").lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable letter
4
words = s.split()
๐Ÿงฎ Store / Calculate Breaks s into a list of words (at spaces); the result is stored in variable words
5
print("Words starting with '" + letter + "':")
๐Ÿ–ฅ๏ธ Output Displays the value of "Words starting with '" + letter + "':" on the screen
6
for w in words:
๐Ÿ” Loop LOOP: takes each item of words one-by-one into w and runs the indented block for it
7
if w.lower().startswith(letter):
๐Ÿ”€ Decision CHECKS whether w.lower().startswith(letter) is True. If True, the indented lines below run; otherwise they are skipped
8
print(w)
๐Ÿ–ฅ๏ธ Output Displays the value of w on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
s = input("Enter a sentence: ")
s = 'Amit Angad Rahul Anjali'
Enter a sentence: Amit Angad Rahul Anjali
22
letter = input("Enter starting alphabet: ").lower()
letter = 'a'
Enter starting alphabet: a
34
words = s.split()
words = ['Amit', 'Angad', 'Rahul', 'Anjali']
45
print("Words starting with '" + letter + "':")
Words starting with 'a':
56
for w in words:
next item taken
w = 'Amit'
67
if w.lower().startswith(letter):
condition is TRUE โ†’ enters the block
78
print(w)
Amit
86
for w in words:
next item taken
w = 'Angad'
97
if w.lower().startswith(letter):
condition is TRUE โ†’ enters the block
108
print(w)
Angad
116
for w in words:
next item taken
w = 'Rahul'
127
if w.lower().startswith(letter):
condition is FALSE โ†’ skips this block
136
for w in words:
next item taken
w = 'Anjali'
147
if w.lower().startswith(letter):
condition is TRUE โ†’ enters the block
158
print(w)
Anjali
166
for w in words:
no items left โ†’ loop ends
Q17 PYTHON

Write a python program to print the number of occurrences of a given alphabet in each string.

n = int(input("How many strings? "))
letter = input("Enter alphabet to search: ").lower()

for i in range(n):
    s = input(f"Enter string {i+1}: ")
    print("Occurrences of '" + letter + "' :", s.lower().count(letter))
โ–ถ Sample Output
How many strings? 2
Enter alphabet to search: a
Enter string 1: banana
Occurrences of 'a' : 3
Enter string 2: apple
Occurrences of 'a' : 1
๐Ÿ’ก Explanation: str.count() directly returns how many times a character/substring appears.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ n, letter, s
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2, a, banana, apple (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop
LineCodeWhat it does
1
n = int(input("How many strings? "))
โŒจ๏ธ Input Shows "How many strings? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
2
letter = input("Enter alphabet to search: ").lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable letter
4
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
5
s = input(f"Enter string {i+1}: ")
โŒจ๏ธ Input Shows the message f"Enter string {i+1}: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
6
print("Occurrences of '" + letter + "' :", s.lower().count(letter))
๐Ÿ–ฅ๏ธ Output Displays the value of "Occurrences of '" + letter + "' :", then the value of s.lower().count(letter) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
n = int(input("How many strings? "))
n = 2
How many strings? 2
22
letter = input("Enter alphabet to search: ").lower()
letter = 'a'
Enter alphabet to search: a
34
for i in range(n):
next item taken
i = 0
45
s = input(f"Enter string {i+1}: ")
s = 'banana'
Enter string 1: banana
56
print("Occurrences of '" + letter + "' :", s.lower().count(letter))
Occurrences of 'a' : 3
64
for i in range(n):
next item taken
i = 1
75
s = input(f"Enter string {i+1}: ")
s = 'apple'
Enter string 2: apple
86
print("Occurrences of '" + letter + "' :", s.lower().count(letter))
Occurrences of 'a' : 1
94
for i in range(n):
no items left โ†’ loop ends
Q18 PYTHON

Write a python program to Create a dictionary to store names of states and their capitals.

states = {
    "Delhi": "New Delhi",
    "Maharashtra": "Mumbai",
    "Rajasthan": "Jaipur",
    "Punjab": "Chandigarh",
    "Kerala": "Thiruvananthapuram"
}

for state, capital in states.items():
    print(state, "->", capital)

query = input("\nEnter state name to find capital: ")
if query in states:
    print("Capital of", query, "is", states[query])
else:
    print("State not found")
โ–ถ Sample Output
Delhi -> New Delhi
Maharashtra -> Mumbai
Rajasthan -> Jaipur
Punjab -> Chandigarh
Kerala -> Thiruvananthapuram

Enter state name to find capital: Punjab
Capital of Punjab is Chandigarh
๐Ÿ’ก Explanation: Classic key-value dictionary โ€” key = state, value = capital.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ query
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Punjab (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
states = {
    "Delhi": "New Delhi",
    "Maharashtra": "Mumbai",
    "Rajasthan": "Jaipur",
    "Punjab": "Chandigarh",
    "Kerala": "Thiruvananthapuram"
}
๐Ÿงฎ Store / Calculate Stores a dictionary { "Delhi": "New Delhi", "Maharashtra": "Mumbaโ€ฆ in variable states
9
for state, capital in states.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary states; state, capital get one pair each round
10
print(state, "->", capital)
๐Ÿ–ฅ๏ธ Output Displays the value of state, then the text "->", then the value of capital on the screen
12
query = input("\nEnter state name to find capital: ")
โŒจ๏ธ Input Shows the message "\nEnter state name to find capital: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable query
13
if query in states:
๐Ÿ”€ Decision CHECKS whether query is present in states. If True, the indented lines below run; otherwise Python jumps to the elif/else part
14
print("Capital of", query, "is", states[query])
๐Ÿ–ฅ๏ธ Output Displays the text "Capital of", then the value of query, then the text "is", then the value of states[query] on the screen
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
print("State not found")
๐Ÿ–ฅ๏ธ Output Displays the text "State not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
"Delhi": "New Delhi",
23
"Maharashtra": "Mumbai",
34
"Rajasthan": "Jaipur",
45
"Punjab": "Chandigarh",
56
"Kerala": "Thiruvananthapuram"
61
states = {
states = {'Delhi': 'New Delhi', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipuโ€ฆ
79
for state, capital in states.items():
next item taken
state = 'Delhi', capital = 'New Delhi'
810
print(state, "->", capital)
Delhi -> New Delhi
99
for state, capital in states.items():
next item taken
state = 'Maharashtra', capital = 'Mumbai'
1010
print(state, "->", capital)
Maharashtra -> Mumbai
119
for state, capital in states.items():
next item taken
state = 'Rajasthan', capital = 'Jaipur'
1210
print(state, "->", capital)
Rajasthan -> Jaipur
139
for state, capital in states.items():
next item taken
state = 'Punjab', capital = 'Chandigarh'
1410
print(state, "->", capital)
Punjab -> Chandigarh
159
for state, capital in states.items():
next item taken
state = 'Kerala', capital = 'Thiruvananthapuram'
1610
print(state, "->", capital)
Kerala -> Thiruvananthapuram
179
for state, capital in states.items():
no items left โ†’ loop ends
1812
query = input("\nEnter state name to find capital: ")
query = 'Punjab'
Enter state name to find capital: Punjab
1913
if query in states:
condition is TRUE โ†’ enters the block
2014
print("Capital of", query, "is", states[query])
Capital of Punjab is Chandigarh
Q19 PYTHON

Write a python program to Create a dictionary of students to store names and marks obtained in 5 subjects.

students = {}
n = int(input("Number of students: "))

for i in range(n):
    name = input("Enter student name: ")
    marks = []
    for s in range(5):
        m = float(input(f"  Marks in subject {s+1}: "))
        marks.append(m)
    students[name] = marks

for name, marks in students.items():
    print(name, ":", marks, " Total =", sum(marks), " Avg =", sum(marks)/5)
โ–ถ Sample Output
Number of students: 2
Enter student name: Amit
  Marks in subject 1: 80
  Marks in subject 2: 85
  Marks in subject 3: 90
  Marks in subject 4: 78
  Marks in subject 5: 92
Enter student name: Sara
  Marks in subject 1: 88
  Marks in subject 2: 91
  Marks in subject 3: 79
  Marks in subject 4: 95
  Marks in subject 5: 84
Amit : [80.0, 85.0, 90.0, 78.0, 92.0]  Total = 425.0  Avg = 85.0
Sara : [88.0, 91.0, 79.0, 95.0, 84.0]  Total = 437.0  Avg = 87.4
๐Ÿ’ก Explanation: Value of the dictionary here is itself a list of 5 marks โ€” a dictionary-of-lists structure.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ n, name, m
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2, Amit, 80, 85, 90, 78, 92, Sara, 88, 91 โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop
LineCodeWhat it does
1
students = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable students
2
n = int(input("Number of students: "))
โŒจ๏ธ Input Shows "Number of students: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
4
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
5
name = input("Enter student name: ")
โŒจ๏ธ Input Shows the message "Enter student name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
6
marks = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable marks
7
for s in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, s takes that value and the indented block runs once
8
m = float(input(f"  Marks in subject {s+1}: "))
โŒจ๏ธ Input Shows f" Marks in subject {s+1}: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable m
9
marks.append(m)
๐Ÿงฎ Store / Calculate Adds m at the end of list marks
10
students[name] = marks
๐Ÿงฎ Store / Calculate Puts the value of marks into students[name] (item name of students)
12
for name, marks in students.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary students; name, marks get one pair each round
13
print(name, ":", marks, " Total =", sum(marks), " Avg =", sum(marks)/5)
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text ":", then the value of marks, then the text "Total =", then the value of sum(marks), then the text "Avg =", then the value of sum(marks)/5 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
students = {}
students = {}
22
n = int(input("Number of students: "))
n = 2
Number of students: 2
34
for i in range(n):
next item taken
i = 0
45
name = input("Enter student name: ")
name = 'Amit'
Enter student name: Amit
56
marks = []
marks = []
67
for s in range(5):
next item taken
s = 0
78
m = float(input(f"  Marks in subject {s+1}: "))
m = 80.0
  Marks in subject 1: 80
89
marks.append(m)
marks = [80.0]
97
for s in range(5):
next item taken
s = 1
108
m = float(input(f"  Marks in subject {s+1}: "))
m = 85.0
  Marks in subject 2: 85
119
marks.append(m)
marks = [80.0, 85.0]
127
for s in range(5):
next item taken
s = 2
138
m = float(input(f"  Marks in subject {s+1}: "))
m = 90.0
  Marks in subject 3: 90
149
marks.append(m)
marks = [80.0, 85.0, 90.0]
157
for s in range(5):
next item taken
s = 3
168
m = float(input(f"  Marks in subject {s+1}: "))
m = 78.0
  Marks in subject 4: 78
179
marks.append(m)
marks = [80.0, 85.0, 90.0, 78.0]
187
for s in range(5):
next item taken
s = 4
198
m = float(input(f"  Marks in subject {s+1}: "))
m = 92.0
  Marks in subject 5: 92
209
marks.append(m)
marks = [80.0, 85.0, 90.0, 78.0, 92.0]
217
for s in range(5):
no items left โ†’ loop ends
2210
students[name] = marks
students = {'Amit': [80.0, 85.0, 90.0, 78.0, 92.0]}
234
for i in range(n):
next item taken
i = 1
245
name = input("Enter student name: ")
name = 'Sara'
Enter student name: Sara
256
marks = []
marks = []
267
for s in range(5):
next item taken
s = 0
278
m = float(input(f"  Marks in subject {s+1}: "))
m = 88.0
  Marks in subject 1: 88
289
marks.append(m)
marks = [88.0]
297
for s in range(5):
next item taken
s = 1
308
m = float(input(f"  Marks in subject {s+1}: "))
m = 91.0
  Marks in subject 2: 91
319
marks.append(m)
marks = [88.0, 91.0]
327
for s in range(5):
next item taken
s = 2

โ€ฆ Python runs 16 more line-steps in the same way (loops repeat the same lines). Final values: students = {'Amit': [80.0, 85.0, 90.0, 78.0, 92.0], 'Sara': [88.0, 91.0, 79.0,โ€ฆ, n = 2, i = 1, name = 'Sara', marks = [88.0, 91.0, 79.0, 95.0, 84.0], s = 4, m = 84.0

Q20 PYTHON

Write a python program to print the highest and lowest values in the dictionary.

d = {"Amit": 78, "Sara": 92, "Rahul": 65, "Priya": 88}

max_key = max(d, key=d.get)
min_key = min(d, key=d.get)

print("Highest:", max_key, "with value", d[max_key])
print("Lowest :", min_key, "with value", d[min_key])
โ–ถ Sample Output
Highest: Sara with value 92
Lowest : Rahul with value 65
๐Ÿ’ก Explanation: max(d, key=d.get) compares dictionary values (not keys) and returns the key with the highest value.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
d = {"Amit": 78, "Sara": 92, "Rahul": 65, "Priya": 88}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Amit": 78, "Sara": 92, "Rahul": 65, "Priya"โ€ฆ in variable d
3
max_key = max(d, key=d.get)
๐Ÿงฎ Store / Calculate Finds the largest value among d; the result is stored in variable max_key
4
min_key = min(d, key=d.get)
๐Ÿงฎ Store / Calculate Finds the smallest value among d; the result is stored in variable min_key
6
print("Highest:", max_key, "with value", d[max_key])
๐Ÿ–ฅ๏ธ Output Displays the text "Highest:", then the value of max_key, then the text "with value", then the value of d[max_key] on the screen
7
print("Lowest :", min_key, "with value", d[min_key])
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest :", then the value of min_key, then the text "with value", then the value of d[min_key] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
d = {"Amit": 78, "Sara": 92, "Rahul": 65, "Priya": 88}
d = {'Amit': 78, 'Sara': 92, 'Rahul': 65, 'Priya': 88}
23
max_key = max(d, key=d.get)
max_key = 'Sara'
34
min_key = min(d, key=d.get)
min_key = 'Rahul'
46
print("Highest:", max_key, "with value", d[max_key])
Highest: Sara with value 92
57
print("Lowest :", min_key, "with value", d[min_key])
Lowest : Rahul with value 65
Q21 PYTHON

Write a python program to create a student dictionary and search by using the name of the student and display the details.

students = {
    "Amit": {"roll": 1, "class": "XI-A", "marks": 88},
    "Sara": {"roll": 2, "class": "XI-B", "marks": 92},
    "Rahul": {"roll": 3, "class": "XI-A", "marks": 76},
}

name = input("Enter student name to search: ")
if name in students:
    print("Details found:")
    for key, val in students[name].items():
        print(" ", key, ":", val)
else:
    print("Student not found")
โ–ถ Sample Output
Enter student name to search: Sara
Details found:
  roll : 2
  class : XI-B
  marks : 92
๐Ÿ’ก Explanation: Nested dictionary again โ€” 'in' operator checks key existence before accessing to avoid a KeyError.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ name
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ip_q21.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Sara (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
students = {
    "Amit": {"roll": 1, "class": "XI-A", "marks": 88},
    "Sara": {"roll": 2, "class": "XI-B", "marks": 92},
    "Rahul": {"roll": 3, "class": โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { "Amit": {"roll": 1, "class": "XI-A", "marksโ€ฆ in variable students
7
name = input("Enter student name to search: ")
โŒจ๏ธ Input Shows the message "Enter student name to search: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
8
if name in students:
๐Ÿ”€ Decision CHECKS whether name is present in students. If True, the indented lines below run; otherwise Python jumps to the elif/else part
9
print("Details found:")
๐Ÿ–ฅ๏ธ Output Displays the text "Details found:" on the screen
10
for key, val in students[name].items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary students[name]; key, val get one pair each round
11
print(" ", key, ":", val)
๐Ÿ–ฅ๏ธ Output Displays a blank, then the value of key, then the text ":", then the value of val on the screen
12
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
13
print("Student not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
"Amit": {"roll": 1, "class": "XI-A", "marks": 88},
23
"Sara": {"roll": 2, "class": "XI-B", "marks": 92},
34
"Rahul": {"roll": 3, "class": "XI-A", "marks": 76},
41
students = {
students = {'Amit': {'roll': 1, 'class': 'XI-A', 'marks': 88}, 'Sara': {'roll'โ€ฆ
57
name = input("Enter student name to search: ")
name = 'Sara'
Enter student name to search: Sara
68
if name in students:
condition is TRUE โ†’ enters the block
79
print("Details found:")
Details found:
810
for key, val in students[name].items():
next item taken
key = 'roll', val = 2
911
print(" ", key, ":", val)
  roll : 2
1010
for key, val in students[name].items():
next item taken
key = 'class', val = 'XI-B'
1111
print(" ", key, ":", val)
  class : XI-B
1210
for key, val in students[name].items():
next item taken
key = 'marks', val = 92
1311
print(" ", key, ":", val)
  marks : 92
1410
for key, val in students[name].items():
no items left โ†’ loop ends
Q22 SQL

SQL: To create a school database and access it.

CREATE DATABASE school;
USE school;

-- Verify:
SHOW DATABASES;
โ–ถ Sample Output
mysql> CREATE DATABASE school;
Query OK, 1 row affected (0.00 sec)

mysql> USE school;
Database changed

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
๐Ÿ’ก Explanation: CREATE DATABASE makes a new database; USE selects it as the active database for subsequent commands.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. The code selects the database with USE school; - MySQL replies Database changed.
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE DATABASE school;

Creates a new, empty database (a folder for tables) named school.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
2
Command
USE school;

Selects the database school - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
๐Ÿ“Œ Verify:
3
Query ยท read only
SHOW DATABASES;

Lists all the databases on the MySQL server.

โœ” Result: 5 rows in set
Q23 SQL

SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key).

CREATE TABLE student (
    student_id INT PRIMARY KEY,
    class      INT,
    section    CHAR(1),
    gender     CHAR(1),
    name       VARCHAR(30),
    dob        DATE,
    marks      DECIMAL(5,2),
    email      VARCHAR(40)
);

DESC student;
โ–ถ Sample Output
mysql> CREATE TABLE student (
    ->     student_id INT PRIMARY KEY,
    ->     class      INT,
    ->     section    CHAR(1),
    ->     gender     CHAR(1),
    ->     name       VARCHAR(30),
    ->     dob        DATE,
    ->     marks      DECIMAL(5,2),
    ->     email      VARCHAR(40)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> DESC student;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int          | NO   | PRI | NULL    |       |
| class      | int          | YES  |     | NULL    |       |
| section    | char(1)      | YES  |     | NULL    |       |
| gender     | char(1)      | YES  |     | NULL    |       |
| name       | varchar(30)  | YES  |     | NULL    |       |
| dob        | date         | YES  |     | NULL    |       |
| marks      | decimal(5,2) | YES  |     | NULL    |       |
| email      | varchar(40)  | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
๐Ÿ’ก Explanation: PRIMARY KEY ensures student_id is unique and NOT NULL for every row โ€” the golden rule of table design.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE TABLE student (
    student_id INT PRIMARY KEY,
    class      INT,
    section    CHAR(1),
    gender     CHAR(1),
    name       VARCHAR(30),
    dob        DATE,
    marks      DECIMAL(5,2),
    email      VARCHAR(40)
);

Creates a new table student with 8 columns. Each column gets a name and a data type:

  • student_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • class โ†’ INT (whole numbers)
  • section โ†’ CHAR(1) (text up to 1 characters)
  • gender โ†’ CHAR(1) (text up to 1 characters)
  • name โ†’ VARCHAR(30) (text up to 30 characters)
  • dob โ†’ DATE (date (YYYY-MM-DD))
  • marks โ†’ DECIMAL(5,2) (decimal number, 5 digits in all with 2 after the point)
  • email โ†’ VARCHAR(40) (text up to 40 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
2
Query ยท read only
DESC student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 8 rows in set
Q24 SQL

SQL: To insert the details of at least 10 students in the above table.

INSERT INTO student VALUES (1,11,'A','M','Amit Kumar','2009-05-14',88.5,'amit@kvsb.in');
INSERT INTO student VALUES (2,11,'B','F','Sara Khan','2009-08-21',92.0,'sara@kvsb.in');
INSERT INTO student VALUES (3,11,'A','M','Rahul Sharma','2008-12-02',65.5,'rahul@kvsb.in');
INSERT INTO student VALUES (4,11,'A','F','Priya Singh','2009-03-11',78.0,'priya@kvsb.in');
INSERT INTO student VALUES (5,11,'B','M','Anand Verma','2009-07-19',55.0,'anand@kvsb.in');
INSERT INTO student VALUES (6,11,'A','F','Angad Kaur','2009-01-25',81.0,'angad@kvsb.in');
INSERT INTO student VALUES (7,11,'B','M','Vivek Yadav','2008-11-30',48.0,'vivek@kvsb.in');
INSERT INTO student VALUES (8,11,'A','F','Neha Gupta','2009-09-09',95.0,'neha@kvsb.in');
INSERT INTO student VALUES (9,11,'B','M','Karan Mehta','2009-04-17',60.0,'karan@kvsb.in');
INSERT INTO student VALUES (10,11,'A','F','Divya Rao','2008-10-05',73.5,'divya@kvsb.in');
โ–ถ Sample Output
mysql> INSERT INTO student VALUES (1,11,'A','M','Amit Kumar','2009-05-14',88.5,'amit@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (2,11,'B','F','Sara Khan','2009-08-21',92.0,'sara@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (3,11,'A','M','Rahul Sharma','2008-12-02',65.5,'rahul@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (4,11,'A','F','Priya Singh','2009-03-11',78.0,'priya@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (5,11,'B','M','Anand Verma','2009-07-19',55.0,'anand@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (6,11,'A','F','Angad Kaur','2009-01-25',81.0,'angad@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (7,11,'B','M','Vivek Yadav','2008-11-30',48.0,'vivek@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (8,11,'A','F','Neha Gupta','2009-09-09',95.0,'neha@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (9,11,'B','M','Karan Mehta','2009-04-17',60.0,'karan@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (10,11,'A','F','Divya Rao','2008-10-05',73.5,'divya@kvsb.in');
Query OK, 1 row affected (0.00 sec)
๐Ÿ’ก Explanation: Column order must exactly match the CREATE TABLE order when values are given without column names.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DML ยท data change
INSERT INTO student VALUES (1,11,'A','M','Amit Kumar','2009-05-14',88.5,'amit@kvsb.in');
โ€ฆ (9 more INSERT statements of the same kind)

These 10 INSERT statements add 10 rows, one row each, into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: each INSERT says "Query OK, 1 row affected"
Q25 SQL

SQL: To display the entire content of the table.

SELECT * FROM student;
โ–ถ Sample Output
mysql> SELECT * FROM student;
+------------+-------+---------+--------+--------------+------------+-------+---------------+
| student_id | class | section | gender | name         | dob        | marks | email         |
+------------+-------+---------+--------+--------------+------------+-------+---------------+
|          1 |    11 | A       | M      | Amit Kumar   | 2009-05-14 | 88.50 | amit@kvsb.in  |
|          2 |    11 | B       | F      | Sara Khan    | 2009-08-21 | 92.00 | sara@kvsb.in  |
|          3 |    11 | A       | M      | Rahul Sharma | 2008-12-02 | 65.50 | rahul@kvsb.in |
|          4 |    11 | A       | F      | Priya Singh  | 2009-03-11 | 78.00 | priya@kvsb.in |
|          5 |    11 | B       | M      | Anand Verma  | 2009-07-19 | 55.00 | anand@kvsb.in |
|          6 |    11 | A       | F      | Angad Kaur   | 2009-01-25 | 81.00 | angad@kvsb.in |
|          7 |    11 | B       | M      | Vivek Yadav  | 2008-11-30 | 48.00 | vivek@kvsb.in |
|          8 |    11 | A       | F      | Neha Gupta   | 2009-09-09 | 95.00 | neha@kvsb.in  |
|          9 |    11 | B       | M      | Karan Mehta  | 2009-04-17 | 60.00 | karan@kvsb.in |
|         10 |    11 | A       | F      | Divya Rao    | 2008-10-05 | 73.50 | divya@kvsb.in |
+------------+-------+---------+--------+--------------+------------+-------+---------------+
10 rows in set (0.00 sec)
๐Ÿ’ก Explanation: SELECT * fetches all columns; use this to verify data after every INSERT.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT * FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 10 rows in set
Q26 SQL

SQL: To display Rno, Name and Marks of those students scoring marks more than 50.

SELECT student_id, name, marks
FROM student
WHERE marks > 50;
โ–ถ Sample Output
mysql> SELECT student_id, name, marks
    -> FROM student
    -> WHERE marks > 50;
+------------+--------------+-------+
| student_id | name         | marks |
+------------+--------------+-------+
|          1 | Amit Kumar   | 88.50 |
|          2 | Sara Khan    | 92.00 |
|          3 | Rahul Sharma | 65.50 |
|          4 | Priya Singh  | 78.00 |
|          5 | Anand Verma  | 55.00 |
|          6 | Angad Kaur   | 81.00 |
|          8 | Neha Gupta   | 95.00 |
|          9 | Karan Mehta  | 60.00 |
|         10 | Divya Rao    | 73.50 |
+------------+--------------+-------+
9 rows in set (0.00 sec)
๐Ÿ’ก Explanation: WHERE filters rows based on a condition โ€” here, marks strictly greater than 50.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, marks
FROM student
WHERE marks > 50;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks > 50 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, marks โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 9 rows in set
Q27 SQL

SQL: To find the average of marks from the student table.

SELECT AVG(marks) AS Average_Marks
FROM student;
โ–ถ Sample Output
mysql> SELECT AVG(marks) AS Average_Marks
    -> FROM student;
+---------------+
| Average_Marks |
+---------------+
|     73.650000 |
+---------------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: AVG() is an aggregate function that returns a single summary value across all matching rows.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT AVG(marks) AS Average_Marks
FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT AVG(marks) AS Average_Marks โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
Q28 SQL

SQL: To find the number of students who are from section 'A'.

SELECT COUNT(*) AS Total_Section_A
FROM student
WHERE section = 'A';
โ–ถ Sample Output
mysql> SELECT COUNT(*) AS Total_Section_A
    -> FROM student
    -> WHERE section = 'A';
+-----------------+
| Total_Section_A |
+-----------------+
|               6 |
+-----------------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: COUNT(*) counts rows matching the WHERE condition.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT COUNT(*) AS Total_Section_A
FROM student
WHERE section = 'A';

Fetches the summary values from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE section = 'A' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT COUNT(*) AS Total_Section_A โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
Q29 SQL

SQL: To display information of all students whose name starts with 'AN'.

SELECT * FROM student
WHERE name LIKE 'AN%';
โ–ถ Sample Output
mysql> SELECT * FROM student
    -> WHERE name LIKE 'AN%';
+------------+-------+---------+--------+-------------+------------+-------+---------------+
| student_id | class | section | gender | name        | dob        | marks | email         |
+------------+-------+---------+--------+-------------+------------+-------+---------------+
|          5 |    11 | B       | M      | Anand Verma | 2009-07-19 | 55.00 | anand@kvsb.in |
|          6 |    11 | A       | F      | Angad Kaur  | 2009-01-25 | 81.00 | angad@kvsb.in |
+------------+-------+---------+--------+-------------+------------+-------+---------------+
2 rows in set (0.00 sec)
๐Ÿ’ก Explanation: LIKE with wildcard % matches any characters after 'AN' โ€” the classic pattern-matching operator.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT * FROM student
WHERE name LIKE 'AN%';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE name LIKE 'AN%' (starts with "AN") โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 2 rows in set
Q30 SQL

SQL: To display Rno, Name, DOB of students born between '2009-01-01' and '2009-12-31'.

SELECT student_id, name, dob
FROM student
WHERE dob BETWEEN '2009-01-01' AND '2009-12-31';
โ–ถ Sample Output
mysql> SELECT student_id, name, dob
    -> FROM student
    -> WHERE dob BETWEEN '2009-01-01' AND '2009-12-31';
+------------+-------------+------------+
| student_id | name        | dob        |
+------------+-------------+------------+
|          1 | Amit Kumar  | 2009-05-14 |
|          2 | Sara Khan   | 2009-08-21 |
|          4 | Priya Singh | 2009-03-11 |
|          5 | Anand Verma | 2009-07-19 |
|          6 | Angad Kaur  | 2009-01-25 |
|          8 | Neha Gupta  | 2009-09-09 |
|          9 | Karan Mehta | 2009-04-17 |
+------------+-------------+------------+
7 rows in set (0.00 sec)
๐Ÿ’ก Explanation: BETWEEN is inclusive of both boundary dates.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, dob
FROM student
WHERE dob BETWEEN '2009-01-01' AND '2009-12-31';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE dob BETWEEN '2009-01-01' AND '2009-12-31' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, dob โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 7 rows in set
Q31 SQL

SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names.

SELECT student_id, name, dob, marks, email
FROM student
WHERE gender = 'M'
ORDER BY name ASC;
โ–ถ Sample Output
mysql> SELECT student_id, name, dob, marks, email
    -> FROM student
    -> WHERE gender = 'M'
    -> ORDER BY name ASC;
+------------+--------------+------------+-------+---------------+
| student_id | name         | dob        | marks | email         |
+------------+--------------+------------+-------+---------------+
|          1 | Amit Kumar   | 2009-05-14 | 88.50 | amit@kvsb.in  |
|          5 | Anand Verma  | 2009-07-19 | 55.00 | anand@kvsb.in |
|          9 | Karan Mehta  | 2009-04-17 | 60.00 | karan@kvsb.in |
|          3 | Rahul Sharma | 2008-12-02 | 65.50 | rahul@kvsb.in |
|          7 | Vivek Yadav  | 2008-11-30 | 48.00 | vivek@kvsb.in |
+------------+--------------+------------+-------+---------------+
5 rows in set (0.00 sec)
๐Ÿ’ก Explanation: ORDER BY ... ASC sorts alphabetically (add an 'email' VARCHAR column to your table via ALTER TABLE if not already present).
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, dob, marks, email
FROM student
WHERE gender = 'M'
ORDER BY name ASC;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE gender = 'M' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, dob, marks, email โ†’ picks the columns / calculates the values to show.
  4. ORDER BY name ASC โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 5 rows in set
Q32 SQL

SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks.

SELECT student_id, gender, name, dob, marks, email
FROM student
ORDER BY marks DESC;
โ–ถ Sample Output
mysql> SELECT student_id, gender, name, dob, marks, email
    -> FROM student
    -> ORDER BY marks DESC;
+------------+--------+--------------+------------+-------+---------------+
| student_id | gender | name         | dob        | marks | email         |
+------------+--------+--------------+------------+-------+---------------+
|          8 | F      | Neha Gupta   | 2009-09-09 | 95.00 | neha@kvsb.in  |
|          2 | F      | Sara Khan    | 2009-08-21 | 92.00 | sara@kvsb.in  |
|          1 | M      | Amit Kumar   | 2009-05-14 | 88.50 | amit@kvsb.in  |
|          6 | F      | Angad Kaur   | 2009-01-25 | 81.00 | angad@kvsb.in |
|          4 | F      | Priya Singh  | 2009-03-11 | 78.00 | priya@kvsb.in |
|         10 | F      | Divya Rao    | 2008-10-05 | 73.50 | divya@kvsb.in |
|          3 | M      | Rahul Sharma | 2008-12-02 | 65.50 | rahul@kvsb.in |
|          9 | M      | Karan Mehta  | 2009-04-17 | 60.00 | karan@kvsb.in |
|          5 | M      | Anand Verma  | 2009-07-19 | 55.00 | anand@kvsb.in |
|          7 | M      | Vivek Yadav  | 2008-11-30 | 48.00 | vivek@kvsb.in |
+------------+--------+--------------+------------+-------+---------------+
10 rows in set (0.00 sec)
๐Ÿ’ก Explanation: DESC sorts highest-to-lowest โ€” useful for merit-list style ranking.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, gender, name, dob, marks, email
FROM student
ORDER BY marks DESC;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT student_id, gender, name, dob, marks, email โ†’ picks the columns / calculates the values to show.
  3. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 10 rows in set
Q33 SQL

SQL: To display the unique sections available in the table.

SELECT DISTINCT section FROM student;
โ–ถ Sample Output
mysql> SELECT DISTINCT section FROM student;
+---------+
| section |
+---------+
| A       |
| B       |
+---------+
2 rows in set (0.00 sec)
๐Ÿ’ก Explanation: DISTINCT removes duplicate values, showing each section only once.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT DISTINCT section FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT section โ†’ picks the columns / calculates the values to show.
  3. DISTINCT โ†’ removes repeated rows, so each value appears only once.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 2 rows in set
Q34 SQL

SQL: To display the name and class of students whose marks are less than 33.

SELECT name, class
FROM student
WHERE marks < 33;
โ–ถ Sample Output
mysql> SELECT name, class
    -> FROM student
    -> WHERE marks < 33;
Empty set (0.00 sec)
๐Ÿ’ก Explanation: Identifies 'failed' students โ€” marks below the pass threshold of 33.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT name, class
FROM student
WHERE marks < 33;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks < 33 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, class โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: Empty set
Q35 SQL

SQL: To display the structure of the student table.

DESC student;
-- or
DESCRIBE student;
โ–ถ Sample Output
mysql> DESC student;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int          | NO   | PRI | NULL    |       |
| class      | int          | YES  |     | NULL    |       |
| section    | char(1)      | YES  |     | NULL    |       |
| gender     | char(1)      | YES  |     | NULL    |       |
| name       | varchar(30)  | YES  |     | NULL    |       |
| dob        | date         | YES  |     | NULL    |       |
| marks      | decimal(5,2) | YES  |     | NULL    |       |
| email      | varchar(40)  | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> DESCRIBE student;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int          | NO   | PRI | NULL    |       |
| class      | int          | YES  |     | NULL    |       |
| section    | char(1)      | YES  |     | NULL    |       |
| gender     | char(1)      | YES  |     | NULL    |       |
| name       | varchar(30)  | YES  |     | NULL    |       |
| dob        | date         | YES  |     | NULL    |       |
| marks      | decimal(5,2) | YES  |     | NULL    |       |
| email      | varchar(40)  | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
๐Ÿ’ก Explanation: DESC shows column names, data types, keys and nullability โ€” not to be confused with ORDER BY DESC.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
DESC student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 8 rows in set
๐Ÿ“Œ or
2
Query ยท read only
DESCRIBE student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 8 rows in set
Q36 SQL

SQL: To display the Name and DOB of students who were born in 2008.

SELECT name, dob
FROM student
WHERE YEAR(dob) = 2008;
โ–ถ Sample Output
mysql> SELECT name, dob
    -> FROM student
    -> WHERE YEAR(dob) = 2008;
+--------------+------------+
| name         | dob        |
+--------------+------------+
| Rahul Sharma | 2008-12-02 |
| Vivek Yadav  | 2008-11-30 |
| Divya Rao    | 2008-10-05 |
+--------------+------------+
3 rows in set (0.00 sec)
๐Ÿ’ก Explanation: YEAR() is a MySQL date function that extracts just the year part from a DATE column.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT name, dob
FROM student
WHERE YEAR(dob) = 2008;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE YEAR(dob) = 2008 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, dob โ†’ picks the columns / calculates the values to show.
  4. Functions used: YEAR() takes the year from a date.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
111AMAmit Kumar2009-05-1488.50amit@kvsb.in
211BFSara Khan2009-08-2192.00sara@kvsb.in
311AMRahul Sharma2008-12-0265.50rahul@kvsb.in
411AFPriya Singh2009-03-1178.00priya@kvsb.in
511BMAnand Verma2009-07-1955.00anand@kvsb.in
611AFAngad Kaur2009-01-2581.00angad@kvsb.in
711BMVivek Yadav2008-11-3048.00vivek@kvsb.in
811AFNeha Gupta2009-09-0995.00neha@kvsb.in
911BMKaran Mehta2009-04-1760.00karan@kvsb.in
1011AFDivya Rao2008-10-0573.50divya@kvsb.in
โœ” Result: 3 rows in set

Class XII โ€” Computer Science (083)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 25 Practicals + Project

๐Ÿ“˜ View Syllabus 2026-27 0%
๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

Q1 PYTHON

Search an element in a list and display frequency & location using Linear Search (user-defined function).

def linear_search(lst, key):
    positions = []
    for i in range(len(lst)):
        if lst[i] == key:
            positions.append(i)
    return positions

lst = list(map(int, input("Enter list elements: ").split()))
key = int(input("Enter element to search: "))

result = linear_search(lst, key)
if result:
    print(key, "found", len(result), "time(s) at position(s):", result)
else:
    print(key, "not found in the list")
โ–ถ Sample Output
Enter list elements: 10 20 30 20 40 20
Enter element to search: 20
20 found 3 time(s) at position(s): [1, 3, 5]
๐Ÿ’ก Explanation: Linear search scans every element one by one โ€” works on unsorted lists too. Time complexity O(n).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ lst, key
โžœ
โ‘ก PROCESSuses its own function linear_search(); decisions with if / elif / else; a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q1.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10 20 30 20 40 20, 20 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def linear_search(lst, key):
๐Ÿงฉ Function DEFINES a function linear_search(lst, key). Python only remembers it here - its body runs later, each time linear_search() is called.
2
positions = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable positions
3
for i in range(len(lst)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(lst) - 1; for each number, i takes that value and the indented block runs once
4
if lst[i] == key:
๐Ÿ”€ Decision CHECKS whether lst[i] is equal to key. If True, the indented lines below run; otherwise they are skipped
5
positions.append(i)
๐Ÿงฎ Store / Calculate Adds i at the end of list positions
6
return positions
๐Ÿงฉ Function Sends back (returns) the value of positions to the line that called the function
8
lst = list(map(int, input("Enter list elements: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter list elements: ").splitโ€ฆ; the result is stored in variable lst
9
key = int(input("Enter element to search: "))
โŒจ๏ธ Input Shows "Enter element to search: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable key
11
result = linear_search(lst, key)
๐Ÿงฎ Store / Calculate Calls our own function linear_search(lst, key); the result is stored in variable result
12
if result:
๐Ÿ”€ Decision CHECKS whether result is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
13
print(key, "found", len(result), "time(s) at position(s):", result)
๐Ÿ–ฅ๏ธ Output Displays the value of key, then the text "found", then the value of len(result), then the text "time(s) at position(s):", then the value of result on the screen
14
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
15
print(key, "not found in the list")
๐Ÿ–ฅ๏ธ Output Displays the value of key, then the text "not found in the list" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def linear_search(lst, key):
function is defined (remembered), not run yet
28
lst = list(map(int, input("Enter list elements: ").split()))
lst = [10, 20, 30, 20, 40, 20]
Enter list elements: 10 20 30 20 40 20
39
key = int(input("Enter element to search: "))
key = 20
Enter element to search: 20
411
result = linear_search(lst, key)
result = [1, 3, 5]
โžก Python jumps INTO function linear_search(lst=[10, 20, 30, 20, 40, 20], key=20)
52
positions = []
positions = []
63
for i in range(len(lst)):
next item taken
i = 0
74
if lst[i] == key:
condition is FALSE โ†’ skips this block
83
for i in range(len(lst)):
next item taken
i = 1
94
if lst[i] == key:
condition is TRUE โ†’ enters the block
105
positions.append(i)
positions = [1]
113
for i in range(len(lst)):
next item taken
i = 2
124
if lst[i] == key:
condition is FALSE โ†’ skips this block
133
for i in range(len(lst)):
next item taken
i = 3
144
if lst[i] == key:
condition is TRUE โ†’ enters the block
155
positions.append(i)
positions = [1, 3]
163
for i in range(len(lst)):
next item taken
i = 4
174
if lst[i] == key:
condition is FALSE โ†’ skips this block
183
for i in range(len(lst)):
next item taken
i = 5
194
if lst[i] == key:
condition is TRUE โ†’ enters the block
205
positions.append(i)
positions = [1, 3, 5]
213
for i in range(len(lst)):
no items left โ†’ loop ends
226
return positions
โฌ… function linear_search() ends and returns [1, 3, 5] to the caller
2312
if result:
condition is TRUE โ†’ enters the block
2413
print(key, "found", len(result), "time(s) at position(s):", result)
20 found 3 time(s) at position(s): [1, 3, 5]
Q2 PYTHON

Search an element in a list and display frequency & location using Binary Search (user-defined function).

def binary_search(lst, key):
    low, high = 0, len(lst) - 1
    positions = []
    while low <= high:
        mid = (low + high) // 2
        if lst[mid] == key:
            positions.append(mid)
            # expand outward to find all occurrences
            i = mid - 1
            while i >= 0 and lst[i] == key:
                positions.append(i); i -= 1
            i = mid + 1
            while i < len(lst) and lst[i] == key:
                positions.append(i); i += 1
            break
        elif lst[mid] < key:
            low = mid + 1
        else:
            high = mid - 1
    return sorted(positions)

lst = sorted(map(int, input("Enter list elements: ").split()))
key = int(input("Enter element to search: "))
print("Sorted list:", lst)

result = binary_search(lst, key)
if result:
    print(key, "found", len(result), "time(s) at position(s):", result)
else:
    print(key, "not found")
โ–ถ Sample Output
Enter list elements: 5 12 8 20 3
Enter element to search: 12
Sorted list: [3, 5, 8, 12, 20]
12 found 1 time(s) at position(s): [3]
๐Ÿ’ก Explanation: Binary search REQUIRES a sorted list; it halves the search space each time โ€” much faster, O(log n).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ lst, key
โžœ
โ‘ก PROCESSuses its own function binary_search(); decisions with if / elif / else; a while loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q2.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 5 12 8 20 3, 12 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function๐Ÿ“Œ Comment
LineCodeWhat it does
1
def binary_search(lst, key):
๐Ÿงฉ Function DEFINES a function binary_search(lst, key). Python only remembers it here - its body runs later, each time binary_search() is called.
2
low, high = 0, len(lst) - 1
๐Ÿงฎ Store / Calculate Stores 0, len(lst) - 1 into low, high respectively
3
positions = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable positions
4
while low <= high:
๐Ÿ” Loop LOOP: repeats the indented block as long as low is less than or equal to high; checks the condition before every round
5
mid = (low + high) // 2
๐Ÿงฎ Store / Calculate Stores the value of (low + high) // 2 (calculated using // (integer division)) in variable mid
6
if lst[mid] == key:
๐Ÿ”€ Decision CHECKS whether lst[mid] is equal to key. If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
positions.append(mid)
๐Ÿงฎ Store / Calculate Adds mid at the end of list positions
๐Ÿ“Œ expand outward to find all occurrences
9
i = mid - 1
๐Ÿงฎ Store / Calculate Stores the value of mid - 1 (calculated using -) in variable i
10
while i >= 0 and lst[i] == key:
๐Ÿ” Loop LOOP: repeats the indented block as long as (i is greater than or equal to 0 AND lst[i] is equal to key); checks the condition before every round
11
positions.append(i); i -= 1
๐Ÿงฎ Store / Calculate Adds i at the end of list positions
11
positions.append(i); i -= 1
๐Ÿงฎ Store / Calculate Subtracts 1 from i (same as i = i - 1)
12
i = mid + 1
๐Ÿงฎ Store / Calculate Stores the value of mid + 1 (calculated using +) in variable i
13
while i < len(lst) and lst[i] == key:
๐Ÿ” Loop LOOP: repeats the indented block as long as (i is less than len(lst) AND lst[i] is equal to key); checks the condition before every round
14
positions.append(i); i += 1
๐Ÿงฎ Store / Calculate Adds i at the end of list positions
14
positions.append(i); i += 1
๐Ÿงฎ Store / Calculate Adds 1 to i (same as i = i + 1)
15
break
๐Ÿ” Loop BREAK - leaves the loop immediately
16
elif lst[mid] < key:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether lst[mid] is less than key
17
low = mid + 1
๐Ÿงฎ Store / Calculate Stores the value of mid + 1 (calculated using +) in variable low
18
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
19
high = mid - 1
๐Ÿงฎ Store / Calculate Stores the value of mid - 1 (calculated using -) in variable high
20
return sorted(positions)
๐Ÿงฉ Function Sends back (returns) the result of: makes a new sorted list from positions to the line that called the function
22
lst = sorted(map(int, input("Enter list elements: ").split()))
โŒจ๏ธ Input Makes a new sorted list from map(int, input("Enter list elements: ").splitโ€ฆ; the result is stored in variable lst
23
key = int(input("Enter element to search: "))
โŒจ๏ธ Input Shows "Enter element to search: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable key
24
print("Sorted list:", lst)
๐Ÿ–ฅ๏ธ Output Displays the text "Sorted list:", then the value of lst on the screen
26
result = binary_search(lst, key)
๐Ÿงฎ Store / Calculate Calls our own function binary_search(lst, key); the result is stored in variable result
27
if result:
๐Ÿ”€ Decision CHECKS whether result is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
28
print(key, "found", len(result), "time(s) at position(s):", result)
๐Ÿ–ฅ๏ธ Output Displays the value of key, then the text "found", then the value of len(result), then the text "time(s) at position(s):", then the value of result on the screen
29
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
30
print(key, "not found")
๐Ÿ–ฅ๏ธ Output Displays the value of key, then the text "not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def binary_search(lst, key):
function is defined (remembered), not run yet
222
lst = sorted(map(int, input("Enter list elements: ").split()))
lst = [3, 5, 8, 12, 20]
Enter list elements: 5 12 8 20 3
323
key = int(input("Enter element to search: "))
key = 12
Enter element to search: 12
424
print("Sorted list:", lst)
Sorted list: [3, 5, 8, 12, 20]
526
result = binary_search(lst, key)
result = [3]
โžก Python jumps INTO function binary_search(lst=[3, 5, 8, 12, 20], key=12)
62
low, high = 0, len(lst) - 1
low = 0, high = 4
73
positions = []
positions = []
84
while low <= high:
condition is TRUE โ†’ enters the block
95
mid = (low + high) // 2
mid = 2
106
if lst[mid] == key:
condition is FALSE โ†’ skips this block
1116
elif lst[mid] < key:
condition is TRUE โ†’ enters the block
1217
low = mid + 1
low = 3
134
while low <= high:
condition is TRUE โ†’ enters the block
145
mid = (low + high) // 2
mid = 3
156
if lst[mid] == key:
condition is TRUE โ†’ enters the block
167
positions.append(mid)
positions = [3]
179
i = mid - 1
i = 2
1810
while i >= 0 and lst[i] == key:
condition is FALSE โ†’ loop ends
1912
i = mid + 1
i = 4
2013
while i < len(lst) and lst[i] == key:
condition is FALSE โ†’ loop ends
2115
break
2220
return sorted(positions)
โฌ… function binary_search() ends and returns [3] to the caller
2327
if result:
condition is TRUE โ†’ enters the block
2428
print(key, "found", len(result), "time(s) at position(s):", result)
12 found 1 time(s) at position(s): [3]
Q3 PYTHON

Pass a list to a function; double the odd values and half the even values, then display the changed list.

def modify(lst):
    for i in range(len(lst)):
        if lst[i] % 2 == 0:
            lst[i] = lst[i] / 2
        else:
            lst[i] = lst[i] * 2
    return lst

lst = list(map(int, input("Enter list elements: ").split()))
print("Original list :", lst)
print("Modified list :", modify(lst))
โ–ถ Sample Output
Enter list elements: 1 2 3 4 5 6
Original list : [1, 2, 3, 4, 5, 6]
Modified list : [2, 1.0, 6, 2.0, 10, 3.0]
๐Ÿ’ก Explanation: Lists are mutable and passed by reference in Python โ€” the function directly modifies the original list.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ lst
โžœ
โ‘ก PROCESSuses its own function modify(); a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1 2 3 4 5 6 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def modify(lst):
๐Ÿงฉ Function DEFINES a function modify(lst). Python only remembers it here - its body runs later, each time modify() is called.
2
for i in range(len(lst)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(lst) - 1; for each number, i takes that value and the indented block runs once
3
if lst[i] % 2 == 0:
๐Ÿ”€ Decision CHECKS whether lst[i] % 2 is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
lst[i] = lst[i] / 2
๐Ÿงฎ Store / Calculate Puts the value of lst[i] / 2 (calculated using รท) into lst[i] (item i of lst)
5
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
6
lst[i] = lst[i] * 2
๐Ÿงฎ Store / Calculate Puts the value of lst[i] * 2 (calculated using ร—) into lst[i] (item i of lst)
7
return lst
๐Ÿงฉ Function Sends back (returns) the value of lst to the line that called the function
9
lst = list(map(int, input("Enter list elements: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter list elements: ").splitโ€ฆ; the result is stored in variable lst
10
print("Original list :", lst)
๐Ÿ–ฅ๏ธ Output Displays the text "Original list :", then the value of lst on the screen
11
print("Modified list :", modify(lst))
๐Ÿ–ฅ๏ธ Output Displays the text "Modified list :", then the value of modify(lst) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def modify(lst):
function is defined (remembered), not run yet
29
lst = list(map(int, input("Enter list elements: ").split()))
lst = [1, 2, 3, 4, 5, 6]
Enter list elements: 1 2 3 4 5 6
310
print("Original list :", lst)
Original list : [1, 2, 3, 4, 5, 6]
411
print("Modified list :", modify(lst))
lst = [2, 1.0, 6, 2.0, 10, 3.0]
Modified list : [2, 1.0, 6, 2.0, 10, 3.0]
โžก Python jumps INTO function modify(lst=[1, 2, 3, 4, 5, 6])
52
for i in range(len(lst)):
next item taken
i = 0
63
if lst[i] % 2 == 0:
condition is FALSE โ†’ skips this block
76
lst[i] = lst[i] * 2
lst = [2, 2, 3, 4, 5, 6]
82
for i in range(len(lst)):
next item taken
i = 1
93
if lst[i] % 2 == 0:
condition is TRUE โ†’ enters the block
104
lst[i] = lst[i] / 2
lst = [2, 1.0, 3, 4, 5, 6]
112
for i in range(len(lst)):
next item taken
i = 2
123
if lst[i] % 2 == 0:
condition is FALSE โ†’ skips this block
136
lst[i] = lst[i] * 2
lst = [2, 1.0, 6, 4, 5, 6]
142
for i in range(len(lst)):
next item taken
i = 3
153
if lst[i] % 2 == 0:
condition is TRUE โ†’ enters the block
164
lst[i] = lst[i] / 2
lst = [2, 1.0, 6, 2.0, 5, 6]
172
for i in range(len(lst)):
next item taken
i = 4
183
if lst[i] % 2 == 0:
condition is FALSE โ†’ skips this block
196
lst[i] = lst[i] * 2
lst = [2, 1.0, 6, 2.0, 10, 6]
202
for i in range(len(lst)):
next item taken
i = 5
213
if lst[i] % 2 == 0:
condition is TRUE โ†’ enters the block
224
lst[i] = lst[i] / 2
lst = [2, 1.0, 6, 2.0, 10, 3.0]
232
for i in range(len(lst)):
no items left โ†’ loop ends
247
return lst
โฌ… function modify() ends and returns [2, 1.0, 6, 2.0, 10, 3.0] to the caller
Q4 PYTHON

Input n numbers in a tuple and pass it to a function to count how many even and odd numbers are entered.

def count_even_odd(t):
    even = odd = 0
    for num in t:
        if num % 2 == 0:
            even += 1
        else:
            odd += 1
    return even, odd

n = int(input("How many numbers? "))
t = tuple(int(input("Enter number: ")) for _ in range(n))

e, o = count_even_odd(t)
print("Tuple:", t)
print("Even count:", e, " Odd count:", o)
โ–ถ Sample Output
How many numbers? 5
Enter number: 2
Enter number: 4
Enter number: 6
Enter number: 3
Enter number: 5
Tuple: (2, 4, 6, 3, 5)
Even count: 3  Odd count: 2
๐Ÿ’ก Explanation: Function returns two values as a tuple โ€” Python auto-unpacks them into e, o at the call site.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ n, t
โžœ
โ‘ก PROCESSuses its own function count_even_odd(); a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 5, 2, 4, 6, 3, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def count_even_odd(t):
๐Ÿงฉ Function DEFINES a function count_even_odd(t). Python only remembers it here - its body runs later, each time count_even_odd() is called.
2
even = odd = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable even
3
for num in t:
๐Ÿ” Loop LOOP: takes each item of t one-by-one into num and runs the indented block for it
4
if num % 2 == 0:
๐Ÿ”€ Decision CHECKS whether num % 2 is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
even += 1
๐Ÿงฎ Store / Calculate Adds 1 to even (same as even = even + 1)
6
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
7
odd += 1
๐Ÿงฎ Store / Calculate Adds 1 to odd (same as odd = odd + 1)
8
return even, odd
๐Ÿงฉ Function Sends back (returns) the tuple even, odd to the line that called the function
10
n = int(input("How many numbers? "))
โŒจ๏ธ Input Shows "How many numbers? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
11
t = tuple(int(input("Enter number: ")) for _ in range(n))
โŒจ๏ธ Input Makes a tuple from (int(input("Enter number: ")) for _ in range(โ€ฆ; the result is stored in variable t
13
e, o = count_even_odd(t)
๐Ÿงฎ Store / Calculate Calls our own function count_even_odd(t); the result is stored in variables e, o
14
print("Tuple:", t)
๐Ÿ–ฅ๏ธ Output Displays the text "Tuple:", then the value of t on the screen
15
print("Even count:", e, " Odd count:", o)
๐Ÿ–ฅ๏ธ Output Displays the text "Even count:", then the value of e, then the text "Odd count:", then the value of o on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def count_even_odd(t):
function is defined (remembered), not run yet
210
n = int(input("How many numbers? "))
n = 5
How many numbers? 5
311
t = tuple(int(input("Enter number: ")) for _ in range(n))
t = (2, 4, 6, 3, 5)
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
411
t = tuple(int(input("Enter number: ")) for _ in range(n))
_ = 0
Enter number: 2
โฌ… function <genexpr>() ends and returns 2 to the caller
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
511
t = tuple(int(input("Enter number: ")) for _ in range(n))
_ = 1
Enter number: 4
โฌ… function <genexpr>() ends and returns 4 to the caller
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
611
t = tuple(int(input("Enter number: ")) for _ in range(n))
_ = 2
Enter number: 6
โฌ… function <genexpr>() ends and returns 6 to the caller
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
711
t = tuple(int(input("Enter number: ")) for _ in range(n))
_ = 3
Enter number: 3
โฌ… function <genexpr>() ends and returns 3 to the caller
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
811
t = tuple(int(input("Enter number: ")) for _ in range(n))
_ = 4
Enter number: 5
โฌ… function <genexpr>() ends and returns 5 to the caller
โžก Python jumps INTO function <genexpr>(.0=<range_iterator object at 0x7f894ac77a80>)
911
t = tuple(int(input("Enter number: ")) for _ in range(n))
โฌ… function <genexpr>() ends and returns None to the caller
1013
e, o = count_even_odd(t)
e = 3, o = 2
โžก Python jumps INTO function count_even_odd(t=(2, 4, 6, 3, 5))
112
even = odd = 0
even = 0, odd = 0
123
for num in t:
next item taken
num = 2
134
if num % 2 == 0:
condition is TRUE โ†’ enters the block
145
even += 1
even = 1
153
for num in t:
next item taken
num = 4
164
if num % 2 == 0:
condition is TRUE โ†’ enters the block
175
even += 1
even = 2
183
for num in t:
next item taken
num = 6
194
if num % 2 == 0:
condition is TRUE โ†’ enters the block

โ€ฆ Python runs 11 more line-steps in the same way (loops repeat the same lines). Final values: n = 5, t = (2, 4, 6, 3, 5), _ = 4, e = 3, o = 2, even = 3, odd = 2, num = 5

Q5 PYTHON

Function with key and value updates the value at that key in a dictionary entered by the user.

def update_dict(d, key, value):
    if key in d:
        d[key] = value
        print("Updated successfully!")
    else:
        print("Key not found, adding as new entry")
        d[key] = value
    return d

d = {}
n = int(input("How many key-value pairs to enter? "))
for i in range(n):
    k = input("Enter key: ")
    v = input("Enter value: ")
    d[k] = v

print("Dictionary:", d)
key = input("Enter key to update: ")
value = input("Enter new value: ")
print("Result:", update_dict(d, key, value))
โ–ถ Sample Output
How many key-value pairs to enter? 3
Enter key: 1
Enter value: Amit
Enter key: 2
Enter value: Sara
Enter key: 3
Enter value: Rahul
Dictionary: {'1': 'Amit', '2': 'Sara', '3': 'Rahul'}
Enter key to update: 2
Enter new value: Sara-Updated
Updated successfully!
Result: {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'}
๐Ÿ’ก Explanation: d[key] = value works both to add a new pair and to update an existing one โ€” dictionaries handle this automatically.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 5 values from the keyboard โ†’ n, key, value, k, v
โžœ
โ‘ก PROCESSuses its own function update_dict(); a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 3, 1, Amit, 2, Sara, 3, Rahul, 2, Sara-Updated (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def update_dict(d, key, value):
๐Ÿงฉ Function DEFINES a function update_dict(d, key, value). Python only remembers it here - its body runs later, each time update_dict() is called.
2
if key in d:
๐Ÿ”€ Decision CHECKS whether key is present in d. If True, the indented lines below run; otherwise Python jumps to the elif/else part
3
d[key] = value
๐Ÿงฎ Store / Calculate Puts the value of value into d[key] (item key of d)
4
print("Updated successfully!")
๐Ÿ–ฅ๏ธ Output Displays the text "Updated successfully!" on the screen
5
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
6
print("Key not found, adding as new entry")
๐Ÿ–ฅ๏ธ Output Displays the text "Key not found, adding as new entry" on the screen
7
d[key] = value
๐Ÿงฎ Store / Calculate Puts the value of value into d[key] (item key of d)
8
return d
๐Ÿงฉ Function Sends back (returns) the value of d to the line that called the function
10
d = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable d
11
n = int(input("How many key-value pairs to enter? "))
โŒจ๏ธ Input Shows "How many key-value pairs to enter? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
12
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
13
k = input("Enter key: ")
โŒจ๏ธ Input Shows the message "Enter key: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable k
14
v = input("Enter value: ")
โŒจ๏ธ Input Shows the message "Enter value: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable v
15
d[k] = v
๐Ÿงฎ Store / Calculate Puts the value of v into d[k] (item k of d)
17
print("Dictionary:", d)
๐Ÿ–ฅ๏ธ Output Displays the text "Dictionary:", then the value of d on the screen
18
key = input("Enter key to update: ")
โŒจ๏ธ Input Shows the message "Enter key to update: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable key
19
value = input("Enter new value: ")
โŒจ๏ธ Input Shows the message "Enter new value: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable value
20
print("Result:", update_dict(d, key, value))
๐Ÿ–ฅ๏ธ Output Displays the text "Result:", then the value of update_dict(d, key, value) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def update_dict(d, key, value):
function is defined (remembered), not run yet
210
d = {}
d = {}
311
n = int(input("How many key-value pairs to enter? "))
n = 3
How many key-value pairs to enter? 3
412
for i in range(n):
next item taken
i = 0
513
k = input("Enter key: ")
k = '1'
Enter key: 1
614
v = input("Enter value: ")
v = 'Amit'
Enter value: Amit
715
d[k] = v
d = {'1': 'Amit'}
812
for i in range(n):
next item taken
i = 1
913
k = input("Enter key: ")
k = '2'
Enter key: 2
1014
v = input("Enter value: ")
v = 'Sara'
Enter value: Sara
1115
d[k] = v
d = {'1': 'Amit', '2': 'Sara'}
1212
for i in range(n):
next item taken
i = 2
1313
k = input("Enter key: ")
k = '3'
Enter key: 3
1414
v = input("Enter value: ")
v = 'Rahul'
Enter value: Rahul
1515
d[k] = v
d = {'1': 'Amit', '2': 'Sara', '3': 'Rahul'}
1612
for i in range(n):
no items left โ†’ loop ends
1717
print("Dictionary:", d)
Dictionary: {'1': 'Amit', '2': 'Sara', '3': 'Rahul'}
1818
key = input("Enter key to update: ")
key = '2'
Enter key to update: 2
1919
value = input("Enter new value: ")
value = 'Sara-Updated'
Enter new value: Sara-Updated
2020
print("Result:", update_dict(d, key, value))
d = {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'}
Result: {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'}
โžก Python jumps INTO function update_dict(d={'1': 'Amit', '2': 'Sara', '3': 'Rahul'}, key='2', value='Sara-Updated')
212
if key in d:
condition is TRUE โ†’ enters the block
223
d[key] = value
d = {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'}
234
print("Updated successfully!")
Updated successfully!
248
return d
โฌ… function update_dict() ends and returns {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'} to the caller
Q6 PYTHON

Pass a string to a function and count how many vowels are present in the string.

def count_vowels(s):
    count = 0
    for ch in s.lower():
        if ch in 'aeiou':
            count += 1
    return count

s = input("Enter a string: ")
print("Number of vowels =", count_vowels(s))
โ–ถ Sample Output
Enter a string: Educational Excellence
Number of vowels = 10
๐Ÿ’ก Explanation: Simple function encapsulation โ€” reusable vowel-counting logic.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ s
โžœ
โ‘ก PROCESSuses its own function count_vowels(); a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Educational Excellence (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def count_vowels(s):
๐Ÿงฉ Function DEFINES a function count_vowels(s). Python only remembers it here - its body runs later, each time count_vowels() is called.
2
count = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable count
3
for ch in s.lower():
๐Ÿ” Loop LOOP: takes each item of s.lower() one-by-one into ch and runs the indented block for it
4
if ch in 'aeiou':
๐Ÿ”€ Decision CHECKS whether ch is present in 'aeiou'. If True, the indented lines below run; otherwise they are skipped
5
count += 1
๐Ÿงฎ Store / Calculate Adds 1 to count (same as count = count + 1)
6
return count
๐Ÿงฉ Function Sends back (returns) the value of count to the line that called the function
8
s = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable s
9
print("Number of vowels =", count_vowels(s))
๐Ÿ–ฅ๏ธ Output Displays the text "Number of vowels =", then the value of count_vowels(s) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def count_vowels(s):
function is defined (remembered), not run yet
28
s = input("Enter a string: ")
s = 'Educational Excellence'
Enter a string: Educational Excellence
39
print("Number of vowels =", count_vowels(s))
Number of vowels = 10
โžก Python jumps INTO function count_vowels(s='Educational Excellence')
42
count = 0
count = 0
53
for ch in s.lower():
next item taken
ch = 'e'
64
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
75
count += 1
count = 1
83
for ch in s.lower():
next item taken
ch = 'd'
94
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
103
for ch in s.lower():
next item taken
ch = 'u'
114
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
125
count += 1
count = 2
133
for ch in s.lower():
next item taken
ch = 'c'
144
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
153
for ch in s.lower():
next item taken
ch = 'a'
164
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
175
count += 1
count = 3
183
for ch in s.lower():
next item taken
ch = 't'
194
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
203
for ch in s.lower():
next item taken
ch = 'i'
214
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
225
count += 1
count = 4
233
for ch in s.lower():
next item taken
ch = 'o'
244
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
255
count += 1
count = 5
263
for ch in s.lower():
next item taken
ch = 'n'
274
if ch in 'aeiou':
condition is FALSE โ†’ skips this block
283
for ch in s.lower():
next item taken
ch = 'a'
294
if ch in 'aeiou':
condition is TRUE โ†’ enters the block
305
count += 1
count = 6
313
for ch in s.lower():
next item taken
ch = 'l'

โ€ฆ Python runs 29 more line-steps in the same way (loops repeat the same lines). Final values: s = 'Educational Excellence', count = 10, ch = 'e'

Q7 PYTHON

Generate random numbers between 1 and 6 (simulate a dice) using a user-defined function.

import random

def roll_dice():
    return random.randint(1, 6)

n = int(input("How many times to roll the dice? "))
for i in range(n):
    print("Roll", i + 1, ":", roll_dice())
โ–ถ Sample Output
How many times to roll the dice? 3
Roll 1 : 1
Roll 2 : 3
Roll 3 : 5
๐Ÿ’ก Explanation: random.randint(1,6) gives a value in [1,6] inclusive โ€” exactly simulating a 6-face dice.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses its own function roll_dice(); a for loop; module random
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 3 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿงฉ Function๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import random
๐Ÿ“ฆ Library / Data Loads the module random - random number functions
3
def roll_dice():
๐Ÿงฉ Function DEFINES a function roll_dice(). Python only remembers it here - its body runs later, each time roll_dice() is called.
4
return random.randint(1, 6)
๐Ÿงฉ Function Sends back (returns) the result of: picks a random whole number from 1 to 6 (both included) to the line that called the function
6
n = int(input("How many times to roll the dice? "))
โŒจ๏ธ Input Shows "How many times to roll the dice? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
7
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
8
print("Roll", i + 1, ":", roll_dice())
๐Ÿ–ฅ๏ธ Output Displays the text "Roll", then the value of i + 1, then the text ":", then the value of roll_dice() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import random
23
def roll_dice():
function is defined (remembered), not run yet
36
n = int(input("How many times to roll the dice? "))
n = 3
How many times to roll the dice? 3
47
for i in range(n):
next item taken
i = 0
58
print("Roll", i + 1, ":", roll_dice())
Roll 1 : 1
โžก Python jumps INTO function roll_dice()
64
return random.randint(1, 6)
โฌ… function roll_dice() ends and returns 1 to the caller
77
for i in range(n):
next item taken
i = 1
88
print("Roll", i + 1, ":", roll_dice())
Roll 2 : 3
โžก Python jumps INTO function roll_dice()
94
return random.randint(1, 6)
โฌ… function roll_dice() ends and returns 3 to the caller
107
for i in range(n):
next item taken
i = 2
118
print("Roll", i + 1, ":", roll_dice())
Roll 3 : 5
โžก Python jumps INTO function roll_dice()
124
return random.randint(1, 6)
โฌ… function roll_dice() ends and returns 5 to the caller
137
for i in range(n):
no items left โ†’ loop ends
Q8 PYTHON

Menu driven python program to implement 10 python mathematical functions.

import math

def menu():
    print('''
1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit''')

while True:
    menu()
    ch = int(input("Enter choice: "))
    if ch == 0:
        break
    elif ch == 1:
        print(math.sqrt(float(input("Enter number: "))))
    elif ch == 2:
        b = float(input("Base: ")); p = float(input("Power: "))
        print(math.pow(b, p))
    elif ch == 3:
        print(math.factorial(int(input("Enter number: "))))
    elif ch == 4:
        print(math.ceil(float(input("Enter number: "))))
    elif ch == 5:
        print(math.floor(float(input("Enter number: "))))
    elif ch == 6:
        print(math.fabs(float(input("Enter number: "))))
    elif ch == 7:
        print(math.gcd(int(input("Num1: ")), int(input("Num2: "))))
    elif ch == 8:
        print(math.sin(float(input("Enter angle (radians): "))))
    elif ch == 9:
        print(math.log(float(input("Enter number: "))))
    elif ch == 10:
        print(math.exp(float(input("Enter number: "))))
    else:
        print("Invalid choice")
โ–ถ Sample Output
1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
Enter choice: 1
Enter number: 81
9.0

1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
Enter choice: 3
Enter number: 5
120

1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
Enter choice: 7
Num1: 36
Num2: 48
12

1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
Enter choice: 0
๐Ÿ’ก Explanation: A while True loop with break gives a repeating menu โ€” the standard structure for all 'menu driven' CBSE questions.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ ch, b, p
โžœ
โ‘ก PROCESSuses its own function menu(); a while loop; decisions with if / elif / else; module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 81, 3, 5, 7, 36, 48, 0 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
3
def menu():
๐Ÿงฉ Function DEFINES a function menu(). Python only remembers it here - its body runs later, each time menu() is called.
4
print('''
quare Root   2. Power        3. Factorial
eil          5. Floor        6. Absolute
CD           8. Sin          9. Log
Exp          0. Exit''')
๐Ÿ–ฅ๏ธ Output Displays the text "1. Square Root 2. Power 3. Factorโ€ฆ" on the screen
10
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
11
menu()
๐Ÿงฎ Store / Calculate Calls our own function menu()
12
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
13
if ch == 0:
๐Ÿ”€ Decision CHECKS whether ch is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
14
break
๐Ÿ” Loop BREAK - leaves the loop immediately
15
elif ch == 1:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 1
16
print(math.sqrt(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.sqrt(float(input("Enter number: "))) on the screen
17
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
18
b = float(input("Base: ")); p = float(input("Power: "))
โŒจ๏ธ Input Shows "Base: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable b
18
b = float(input("Base: ")); p = float(input("Power: "))
โŒจ๏ธ Input Shows "Power: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable p
19
print(math.pow(b, p))
๐Ÿ–ฅ๏ธ Output Displays the value of math.pow(b, p) on the screen
20
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
21
print(math.factorial(int(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.factorial(int(input("Enter number: "))) on the screen
22
elif ch == 4:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 4
23
print(math.ceil(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.ceil(float(input("Enter number: "))) on the screen
24
elif ch == 5:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 5
25
print(math.floor(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.floor(float(input("Enter number: "))) on the screen
26
elif ch == 6:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 6
27
print(math.fabs(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.fabs(float(input("Enter number: "))) on the screen
28
elif ch == 7:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 7
29
print(math.gcd(int(input("Num1: ")), int(input("Num2: "))))
โŒจ๏ธ Input Displays the value of math.gcd(int(input("Num1: ")), int(input("Numโ€ฆ on the screen
30
elif ch == 8:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 8
31
print(math.sin(float(input("Enter angle (radians): "))))
โŒจ๏ธ Input Displays the value of math.sin(float(input("Enter angle (radians): โ€ฆ on the screen
32
elif ch == 9:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 9
33
print(math.log(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.log(float(input("Enter number: "))) on the screen
34
elif ch == 10:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 10
35
print(math.exp(float(input("Enter number: "))))
โŒจ๏ธ Input Displays the value of math.exp(float(input("Enter number: "))) on the screen
36
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
37
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import math
23
def menu():
function is defined (remembered), not run yet
310
while True:
condition is TRUE โ†’ enters the block
411
menu()
โžก Python jumps INTO function menu()
54
print('''
1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
โฌ… function menu() ends and returns None to the caller
612
ch = int(input("Enter choice: "))
ch = 1
Enter choice: 1
713
if ch == 0:
condition is FALSE โ†’ skips this block
815
elif ch == 1:
condition is TRUE โ†’ enters the block
916
print(math.sqrt(float(input("Enter number: "))))
Enter number: 81
9.0
1010
while True:
condition is TRUE โ†’ enters the block
1111
menu()
โžก Python jumps INTO function menu()
124
print('''
1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
โฌ… function menu() ends and returns None to the caller
1312
ch = int(input("Enter choice: "))
ch = 3
Enter choice: 3
1413
if ch == 0:
condition is FALSE โ†’ skips this block
1515
elif ch == 1:
condition is FALSE โ†’ skips this block
1617
elif ch == 2:
condition is FALSE โ†’ skips this block
1720
elif ch == 3:
condition is TRUE โ†’ enters the block
1821
print(math.factorial(int(input("Enter number: "))))
Enter number: 5
120
1910
while True:
condition is TRUE โ†’ enters the block
2011
menu()
โžก Python jumps INTO function menu()
214
print('''
1. Square Root   2. Power        3. Factorial
4. Ceil          5. Floor        6. Absolute
7. GCD           8. Sin          9. Log
10. Exp          0. Exit
โฌ… function menu() ends and returns None to the caller
2212
ch = int(input("Enter choice: "))
ch = 7
Enter choice: 7
2313
if ch == 0:
condition is FALSE โ†’ skips this block
2415
elif ch == 1:
condition is FALSE โ†’ skips this block
2517
elif ch == 2:
condition is FALSE โ†’ skips this block
2620
elif ch == 3:
condition is FALSE โ†’ skips this block

โ€ฆ Python runs 11 more line-steps in the same way (loops repeat the same lines). Final values: ch = 0

Q9 PYTHON

Implement Python string functions (all listed in Sumita Arora book).

s = "Hello Python Programming"

print("Original    :", s)
print("upper()     :", s.upper())
print("lower()     :", s.lower())
print("len()       :", len(s))
print("find('Py')  :", s.find("Py"))
print("count('m')  :", s.count("m"))
print("replace()   :", s.replace("Python", "World"))
print("split()     :", s.split())
print("strip()     :", "  spaced  ".strip())
print("capitalize():", s.capitalize())
print("title()     :", s.title())
print("isalpha()   :", "Hello".isalpha())
print("isdigit()   :", "123".isdigit())
print("startswith():", s.startswith("Hello"))
print("endswith()  :", s.endswith("ing"))
print("index()     :", s.index("Python"))
print("swapcase()  :", s.swapcase())
print("join()      :", "-".join(["a", "b", "c"]))
print("partition() :", s.partition("Python"))
print("slicing s[0:5]:", s[0:5])
โ–ถ Sample Output
Original    : Hello Python Programming
upper()     : HELLO PYTHON PROGRAMMING
lower()     : hello python programming
len()       : 24
find('Py')  : 6
count('m')  : 2
replace()   : Hello World Programming
split()     : ['Hello', 'Python', 'Programming']
strip()     : spaced
capitalize(): Hello python programming
title()     : Hello Python Programming
isalpha()   : True
isdigit()   : True
startswith(): True
endswith()  : True
index()     : 6
swapcase()  : hELLO pYTHON pROGRAMMING
join()      : a-b-c
partition() : ('Hello ', 'Python', ' Programming')
slicing s[0:5]: Hello
๐Ÿ’ก Explanation: Covers the most commonly-asked string methods in the CBSE syllabus โ€” practise each individually too.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate
LineCodeWhat it does
1
s = "Hello Python Programming"
๐Ÿงฎ Store / Calculate Stores the text "Hello Python Programming" in variable s
3
print("Original    :", s)
๐Ÿ–ฅ๏ธ Output Displays the text "Original :", then the value of s on the screen
4
print("upper()     :", s.upper())
๐Ÿ–ฅ๏ธ Output Displays the text "upper() :", then the value of s.upper() on the screen
5
print("lower()     :", s.lower())
๐Ÿ–ฅ๏ธ Output Displays the text "lower() :", then the value of s.lower() on the screen
6
print("len()       :", len(s))
๐Ÿ–ฅ๏ธ Output Displays the text "len() :", then the value of len(s) on the screen
7
print("find('Py')  :", s.find("Py"))
๐Ÿ–ฅ๏ธ Output Displays the text "find('Py') :", then the value of s.find("Py") on the screen
8
print("count('m')  :", s.count("m"))
๐Ÿ–ฅ๏ธ Output Displays the text "count('m') :", then the value of s.count("m") on the screen
9
print("replace()   :", s.replace("Python", "World"))
๐Ÿ–ฅ๏ธ Output Displays the text "replace() :", then the value of s.replace("Python", "World") on the screen
10
print("split()     :", s.split())
๐Ÿ–ฅ๏ธ Output Displays the text "split() :", then the value of s.split() on the screen
11
print("strip()     :", "  spaced  ".strip())
๐Ÿ–ฅ๏ธ Output Displays the text "strip() :", then the value of " spaced ".strip() on the screen
12
print("capitalize():", s.capitalize())
๐Ÿ–ฅ๏ธ Output Displays the text "capitalize():", then the value of s.capitalize() on the screen
13
print("title()     :", s.title())
๐Ÿ–ฅ๏ธ Output Displays the text "title() :", then the value of s.title() on the screen
14
print("isalpha()   :", "Hello".isalpha())
๐Ÿ–ฅ๏ธ Output Displays the text "isalpha() :", then the value of "Hello".isalpha() on the screen
15
print("isdigit()   :", "123".isdigit())
๐Ÿ–ฅ๏ธ Output Displays the text "isdigit() :", then the value of "123".isdigit() on the screen
16
print("startswith():", s.startswith("Hello"))
๐Ÿ–ฅ๏ธ Output Displays the text "startswith():", then the value of s.startswith("Hello") on the screen
17
print("endswith()  :", s.endswith("ing"))
๐Ÿ–ฅ๏ธ Output Displays the text "endswith() :", then the value of s.endswith("ing") on the screen
18
print("index()     :", s.index("Python"))
๐Ÿ–ฅ๏ธ Output Displays the text "index() :", then the value of s.index("Python") on the screen
19
print("swapcase()  :", s.swapcase())
๐Ÿ–ฅ๏ธ Output Displays the text "swapcase() :", then the value of s.swapcase() on the screen
20
print("join()      :", "-".join(["a", "b", "c"]))
๐Ÿ–ฅ๏ธ Output Displays the text "join() :", then the value of "-".join(["a", "b", "c"]) on the screen
21
print("partition() :", s.partition("Python"))
๐Ÿ–ฅ๏ธ Output Displays the text "partition() :", then the value of s.partition("Python") on the screen
22
print("slicing s[0:5]:", s[0:5])
๐Ÿ–ฅ๏ธ Output Displays the text "slicing s[0:5]:", then the value of s[0:5] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
s = "Hello Python Programming"
s = 'Hello Python Programming'
23
print("Original    :", s)
Original    : Hello Python Programming
34
print("upper()     :", s.upper())
upper()     : HELLO PYTHON PROGRAMMING
45
print("lower()     :", s.lower())
lower()     : hello python programming
56
print("len()       :", len(s))
len()       : 24
67
print("find('Py')  :", s.find("Py"))
find('Py')  : 6
78
print("count('m')  :", s.count("m"))
count('m')  : 2
89
print("replace()   :", s.replace("Python", "World"))
replace()   : Hello World Programming
910
print("split()     :", s.split())
split()     : ['Hello', 'Python', 'Programming']
1011
print("strip()     :", "  spaced  ".strip())
strip()     : spaced
1112
print("capitalize():", s.capitalize())
capitalize(): Hello python programming
1213
print("title()     :", s.title())
title()     : Hello Python Programming
1314
print("isalpha()   :", "Hello".isalpha())
isalpha()   : True
1415
print("isdigit()   :", "123".isdigit())
isdigit()   : True
1516
print("startswith():", s.startswith("Hello"))
startswith(): True
1617
print("endswith()  :", s.endswith("ing"))
endswith()  : True
1718
print("index()     :", s.index("Python"))
index()     : 6
1819
print("swapcase()  :", s.swapcase())
swapcase()  : hELLO pYTHON pROGRAMMING
1920
print("join()      :", "-".join(["a", "b", "c"]))
join()      : a-b-c
2021
print("partition() :", s.partition("Python"))
partition() : ('Hello ', 'Python', ' Programming')
2122
print("slicing s[0:5]:", s[0:5])
slicing s[0:5]: Hello
Q10 PYTHON

Menu driven program to delete a student's name from a dictionary and search phone number by student name.

students = {"Amit": "9876543210", "Sara": "9123456780", "Rahul": "9988776655"}

while True:
    print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
    ch = int(input("Enter choice: "))
    if ch == 1:
        name = input("Enter name to delete: ")
        if name in students:
            del students[name]
            print("Deleted successfully")
        else:
            print("Name not found")
    elif ch == 2:
        name = input("Enter name to search: ")
        if name in students:
            print("Phone number:", students[name])
        else:
            print("Name not found")
    elif ch == 3:
        break
    else:
        print("Invalid choice")
โ–ถ Sample Output
MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
Enter choice: 2
Enter name to search: Sara
Phone number: 9123456780

MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
Enter choice: 1
Enter name to delete: Rahul
Deleted successfully

MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
Enter choice: 2
Enter name to search: Rahul
Name not found

MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
Enter choice: 3
๐Ÿ’ก Explanation: Exact menu structure specified in the question โ€” always match the menu wording given in the practical list.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ ch, name
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2, Sara, 1, Rahul, 2, Rahul, 3 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop
LineCodeWhat it does
1
students = {"Amit": "9876543210", "Sara": "9123456780", "Rahul": "9988776655"}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Amit": "9876543210", "Sara": "9123456780", โ€ฆ in variable students
3
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
4
print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "MENU 1. Delete from Dictionary 2.โ€ฆ" on the screen
5
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
6
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
name = input("Enter name to delete: ")
โŒจ๏ธ Input Shows the message "Enter name to delete: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
8
if name in students:
๐Ÿ”€ Decision CHECKS whether name is present in students. If True, the indented lines below run; otherwise Python jumps to the elif/else part
9
del students[name]
๐Ÿงฎ Store / Calculate Deletes students[name]
10
print("Deleted successfully")
๐Ÿ–ฅ๏ธ Output Displays the text "Deleted successfully" on the screen
11
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
12
print("Name not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Name not found" on the screen
13
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
14
name = input("Enter name to search: ")
โŒจ๏ธ Input Shows the message "Enter name to search: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
15
if name in students:
๐Ÿ”€ Decision CHECKS whether name is present in students. If True, the indented lines below run; otherwise Python jumps to the elif/else part
16
print("Phone number:", students[name])
๐Ÿ–ฅ๏ธ Output Displays the text "Phone number:", then the value of students[name] on the screen
17
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
18
print("Name not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Name not found" on the screen
19
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
20
break
๐Ÿ” Loop BREAK - leaves the loop immediately
21
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
22
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
students = {"Amit": "9876543210", "Sara": "9123456780", "Rahul": "9988776655"}
students = {'Amit': '9876543210', 'Sara': '9123456780', 'Rahul': '9988776655'}
23
while True:
condition is TRUE โ†’ enters the block
34
print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
45
ch = int(input("Enter choice: "))
ch = 2
Enter choice: 2
56
if ch == 1:
condition is FALSE โ†’ skips this block
613
elif ch == 2:
condition is TRUE โ†’ enters the block
714
name = input("Enter name to search: ")
name = 'Sara'
Enter name to search: Sara
815
if name in students:
condition is TRUE โ†’ enters the block
916
print("Phone number:", students[name])
Phone number: 9123456780
103
while True:
condition is TRUE โ†’ enters the block
114
print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
125
ch = int(input("Enter choice: "))
ch = 1
Enter choice: 1
136
if ch == 1:
condition is TRUE โ†’ enters the block
147
name = input("Enter name to delete: ")
name = 'Rahul'
Enter name to delete: Rahul
158
if name in students:
condition is TRUE โ†’ enters the block
169
del students[name]
students = {'Amit': '9876543210', 'Sara': '9123456780'}
1710
print("Deleted successfully")
Deleted successfully
183
while True:
condition is TRUE โ†’ enters the block
194
print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
205
ch = int(input("Enter choice: "))
ch = 2
Enter choice: 2
216
if ch == 1:
condition is FALSE โ†’ skips this block
2213
elif ch == 2:
condition is TRUE โ†’ enters the block
2314
name = input("Enter name to search: ")
Enter name to search: Rahul
2415
if name in students:
condition is FALSE โ†’ skips this block
2518
print("Name not found")
Name not found
263
while True:
condition is TRUE โ†’ enters the block
274
print("\nMENU\n1. Delete from Dictionary\n2. Search Phone number using name\n3. Exit")
MENU
1. Delete from Dictionary
2. Search Phone number using name
3. Exit
285
ch = int(input("Enter choice: "))
ch = 3
Enter choice: 3
296
if ch == 1:
condition is FALSE โ†’ skips this block
3013
elif ch == 2:
condition is FALSE โ†’ skips this block
3119
elif ch == 3:
condition is TRUE โ†’ enters the block
3220
break
Q11 PYTHON

Read and display file content line by line with each word separated by #.

with open("data.txt", "w") as f:
    f.write("This is line one\nThis is line two\nPython file handling")

with open("data.txt", "r") as f:
    for line in f:
        words = line.split()
        print("#".join(words))
โ–ถ Sample Output
This#is#line#one
This#is#line#two
Python#file#handling
๐Ÿ’ก Explanation: 'with open()' auto-closes the file. Splitting each line into words and joining with '#' meets the exact requirement.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; file handling (open โ†’ read/write โ†’ close)
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ File
LineCodeWhat it does
1
with open("data.txt", "w") as f:
๐Ÿ“ File Opens the file "data.txt" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
2
f.write("This is line one\nThis is line two\nPython file handling")
๐Ÿ“ File Writes "This is line one\nThis is line two\nPython fโ€ฆ into file f
4
with open("data.txt", "r") as f:
๐Ÿ“ File Opens the file "data.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
5
for line in f:
๐Ÿ” Loop LOOP that reads the file f one line at a time; line holds the current line
6
words = line.split()
๐Ÿงฎ Store / Calculate Breaks line into a list of words (at spaces); the result is stored in variable words
7
print("#".join(words))
๐Ÿ–ฅ๏ธ Output Displays the value of "#".join(words) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
with open("data.txt", "w") as f:
f = file object "data.txt" (mode w)
22
f.write("This is line one\nThis is line two\nPython file handling")
31
with open("data.txt", "w") as f:
block over โ†’ file closed automatically
44
with open("data.txt", "r") as f:
f = file object "data.txt" (mode r)
55
for line in f:
next item taken
line = 'This is line one\n'
66
words = line.split()
words = ['This', 'is', 'line', 'one']
77
print("#".join(words))
This#is#line#one
85
for line in f:
next item taken
line = 'This is line two\n'
96
words = line.split()
words = ['This', 'is', 'line', 'two']
107
print("#".join(words))
This#is#line#two
115
for line in f:
next item taken
line = 'Python file handling'
126
words = line.split()
words = ['Python', 'file', 'handling']
137
print("#".join(words))
Python#file#handling
145
for line in f:
no items left โ†’ loop ends
154
with open("data.txt", "r") as f:
block over โ†’ file closed automatically
Q12 PYTHON

Read a text file and display the number of vowels, consonants, uppercase, lowercase characters in the file.

with open("data.txt", "r") as f:
    content = f.read()

vowels = consonants = upper = lower = 0
for ch in content:
    if ch.isalpha():
        if ch.lower() in 'aeiou':
            vowels += 1
        else:
            consonants += 1
        if ch.isupper():
            upper += 1
        else:
            lower += 1

print("Vowels     :", vowels)
print("Consonants :", consonants)
print("Uppercase  :", upper)
print("Lowercase  :", lower)
โ–ถ Sample Output
Vowels     : 16
Consonants : 28
Uppercase  : 3
Lowercase  : 41
๐Ÿ’ก Explanation: read() loads the entire file as one string; then we iterate character by character exactly like the string-based version.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else; file handling (open โ†’ read/write โ†’ close)
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File
LineCodeWhat it does
1
with open("data.txt", "r") as f:
๐Ÿ“ File Opens the file "data.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
2
content = f.read()
๐Ÿ“ File Reads the whole content of file f as one string; the result is stored in variable content
4
vowels = consonants = upper = lower = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable vowels
5
for ch in content:
๐Ÿ” Loop LOOP: takes each item of content one-by-one into ch and runs the indented block for it
6
if ch.isalpha():
๐Ÿ”€ Decision CHECKS whether ch.isalpha() is True. If True, the indented lines below run; otherwise they are skipped
7
if ch.lower() in 'aeiou':
๐Ÿ”€ Decision CHECKS whether ch.lower() is present in 'aeiou'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
8
vowels += 1
๐Ÿงฎ Store / Calculate Adds 1 to vowels (same as vowels = vowels + 1)
9
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
10
consonants += 1
๐Ÿงฎ Store / Calculate Adds 1 to consonants (same as consonants = consonants + 1)
11
if ch.isupper():
๐Ÿ”€ Decision CHECKS whether ch.isupper() is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
12
upper += 1
๐Ÿงฎ Store / Calculate Adds 1 to upper (same as upper = upper + 1)
13
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
14
lower += 1
๐Ÿงฎ Store / Calculate Adds 1 to lower (same as lower = lower + 1)
16
print("Vowels     :", vowels)
๐Ÿ–ฅ๏ธ Output Displays the text "Vowels :", then the value of vowels on the screen
17
print("Consonants :", consonants)
๐Ÿ–ฅ๏ธ Output Displays the text "Consonants :", then the value of consonants on the screen
18
print("Uppercase  :", upper)
๐Ÿ–ฅ๏ธ Output Displays the text "Uppercase :", then the value of upper on the screen
19
print("Lowercase  :", lower)
๐Ÿ–ฅ๏ธ Output Displays the text "Lowercase :", then the value of lower on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
with open("data.txt", "r") as f:
f = file object "data.txt" (mode r)
22
content = f.read()
content = 'This is line one\nThis is line two\nPython file handling'
31
with open("data.txt", "r") as f:
block over โ†’ file closed automatically
44
vowels = consonants = upper = lower = 0
vowels = 0, consonants = 0, upper = 0, lower = 0
55
for ch in content:
next item taken
ch = 'T'
66
if ch.isalpha():
condition is TRUE โ†’ enters the block
77
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
810
consonants += 1
consonants = 1
911
if ch.isupper():
condition is TRUE โ†’ enters the block
1012
upper += 1
upper = 1
115
for ch in content:
next item taken
ch = 'h'
126
if ch.isalpha():
condition is TRUE โ†’ enters the block
137
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
1410
consonants += 1
consonants = 2
1511
if ch.isupper():
condition is FALSE โ†’ skips this block
1614
lower += 1
lower = 1
175
for ch in content:
next item taken
ch = 'i'
186
if ch.isalpha():
condition is TRUE โ†’ enters the block
197
if ch.lower() in 'aeiou':
condition is TRUE โ†’ enters the block
208
vowels += 1
vowels = 1
2111
if ch.isupper():
condition is FALSE โ†’ skips this block
2214
lower += 1
lower = 2
235
for ch in content:
next item taken
ch = 's'
246
if ch.isalpha():
condition is TRUE โ†’ enters the block
257
if ch.lower() in 'aeiou':
condition is FALSE โ†’ skips this block
2610
consonants += 1
consonants = 3
2711
if ch.isupper():
condition is FALSE โ†’ skips this block
2814
lower += 1
lower = 3
295
for ch in content:
next item taken
ch = ' '
306
if ch.isalpha():
condition is FALSE โ†’ skips this block
315
for ch in content:
next item taken
ch = 'i'
326
if ch.isalpha():
condition is TRUE โ†’ enters the block

โ€ฆ Python runs 261 more line-steps in the same way (loops repeat the same lines). Final values: f = file object "data.txt" (mode r), content = 'This is line one\nThis is line two\nPython file handling', vowels = 16, consonants = 28, upper = 3, lower = 41, ch = 'g'

Q13 PYTHON

Menu driven program to count spaces, digits, words and lines from text file TOY.txt.

with open("TOY.txt", "w") as f:
    f.write("Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam")

while True:
    print("\nMENU\n1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit")
    ch = int(input("Enter choice: "))
    if ch == 5:
        break
    with open("TOY.txt", "r") as f:
        content = f.read()
    if ch == 1:
        print("Spaces:", content.count(" "))
    elif ch == 2:
        print("Digits:", sum(1 for c in content if c.isdigit()))
    elif ch == 3:
        print("Words:", len(content.split()))
    elif ch == 4:
        print("Lines:", len(content.splitlines()))
    else:
        print("Invalid choice")
โ–ถ Sample Output
MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
Enter choice: 1
Spaces: 6

MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
Enter choice: 2
Digits: 10

MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
Enter choice: 3
Words: 9

MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
Enter choice: 4
Lines: 3

MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
Enter choice: 5
๐Ÿ’ก Explanation: splitlines() correctly counts lines even without a trailing newline character.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ ch
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else; file handling (open โ†’ read/write โ†’ close)
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 2, 3, 4, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File
LineCodeWhat it does
1
with open("TOY.txt", "w") as f:
๐Ÿ“ File Opens the file "TOY.txt" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
2
f.write("Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam")
๐Ÿ“ File Writes "Hello 123 World\nPython 456 Programming\nCBSโ€ฆ into file f
4
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
5
print("\nMENU\n1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "MENU 1.Count Spaces 2.Count Digitโ€ฆ" on the screen
6
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
7
if ch == 5:
๐Ÿ”€ Decision CHECKS whether ch is equal to 5. If True, the indented lines below run; otherwise they are skipped
8
break
๐Ÿ” Loop BREAK - leaves the loop immediately
9
with open("TOY.txt", "r") as f:
๐Ÿ“ File Opens the file "TOY.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
10
content = f.read()
๐Ÿ“ File Reads the whole content of file f as one string; the result is stored in variable content
11
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
12
print("Spaces:", content.count(" "))
๐Ÿ–ฅ๏ธ Output Displays the text "Spaces:", then the value of content.count(" ") on the screen
13
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
14
print("Digits:", sum(1 for c in content if c.isdigit()))
๐Ÿ–ฅ๏ธ Output Displays the text "Digits:", then the value of sum(1 for c in content if c.isdigit()) on the screen
15
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
16
print("Words:", len(content.split()))
๐Ÿ–ฅ๏ธ Output Displays the text "Words:", then the value of len(content.split()) on the screen
17
elif ch == 4:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 4
18
print("Lines:", len(content.splitlines()))
๐Ÿ–ฅ๏ธ Output Displays the text "Lines:", then the value of len(content.splitlines()) on the screen
19
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
20
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
with open("TOY.txt", "w") as f:
f = file object "TOY.txt" (mode w)
22
f.write("Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam")
31
with open("TOY.txt", "w") as f:
block over โ†’ file closed automatically
44
while True:
condition is TRUE โ†’ enters the block
55
print("\nMENU\n1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit")
MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
66
ch = int(input("Enter choice: "))
ch = 1
Enter choice: 1
77
if ch == 5:
condition is FALSE โ†’ skips this block
89
with open("TOY.txt", "r") as f:
f = file object "TOY.txt" (mode r)
910
content = f.read()
content = 'Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam'
109
with open("TOY.txt", "r") as f:
block over โ†’ file closed automatically
1111
if ch == 1:
condition is TRUE โ†’ enters the block
1212
print("Spaces:", content.count(" "))
Spaces: 6
134
while True:
condition is TRUE โ†’ enters the block
145
print("\nMENU\n1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit")
MENU
1.Count Spaces  2.Count Digits  3.Count Words  4.Count Lines  5.Exit
156
ch = int(input("Enter choice: "))
ch = 2
Enter choice: 2
167
if ch == 5:
condition is FALSE โ†’ skips this block
179
with open("TOY.txt", "r") as f:
1810
content = f.read()
199
with open("TOY.txt", "r") as f:
block over โ†’ file closed automatically
2011
if ch == 1:
condition is FALSE โ†’ skips this block
2113
elif ch == 2:
condition is TRUE โ†’ enters the block
2214
print("Digits:", sum(1 for c in content if c.isdigit()))
Digits: 10
โžก Python jumps INTO function <genexpr>(.0=<str_ascii_iterator object at 0x7faa9fa9d5a0>)
2314
print("Digits:", sum(1 for c in content if c.isdigit()))
c = 'H'
2414
print("Digits:", sum(1 for c in content if c.isdigit()))
c = 'e'
2514
print("Digits:", sum(1 for c in content if c.isdigit()))
c = 'l'
2614
print("Digits:", sum(1 for c in content if c.isdigit()))
2714
print("Digits:", sum(1 for c in content if c.isdigit()))
c = 'o'
2814
print("Digits:", sum(1 for c in content if c.isdigit()))
c = ' '
2914
print("Digits:", sum(1 for c in content if c.isdigit()))
c = '1'
โฌ… function <genexpr>() ends and returns 1 to the caller
โžก Python jumps INTO function <genexpr>(.0=<str_ascii_iterator object at 0x7faa9fa9d5a0>)

โ€ฆ Python runs 75 more line-steps in the same way (loops repeat the same lines). Final values: f = file object "TOY.txt" (mode r), ch = 5, content = 'Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam', c = 'm'

Q14 PYTHON

Remove all lines that contain the character 'a' in a file and write remaining lines to another file.

with open("source.txt", "w") as f:
    f.write("apple is red\nkvs school\ntoday is monday\nno match here")

with open("source.txt", "r") as fin, open("filtered.txt", "w") as fout:
    for line in fin:
        if 'a' not in line:
            fout.write(line)

print("Lines without 'a' written to filtered.txt")
with open("filtered.txt", "r") as f:
    print(f.read())
โ–ถ Sample Output
Lines without 'a' written to filtered.txt
kvs school
๐Ÿ’ก Explanation: Two files open simultaneously โ€” read source, conditionally write matching lines to a new destination file.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; file handling (open โ†’ read/write โ†’ close); decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File
LineCodeWhat it does
1
with open("source.txt", "w") as f:
๐Ÿ“ File Opens the file "source.txt" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
2
f.write("apple is red\nkvs school\ntoday is monday\nno match here")
๐Ÿ“ File Writes "apple is red\nkvs school\ntoday is monday\nnโ€ฆ into file f
4
with open("source.txt", "r") as fin, open("filtered.txt", "w") as fout:
๐Ÿ“ File Opens the file "source.txt" in "r" mode - read and calls it fin. "with" closes the file automatically when the block ends
5
for line in fin:
๐Ÿ” Loop LOOP that reads the file fin one line at a time; line holds the current line
6
if 'a' not in line:
๐Ÿ”€ Decision CHECKS whether 'a' is not present in line. If True, the indented lines below run; otherwise they are skipped
7
fout.write(line)
๐Ÿ“ File Writes line into file fout
9
print("Lines without 'a' written to filtered.txt")
๐Ÿ–ฅ๏ธ Output Displays the text "Lines without 'a' written to filtโ€ฆ" on the screen
10
with open("filtered.txt", "r") as f:
๐Ÿ“ File Opens the file "filtered.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
11
print(f.read())
๐Ÿ“ File Displays the value of f.read() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
with open("source.txt", "w") as f:
f = file object "source.txt" (mode w)
22
f.write("apple is red\nkvs school\ntoday is monday\nno match here")
31
with open("source.txt", "w") as f:
block over โ†’ file closed automatically
44
with open("source.txt", "r") as fin, open("filtered.txt", "w") as fout:
fin = file object "source.txt" (mode r), fout = file object "filtered.txt" (mode w)
55
for line in fin:
next item taken
line = 'apple is red\n'
66
if 'a' not in line:
condition is FALSE โ†’ skips this block
75
for line in fin:
next item taken
line = 'kvs school\n'
86
if 'a' not in line:
condition is TRUE โ†’ enters the block
97
fout.write(line)
105
for line in fin:
next item taken
line = 'today is monday\n'
116
if 'a' not in line:
condition is FALSE โ†’ skips this block
125
for line in fin:
next item taken
line = 'no match here'
136
if 'a' not in line:
condition is FALSE โ†’ skips this block
145
for line in fin:
no items left โ†’ loop ends
154
with open("source.txt", "r") as fin, open("filtered.txt", "w") as fout:
block over โ†’ file closed automatically
169
print("Lines without 'a' written to filtered.txt")
Lines without 'a' written to filtered.txt
1710
with open("filtered.txt", "r") as f:
f = file object "filtered.txt" (mode r)
1811
print(f.read())
kvs school
1910
with open("filtered.txt", "r") as f:
block over โ†’ file closed automatically
Q15 PYTHON

Create a binary file with name and roll number; search for a given roll number and display name.

import pickle

with open("student.dat", "wb") as f:
    records = [(1, "Amit"), (2, "Sara"), (3, "Rahul")]
    for rec in records:
        pickle.dump(rec, f)

roll = int(input("Enter roll number to search: "))
found = False
with open("student.dat", "rb") as f:
    while True:
        try:
            rec = pickle.load(f)
            if rec[0] == roll:
                print("Name:", rec[1])
                found = True
                break
        except EOFError:
            break

if not found:
    print("Roll number not found")
โ–ถ Sample Output
Enter roll number to search: 2
Name: Sara
๐Ÿ’ก Explanation: pickle.dump()/load() serialize Python objects to/from a binary file; EOFError signals end-of-file while reading.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ roll
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; a for loop; a while loop; file handling (open โ†’ read/write โ†’ close); try / except to handle errors; module pickle
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 2 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File๐Ÿ“ฆ Library / Data๐Ÿ›ก๏ธ Error handling
LineCodeWhat it does
1
import pickle
๐Ÿ“ฆ Library / Data Loads the module pickle - writing / reading Python objects in binary files
3
with open("student.dat", "wb") as f:
๐Ÿ“ File Opens the file "student.dat" in "wb" mode - write in binary (old content is erased) and calls it f. "with" closes the file automatically when the block ends
4
records = [(1, "Amit"), (2, "Sara"), (3, "Rahul")]
๐Ÿงฎ Store / Calculate Stores a list [(1, "Amit"), (2, "Sara"), (3, "Rahul")] in variable records
5
for rec in records:
๐Ÿ” Loop LOOP: takes each item of records one-by-one into rec and runs the indented block for it
6
pickle.dump(rec, f)
๐Ÿ“ File Writes (pickles) rec into the binary file f
8
roll = int(input("Enter roll number to search: "))
โŒจ๏ธ Input Shows "Enter roll number to search: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
9
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
10
with open("student.dat", "rb") as f:
๐Ÿ“ File Opens the file "student.dat" in "rb" mode - read in binary and calls it f. "with" closes the file automatically when the block ends
11
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
12
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
13
rec = pickle.load(f)
๐Ÿ“ File Reads (un-pickles) the next object from the binary file f; the result is stored in variable rec
14
if rec[0] == roll:
๐Ÿ”€ Decision CHECKS whether rec[0] is equal to roll. If True, the indented lines below run; otherwise they are skipped
15
print("Name:", rec[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Name:", then the value of rec[1] on the screen
16
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
17
break
๐Ÿ” Loop BREAK - leaves the loop immediately
18
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
19
break
๐Ÿ” Loop BREAK - leaves the loop immediately
21
if not found:
๐Ÿ”€ Decision CHECKS whether found is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
22
print("Roll number not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Roll number not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pickle
23
with open("student.dat", "wb") as f:
f = file object "student.dat" (mode wb)
34
records = [(1, "Amit"), (2, "Sara"), (3, "Rahul")]
records = [(1, 'Amit'), (2, 'Sara'), (3, 'Rahul')]
45
for rec in records:
next item taken
rec = (1, 'Amit')
56
pickle.dump(rec, f)
65
for rec in records:
next item taken
rec = (2, 'Sara')
76
pickle.dump(rec, f)
85
for rec in records:
next item taken
rec = (3, 'Rahul')
96
pickle.dump(rec, f)
105
for rec in records:
no items left โ†’ loop ends
113
with open("student.dat", "wb") as f:
block over โ†’ file closed automatically
128
roll = int(input("Enter roll number to search: "))
roll = 2
Enter roll number to search: 2
139
found = False
found = False
1410
with open("student.dat", "rb") as f:
f = file object "student.dat" (mode rb)
1511
while True:
condition is TRUE โ†’ enters the block
1612
try:
1713
rec = pickle.load(f)
rec = (1, 'Amit')
1814
if rec[0] == roll:
condition is FALSE โ†’ skips this block
1911
while True:
condition is TRUE โ†’ enters the block
2012
try:
2113
rec = pickle.load(f)
rec = (2, 'Sara')
2214
if rec[0] == roll:
condition is TRUE โ†’ enters the block
2315
print("Name:", rec[1])
Name: Sara
2416
found = True
found = True
2517
break
2610
with open("student.dat", "rb") as f:
block over โ†’ file closed automatically
2721
if not found:
condition is FALSE โ†’ skips this block
Q16 PYTHON

Create a dictionary with roll number, name and marks; accept 5 records and write them into a binary file.

import pickle

with open("marks.dat", "wb") as f:
    for i in range(5):
        roll = int(input("Roll number: "))
        name = input("Name: ")
        marks = float(input("Marks: "))
        student = {roll: (name, marks)}
        pickle.dump(student, f)

print("\nRecords stored. Reading back:")
with open("marks.dat", "rb") as f:
    while True:
        try:
            print(pickle.load(f))
        except EOFError:
            break
โ–ถ Sample Output
Roll number: 1
Name: Asmita
Marks: 89.7
Roll number: 2
Name: Swati
Marks: 87.5
Roll number: 3
Name: Rohan
Marks: 76
Roll number: 4
Name: Kavya
Marks: 92.5
Roll number: 5
Name: Arjun
Marks: 68

Records stored. Reading back:
{1: ('Asmita', 89.7)}
{2: ('Swati', 87.5)}
{3: ('Rohan', 76.0)}
{4: ('Kavya', 92.5)}
{5: ('Arjun', 68.0)}
๐Ÿ’ก Explanation: The question's sample dictionary format student={1:('Asmita',89.7)} โ€” each record is dumped separately so it can be read one at a time.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ roll, name, marks
โžœ
โ‘ก PROCESSuses a for loop; a while loop; file handling (open โ†’ read/write โ†’ close); try / except to handle errors; module pickle
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, Asmita, 89.7, 2, Swati, 87.5, 3, Rohan, 76, 4 โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ File๐Ÿ“ฆ Library / Data๐Ÿ›ก๏ธ Error handling
LineCodeWhat it does
1
import pickle
๐Ÿ“ฆ Library / Data Loads the module pickle - writing / reading Python objects in binary files
3
with open("marks.dat", "wb") as f:
๐Ÿ“ File Opens the file "marks.dat" in "wb" mode - write in binary (old content is erased) and calls it f. "with" closes the file automatically when the block ends
4
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
5
roll = int(input("Roll number: "))
โŒจ๏ธ Input Shows "Roll number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
6
name = input("Name: ")
โŒจ๏ธ Input Shows the message "Name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
7
marks = float(input("Marks: "))
โŒจ๏ธ Input Shows "Marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable marks
8
student = {roll: (name, marks)}
๐Ÿงฎ Store / Calculate Stores a dictionary {roll: (name, marks)} in variable student
9
pickle.dump(student, f)
๐Ÿ“ File Writes (pickles) student into the binary file f
11
print("\nRecords stored. Reading back:")
๐Ÿ–ฅ๏ธ Output Displays the text "Records stored. Reading back:" on the screen
12
with open("marks.dat", "rb") as f:
๐Ÿ“ File Opens the file "marks.dat" in "rb" mode - read in binary and calls it f. "with" closes the file automatically when the block ends
13
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
14
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
15
print(pickle.load(f))
๐Ÿ“ File Displays the value of pickle.load(f) on the screen
16
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
17
break
๐Ÿ” Loop BREAK - leaves the loop immediately
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pickle
23
with open("marks.dat", "wb") as f:
f = file object "marks.dat" (mode wb)
34
for i in range(5):
next item taken
i = 0
45
roll = int(input("Roll number: "))
roll = 1
Roll number: 1
56
name = input("Name: ")
name = 'Asmita'
Name: Asmita
67
marks = float(input("Marks: "))
marks = 89.7
Marks: 89.7
78
student = {roll: (name, marks)}
student = {1: ('Asmita', 89.7)}
89
pickle.dump(student, f)
94
for i in range(5):
next item taken
i = 1
105
roll = int(input("Roll number: "))
roll = 2
Roll number: 2
116
name = input("Name: ")
name = 'Swati'
Name: Swati
127
marks = float(input("Marks: "))
marks = 87.5
Marks: 87.5
138
student = {roll: (name, marks)}
student = {2: ('Swati', 87.5)}
149
pickle.dump(student, f)
154
for i in range(5):
next item taken
i = 2
165
roll = int(input("Roll number: "))
roll = 3
Roll number: 3
176
name = input("Name: ")
name = 'Rohan'
Name: Rohan
187
marks = float(input("Marks: "))
marks = 76.0
Marks: 76
198
student = {roll: (name, marks)}
student = {3: ('Rohan', 76.0)}
209
pickle.dump(student, f)
214
for i in range(5):
next item taken
i = 3
225
roll = int(input("Roll number: "))
roll = 4
Roll number: 4
236
name = input("Name: ")
name = 'Kavya'
Name: Kavya
247
marks = float(input("Marks: "))
marks = 92.5
Marks: 92.5
258
student = {roll: (name, marks)}
student = {4: ('Kavya', 92.5)}
269
pickle.dump(student, f)
274
for i in range(5):
next item taken
i = 4
285
roll = int(input("Roll number: "))
roll = 5
Roll number: 5
296
name = input("Name: ")
name = 'Arjun'
Name: Arjun
307
marks = float(input("Marks: "))
marks = 68.0
Marks: 68
318
student = {roll: (name, marks)}
student = {5: ('Arjun', 68.0)}
329
pickle.dump(student, f)

โ€ฆ Python runs 25 more line-steps in the same way (loops repeat the same lines). Final values: f = file object "marks.dat" (mode rb), i = 4, roll = 5, name = 'Arjun', marks = 68.0, student = {5: ('Arjun', 68.0)}

Q17 PYTHON

Create a CSV file by entering user-id and password; read and search the password for a given user-id.

import csv

with open("login.csv", "w", newline="") as f:
    writer = csv.writer(f)
    n = int(input("How many records? "))
    for i in range(n):
        uid = input("Enter user-id: ")
        pwd = input("Enter password: ")
        writer.writerow([uid, pwd])

search_id = input("\nEnter user-id to search: ")
with open("login.csv", "r", newline="") as f:
    reader = csv.reader(f)
    found = False
    for row in reader:
        if row[0] == search_id:
            print("Password:", row[1])
            found = True
            break
    if not found:
        print("User-id not found")
โ–ถ Sample Output
How many records? 3
Enter user-id: admin
Enter password: kvs@123
Enter user-id: student
Enter password: pass@26
Enter user-id: teacher
Enter password: tch#2026

Enter user-id to search: admin
Password: kvs@123
๐Ÿ’ก Explanation: csv.writer/reader handle comma-separated data properly; always use newline='' to avoid blank rows on Windows.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ search_id, n, uid, pwd
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else; file handling (open โ†’ read/write โ†’ close); module csv
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 3, admin, kvs@123, student, pass@26, teacher, tch#2026, admin (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import csv
๐Ÿ“ฆ Library / Data Loads the module csv - reading / writing CSV files
3
with open("login.csv", "w", newline="") as f:
๐Ÿ“ File Opens the file "login.csv" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
4
writer = csv.writer(f)
๐Ÿ“ File Creates a CSV writer object for file f; the result is stored in variable writer
5
n = int(input("How many records? "))
โŒจ๏ธ Input Shows "How many records? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
6
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
7
uid = input("Enter user-id: ")
โŒจ๏ธ Input Shows the message "Enter user-id: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable uid
8
pwd = input("Enter password: ")
โŒจ๏ธ Input Shows the message "Enter password: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable pwd
9
writer.writerow([uid, pwd])
๐Ÿ“ File Writes one row [uid, pwd] into the CSV file
11
search_id = input("\nEnter user-id to search: ")
โŒจ๏ธ Input Shows the message "\nEnter user-id to search: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable search_id
12
with open("login.csv", "r", newline="") as f:
๐Ÿ“ File Opens the file "login.csv" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
13
reader = csv.reader(f)
๐Ÿ“ File Creates a CSV reader that gives each row of f as a list; the result is stored in variable reader
14
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
15
for row in reader:
๐Ÿ” Loop LOOP: takes each item of reader one-by-one into row and runs the indented block for it
16
if row[0] == search_id:
๐Ÿ”€ Decision CHECKS whether row[0] is equal to search_id. If True, the indented lines below run; otherwise they are skipped
17
print("Password:", row[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Password:", then the value of row[1] on the screen
18
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
19
break
๐Ÿ” Loop BREAK - leaves the loop immediately
20
if not found:
๐Ÿ”€ Decision CHECKS whether found is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
21
print("User-id not found")
๐Ÿ–ฅ๏ธ Output Displays the text "User-id not found" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import csv
23
with open("login.csv", "w", newline="") as f:
f = file object "login.csv" (mode w)
34
writer = csv.writer(f)
writer = <_csv.writer object at 0x7f47f978d8a0>
45
n = int(input("How many records? "))
n = 3
How many records? 3
56
for i in range(n):
next item taken
i = 0
67
uid = input("Enter user-id: ")
uid = 'admin'
Enter user-id: admin
78
pwd = input("Enter password: ")
pwd = 'kvs@123'
Enter password: kvs@123
89
writer.writerow([uid, pwd])
96
for i in range(n):
next item taken
i = 1
107
uid = input("Enter user-id: ")
uid = 'student'
Enter user-id: student
118
pwd = input("Enter password: ")
pwd = 'pass@26'
Enter password: pass@26
129
writer.writerow([uid, pwd])
136
for i in range(n):
next item taken
i = 2
147
uid = input("Enter user-id: ")
uid = 'teacher'
Enter user-id: teacher
158
pwd = input("Enter password: ")
pwd = 'tch#2026'
Enter password: tch#2026
169
writer.writerow([uid, pwd])
176
for i in range(n):
no items left โ†’ loop ends
183
with open("login.csv", "w", newline="") as f:
block over โ†’ file closed automatically
1911
search_id = input("\nEnter user-id to search: ")
search_id = 'admin'
Enter user-id to search: admin
2012
with open("login.csv", "r", newline="") as f:
f = file object "login.csv" (mode r)
2113
reader = csv.reader(f)
reader = <_csv.reader object at 0x7f47f289e3b0>
2214
found = False
found = False
2315
for row in reader:
next item taken
row = ['admin', 'kvs@123']
2416
if row[0] == search_id:
condition is TRUE โ†’ enters the block
2517
print("Password:", row[1])
Password: kvs@123
2618
found = True
found = True
2719
break
2820
if not found:
condition is FALSE โ†’ skips this block
2912
with open("login.csv", "r", newline="") as f:
block over โ†’ file closed automatically
Q18 PYTHON

Menu driven program to create a CSV file with dept-id, name, city; read and search a record for given dept-id.

import csv

def create_csv():
    with open("dept.csv", "a", newline="") as f:
        writer = csv.writer(f)
        did = input("Enter dept-id: ")
        name = input("Enter name: ")
        city = input("Enter city: ")
        writer.writerow([did, name, city])
    print("Record added")

def search_csv():
    did = input("Enter dept-id to search: ")
    with open("dept.csv", "r", newline="") as f:
        reader = csv.reader(f)
        found = False
        for row in reader:
            if row and row[0] == did:
                print("Record:", row)
                found = True
        if not found:
            print("Dept-id not found")

while True:
    print("\nMENU\n1. Create csv file\n2. Search record as per dept no\n3. Exit")
    ch = int(input("Enter choice: "))
    if ch == 1:
        create_csv()
    elif ch == 2:
        search_csv()
    elif ch == 3:
        break
    else:
        print("Invalid choice")
โ–ถ Sample Output
MENU
1. Create csv file
2. Search record as per dept no
3. Exit
Enter choice: 1
Enter dept-id: D01
Enter name: Admin
Enter city: Delhi
Record added

MENU
1. Create csv file
2. Search record as per dept no
3. Exit
Enter choice: 1
Enter dept-id: D02
Enter name: Accounts
Enter city: Mumbai
Record added

MENU
1. Create csv file
2. Search record as per dept no
3. Exit
Enter choice: 2
Enter dept-id to search: D01
Record: ['D01', 'Admin', 'Delhi']

MENU
1. Create csv file
2. Search record as per dept no
3. Exit
Enter choice: 3
๐Ÿ’ก Explanation: 'a' (append) mode is used so each new run adds to the file instead of erasing previous department records.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ did, ch, name, city
โžœ
โ‘ก PROCESSuses its own functions create_csv(), search_csv(); a while loop; decisions with if / elif / else; a for loop; file handling (open โ†’ read/write โ†’ close); module csv
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, D01, Admin, Delhi, 1, D02, Accounts, Mumbai, 2, D01 โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function๐Ÿ“ File๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import csv
๐Ÿ“ฆ Library / Data Loads the module csv - reading / writing CSV files
3
def create_csv():
๐Ÿงฉ Function DEFINES a function create_csv(). Python only remembers it here - its body runs later, each time create_csv() is called.
4
with open("dept.csv", "a", newline="") as f:
๐Ÿ“ File Opens the file "dept.csv" in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
5
writer = csv.writer(f)
๐Ÿ“ File Creates a CSV writer object for file f; the result is stored in variable writer
6
did = input("Enter dept-id: ")
โŒจ๏ธ Input Shows the message "Enter dept-id: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable did
7
name = input("Enter name: ")
โŒจ๏ธ Input Shows the message "Enter name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
8
city = input("Enter city: ")
โŒจ๏ธ Input Shows the message "Enter city: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable city
9
writer.writerow([did, name, city])
๐Ÿ“ File Writes one row [did, name, city] into the CSV file
10
print("Record added")
๐Ÿ–ฅ๏ธ Output Displays the text "Record added" on the screen
12
def search_csv():
๐Ÿงฉ Function DEFINES a function search_csv(). Python only remembers it here - its body runs later, each time search_csv() is called.
13
did = input("Enter dept-id to search: ")
โŒจ๏ธ Input Shows the message "Enter dept-id to search: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable did
14
with open("dept.csv", "r", newline="") as f:
๐Ÿ“ File Opens the file "dept.csv" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
15
reader = csv.reader(f)
๐Ÿ“ File Creates a CSV reader that gives each row of f as a list; the result is stored in variable reader
16
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
17
for row in reader:
๐Ÿ” Loop LOOP: takes each item of reader one-by-one into row and runs the indented block for it
18
if row and row[0] == did:
๐Ÿ”€ Decision CHECKS whether (row is True (not empty / not zero) AND row[0] is equal to did). If True, the indented lines below run; otherwise they are skipped
19
print("Record:", row)
๐Ÿ–ฅ๏ธ Output Displays the text "Record:", then the value of row on the screen
20
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
21
if not found:
๐Ÿ”€ Decision CHECKS whether found is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
22
print("Dept-id not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Dept-id not found" on the screen
24
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
25
print("\nMENU\n1. Create csv file\n2. Search record as per dept no\n3. Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "MENU 1. Create csv file 2. Searchโ€ฆ" on the screen
26
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
27
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
28
create_csv()
๐Ÿงฎ Store / Calculate Calls our own function create_csv()
29
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
30
search_csv()
๐Ÿงฎ Store / Calculate Calls our own function search_csv()
31
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
32
break
๐Ÿ” Loop BREAK - leaves the loop immediately
33
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
34
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import csv
23
def create_csv():
function is defined (remembered), not run yet
312
def search_csv():
function is defined (remembered), not run yet
424
while True:
condition is TRUE โ†’ enters the block
525
print("\nMENU\n1. Create csv file\n2. Search record as per dept no\n3. Exit")
MENU
1. Create csv file
2. Search record as per dept no
3. Exit
626
ch = int(input("Enter choice: "))
ch = 1
Enter choice: 1
727
if ch == 1:
condition is TRUE โ†’ enters the block
828
create_csv()
โžก Python jumps INTO function create_csv()
94
with open("dept.csv", "a", newline="") as f:
f = file object "dept.csv" (mode a)
105
writer = csv.writer(f)
writer = <_csv.writer object at 0x7f74f51e58a0>
116
did = input("Enter dept-id: ")
did = 'D01'
Enter dept-id: D01
127
name = input("Enter name: ")
name = 'Admin'
Enter name: Admin
138
city = input("Enter city: ")
city = 'Delhi'
Enter city: Delhi
149
writer.writerow([did, name, city])
154
with open("dept.csv", "a", newline="") as f:
block over โ†’ file closed automatically
1610
print("Record added")
Record added
โฌ… function create_csv() ends and returns None to the caller
1724
while True:
condition is TRUE โ†’ enters the block
1825
print("\nMENU\n1. Create csv file\n2. Search record as per dept no\n3. Exit")
MENU
1. Create csv file
2. Search record as per dept no
3. Exit
1926
ch = int(input("Enter choice: "))
Enter choice: 1
2027
if ch == 1:
condition is TRUE โ†’ enters the block
2128
create_csv()
โžก Python jumps INTO function create_csv()
224
with open("dept.csv", "a", newline="") as f:
f = file object "dept.csv" (mode a)
235
writer = csv.writer(f)
writer = <_csv.writer object at 0x7f74f51e58a0>
246
did = input("Enter dept-id: ")
did = 'D02'
Enter dept-id: D02
257
name = input("Enter name: ")
name = 'Accounts'
Enter name: Accounts
268
city = input("Enter city: ")
city = 'Mumbai'
Enter city: Mumbai
279
writer.writerow([did, name, city])
284
with open("dept.csv", "a", newline="") as f:
block over โ†’ file closed automatically
2910
print("Record added")
Record added

โ€ฆ Python runs 26 more line-steps in the same way (loops repeat the same lines). Final values: ch = 3, f = file object "dept.csv" (mode r), writer = <_csv.writer object at 0x7f74f51e58a0>, did = 'D01', name = 'Accounts', city = 'Mumbai', reader = <_csv.reader object at 0x7f74ee386b90>, found = True, row = ['D02', 'Accounts', 'Mumbai']

Q19 PYTHON

Implement a Stack using a list (PUSH & POP operations).

stack = []

def push(item):
    stack.append(item)
    print(item, "pushed to stack")

def pop():
    if not stack:
        print("Stack Underflow! Stack is empty")
    else:
        print(stack.pop(), "popped from stack")

while True:
    print("\n1.PUSH  2.POP  3.Display  4.Exit")
    ch = int(input("Enter choice: "))
    if ch == 1:
        push(input("Enter item to push: "))
    elif ch == 2:
        pop()
    elif ch == 3:
        print("Stack:", stack)
    elif ch == 4:
        break
    else:
        print("Invalid choice")
โ–ถ Sample Output
1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 1
Enter item to push: 10
10 pushed to stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 1
Enter item to push: 20
20 pushed to stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 1
Enter item to push: 30
30 pushed to stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 3
Stack: ['10', '20', '30']

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 2
30 popped from stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 3
Stack: ['10', '20']

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 2
20 popped from stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 2
10 popped from stack

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 2
Stack Underflow! Stack is empty

1.PUSH  2.POP  3.Display  4.Exit
Enter choice: 4
๐Ÿ’ก Explanation: list.append() = PUSH, list.pop() = POP โ€” Python's built-in list already behaves like a stack (LIFO).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ ch
โžœ
โ‘ก PROCESSuses its own functions push(), pop(); a while loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 10, 1, 20, 1, 30, 3, 2, 3, 2 โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
stack = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable stack
3
def push(item):
๐Ÿงฉ Function DEFINES a function push(item). Python only remembers it here - its body runs later, each time push() is called.
4
stack.append(item)
๐Ÿงฎ Store / Calculate Adds item at the end of list stack
5
print(item, "pushed to stack")
๐Ÿ–ฅ๏ธ Output Displays the value of item, then the text "pushed to stack" on the screen
7
def pop():
๐Ÿงฉ Function DEFINES a function pop(). Python only remembers it here - its body runs later, each time pop() is called.
8
if not stack:
๐Ÿ”€ Decision CHECKS whether stack is False (or empty / zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
9
print("Stack Underflow! Stack is empty")
๐Ÿ–ฅ๏ธ Output Displays the text "Stack Underflow! Stack is empty" on the screen
10
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
11
print(stack.pop(), "popped from stack")
๐Ÿ–ฅ๏ธ Output Displays the value of stack.pop(), then the text "popped from stack" on the screen
13
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
14
print("\n1.PUSH  2.POP  3.Display  4.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.PUSH 2.POP 3.Display 4.Exit" on the screen
15
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
16
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
17
push(input("Enter item to push: "))
โŒจ๏ธ Input Calls our own function push(input("Enter item tโ€ฆ)
18
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
19
pop()
๐Ÿงฎ Store / Calculate Calls our own function pop()
20
elif ch == 3:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 3
21
print("Stack:", stack)
๐Ÿ–ฅ๏ธ Output Displays the text "Stack:", then the value of stack on the screen
22
elif ch == 4:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 4
23
break
๐Ÿ” Loop BREAK - leaves the loop immediately
24
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
25
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
stack = []
stack = []
23
def push(item):
function is defined (remembered), not run yet
37
def pop():
function is defined (remembered), not run yet
413
while True:
condition is TRUE โ†’ enters the block
514
print("\n1.PUSH  2.POP  3.Display  4.Exit")
1.PUSH  2.POP  3.Display  4.Exit
615
ch = int(input("Enter choice: "))
ch = 1
Enter choice: 1
716
if ch == 1:
condition is TRUE โ†’ enters the block
817
push(input("Enter item to push: "))
stack = ['10']
Enter item to push: 10
โžก Python jumps INTO function push(item='10')
94
stack.append(item)
105
print(item, "pushed to stack")
10 pushed to stack
โฌ… function push() ends and returns None to the caller
1113
while True:
condition is TRUE โ†’ enters the block
1214
print("\n1.PUSH  2.POP  3.Display  4.Exit")
1.PUSH  2.POP  3.Display  4.Exit
1315
ch = int(input("Enter choice: "))
Enter choice: 1
1416
if ch == 1:
condition is TRUE โ†’ enters the block
1517
push(input("Enter item to push: "))
stack = ['10', '20']
Enter item to push: 20
โžก Python jumps INTO function push(item='20')
164
stack.append(item)
175
print(item, "pushed to stack")
20 pushed to stack
โฌ… function push() ends and returns None to the caller
1813
while True:
condition is TRUE โ†’ enters the block
1914
print("\n1.PUSH  2.POP  3.Display  4.Exit")
1.PUSH  2.POP  3.Display  4.Exit
2015
ch = int(input("Enter choice: "))
Enter choice: 1
2116
if ch == 1:
condition is TRUE โ†’ enters the block
2217
push(input("Enter item to push: "))
stack = ['10', '20', '30']
Enter item to push: 30
โžก Python jumps INTO function push(item='30')
234
stack.append(item)
245
print(item, "pushed to stack")
30 pushed to stack
โฌ… function push() ends and returns None to the caller
2513
while True:
condition is TRUE โ†’ enters the block
2614
print("\n1.PUSH  2.POP  3.Display  4.Exit")
1.PUSH  2.POP  3.Display  4.Exit

โ€ฆ Python runs 52 more line-steps in the same way (loops repeat the same lines). Final values: stack = [], ch = 4

Q20 PYTHON

Function PUSH(Arr): from a given list push all numbers divisible by 5 into a stack implemented using a list.

def PUSH(Arr):
    stack = []
    for num in Arr:
        if num % 5 == 0:
            stack.append(num)
    return stack

Arr = list(map(int, input("Enter list of numbers: ").split()))
stack = PUSH(Arr)

if stack:
    print("Stack (multiples of 5):", stack)
else:
    print("No element divisible by 5 found - Stack is empty")
โ–ถ Sample Output
Enter list of numbers: 5 10 12 15 20 25
Stack (multiples of 5): [5, 10, 15, 20, 25]
๐Ÿ’ก Explanation: Filters elements divisible by 5 and pushes each onto a new stack list, per the exact function signature asked.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ Arr
โžœ
โ‘ก PROCESSuses its own function PUSH(); decisions with if / elif / else; a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 5 10 12 15 20 25 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿงฉ Function
LineCodeWhat it does
1
def PUSH(Arr):
๐Ÿงฉ Function DEFINES a function PUSH(Arr). Python only remembers it here - its body runs later, each time PUSH() is called.
2
stack = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable stack
3
for num in Arr:
๐Ÿ” Loop LOOP: takes each item of Arr one-by-one into num and runs the indented block for it
4
if num % 5 == 0:
๐Ÿ”€ Decision CHECKS whether num % 5 is equal to 0. If True, the indented lines below run; otherwise they are skipped
5
stack.append(num)
๐Ÿงฎ Store / Calculate Adds num at the end of list stack
6
return stack
๐Ÿงฉ Function Sends back (returns) the value of stack to the line that called the function
8
Arr = list(map(int, input("Enter list of numbers: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter list of numbers: ").splโ€ฆ; the result is stored in variable Arr
9
stack = PUSH(Arr)
๐Ÿงฎ Store / Calculate Calls our own function PUSH(Arr); the result is stored in variable stack
11
if stack:
๐Ÿ”€ Decision CHECKS whether stack is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
12
print("Stack (multiples of 5):", stack)
๐Ÿ–ฅ๏ธ Output Displays the text "Stack (multiples of 5):", then the value of stack on the screen
13
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
14
print("No element divisible by 5 found - Stack is empty")
๐Ÿ–ฅ๏ธ Output Displays the text "No element divisible by 5 found -โ€ฆ" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def PUSH(Arr):
function is defined (remembered), not run yet
28
Arr = list(map(int, input("Enter list of numbers: ").split()))
Arr = [5, 10, 12, 15, 20, 25]
Enter list of numbers: 5 10 12 15 20 25
39
stack = PUSH(Arr)
stack = [5, 10, 15, 20, 25]
โžก Python jumps INTO function PUSH(Arr=[5, 10, 12, 15, 20, 25])
42
stack = []
stack = []
53
for num in Arr:
next item taken
num = 5
64
if num % 5 == 0:
condition is TRUE โ†’ enters the block
75
stack.append(num)
stack = [5]
83
for num in Arr:
next item taken
num = 10
94
if num % 5 == 0:
condition is TRUE โ†’ enters the block
105
stack.append(num)
stack = [5, 10]
113
for num in Arr:
next item taken
num = 12
124
if num % 5 == 0:
condition is FALSE โ†’ skips this block
133
for num in Arr:
next item taken
num = 15
144
if num % 5 == 0:
condition is TRUE โ†’ enters the block
155
stack.append(num)
stack = [5, 10, 15]
163
for num in Arr:
next item taken
num = 20
174
if num % 5 == 0:
condition is TRUE โ†’ enters the block
185
stack.append(num)
stack = [5, 10, 15, 20]
193
for num in Arr:
next item taken
num = 25
204
if num % 5 == 0:
condition is TRUE โ†’ enters the block
215
stack.append(num)
stack = [5, 10, 15, 20, 25]
223
for num in Arr:
no items left โ†’ loop ends
236
return stack
โฌ… function PUSH() ends and returns [5, 10, 15, 20, 25] to the caller
2411
if stack:
condition is TRUE โ†’ enters the block
2512
print("Stack (multiples of 5):", stack)
Stack (multiples of 5): [5, 10, 15, 20, 25]
Q21 PYTHON

Function POP(Arr): Arr is a stack implemented using a list of numbers; the function returns the value deleted from the stack.

def POP(Arr):
    if not Arr:
        print("Stack Underflow")
        return None
    return Arr.pop()

Arr = list(map(int, input("Enter stack elements: ").split()))
print("Stack before POP:", Arr)

deleted = POP(Arr)
if deleted is not None:
    print("Value deleted from stack:", deleted)
print("Stack after POP:", Arr)
โ–ถ Sample Output
Enter stack elements: 10 20 30 40
Stack before POP: [10, 20, 30, 40]
Value deleted from stack: 40
Stack after POP: [10, 20, 30]
๐Ÿ’ก Explanation: list.pop() (with no index) removes and returns the last (top) element โ€” exactly the LIFO behaviour of a stack.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines inside a def run only when that function is called. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ Arr
โžœ
โ‘ก PROCESSuses its own function POP(); decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q21.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10 20 30 40 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿงฉ Function
LineCodeWhat it does
1
def POP(Arr):
๐Ÿงฉ Function DEFINES a function POP(Arr). Python only remembers it here - its body runs later, each time POP() is called.
2
if not Arr:
๐Ÿ”€ Decision CHECKS whether Arr is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
3
print("Stack Underflow")
๐Ÿ–ฅ๏ธ Output Displays the text "Stack Underflow" on the screen
4
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
5
return Arr.pop()
๐Ÿงฉ Function Sends back (returns) the result of: removes and returns an item from Arr to the line that called the function
7
Arr = list(map(int, input("Enter stack elements: ").split()))
โŒจ๏ธ Input Makes a list from map(int, input("Enter stack elements: ").spliโ€ฆ; the result is stored in variable Arr
8
print("Stack before POP:", Arr)
๐Ÿ–ฅ๏ธ Output Displays the text "Stack before POP:", then the value of Arr on the screen
10
deleted = POP(Arr)
๐Ÿงฎ Store / Calculate Calls our own function POP(Arr); the result is stored in variable deleted
11
if deleted is not None:
๐Ÿ”€ Decision CHECKS whether deleted is not None. If True, the indented lines below run; otherwise they are skipped
12
print("Value deleted from stack:", deleted)
๐Ÿ–ฅ๏ธ Output Displays the text "Value deleted from stack:", then the value of deleted on the screen
13
print("Stack after POP:", Arr)
๐Ÿ–ฅ๏ธ Output Displays the text "Stack after POP:", then the value of Arr on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
def POP(Arr):
function is defined (remembered), not run yet
27
Arr = list(map(int, input("Enter stack elements: ").split()))
Arr = [10, 20, 30, 40]
Enter stack elements: 10 20 30 40
38
print("Stack before POP:", Arr)
Stack before POP: [10, 20, 30, 40]
410
deleted = POP(Arr)
Arr = [10, 20, 30], deleted = 40
โžก Python jumps INTO function POP(Arr=[10, 20, 30, 40])
52
if not Arr:
condition is FALSE โ†’ skips this block
65
return Arr.pop()
Arr = [10, 20, 30]
โฌ… function POP() ends and returns 40 to the caller
711
if deleted is not None:
condition is TRUE โ†’ enters the block
812
print("Value deleted from stack:", deleted)
Value deleted from stack: 40
913
print("Stack after POP:", Arr)
Stack after POP: [10, 20, 30]
Q22 SQL

Create a school database, create a student table and implement ALTER, UPDATE, ORDER BY, DELETE, GROUP BY, MIN/MAX/SUM/COUNT/AVG on it.

CREATE DATABASE school;
USE school;

CREATE TABLE student (
    rollno INT PRIMARY KEY,
    name   VARCHAR(30),
    class  INT,
    marks  DECIMAL(5,2)
);

INSERT INTO student VALUES (1,'Amit',12,88.5);
INSERT INTO student VALUES (2,'Sara',12,92.0);
INSERT INTO student VALUES (3,'Rahul',12,65.5);
INSERT INTO student VALUES (4,'Priya',12,78.0);

-- ALTER: add a new column
ALTER TABLE student ADD email VARCHAR(40);
-- ALTER: modify data type
ALTER TABLE student MODIFY marks DECIMAL(6,2);
-- ALTER: drop attribute
ALTER TABLE student DROP COLUMN email;

-- UPDATE
UPDATE student SET marks = 90.0 WHERE rollno = 3;

-- ORDER BY
SELECT * FROM student ORDER BY marks DESC;
SELECT * FROM student ORDER BY name ASC;

-- DELETE
DELETE FROM student WHERE rollno = 4;

-- GROUP BY
SELECT class, COUNT(*) FROM student GROUP BY class;

-- Aggregate functions
SELECT MIN(marks), MAX(marks), SUM(marks), COUNT(*), COUNT(marks), AVG(marks) FROM student;
โ–ถ Sample Output
mysql> CREATE DATABASE school;
Query OK, 1 row affected (0.00 sec)

mysql> USE school;
Database changed

mysql> CREATE TABLE student (
    ->     rollno INT PRIMARY KEY,
    ->     name   VARCHAR(30),
    ->     class  INT,
    ->     marks  DECIMAL(5,2)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO student VALUES (1,'Amit',12,88.5);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (2,'Sara',12,92.0);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (3,'Rahul',12,65.5);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (4,'Priya',12,78.0);
Query OK, 1 row affected (0.00 sec)

mysql> ALTER TABLE student ADD email VARCHAR(40);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE student MODIFY marks DECIMAL(6,2);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE student DROP COLUMN email;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> UPDATE student SET marks = 90.0 WHERE rollno = 3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM student ORDER BY marks DESC;
+--------+-------+-------+-------+
| rollno | name  | class | marks |
+--------+-------+-------+-------+
|      2 | Sara  |    12 | 92.00 |
|      3 | Rahul |    12 | 90.00 |
|      1 | Amit  |    12 | 88.50 |
|      4 | Priya |    12 | 78.00 |
+--------+-------+-------+-------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM student ORDER BY name ASC;
+--------+-------+-------+-------+
| rollno | name  | class | marks |
+--------+-------+-------+-------+
|      1 | Amit  |    12 | 88.50 |
|      4 | Priya |    12 | 78.00 |
|      3 | Rahul |    12 | 90.00 |
|      2 | Sara  |    12 | 92.00 |
+--------+-------+-------+-------+
4 rows in set (0.00 sec)

mysql> DELETE FROM student WHERE rollno = 4;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT class, COUNT(*) FROM student GROUP BY class;
+-------+----------+
| class | COUNT(*) |
+-------+----------+
|    12 |        3 |
+-------+----------+
1 row in set (0.00 sec)

mysql> SELECT MIN(marks), MAX(marks), SUM(marks), COUNT(*), COUNT(marks), AVG(marks) FROM student;
+------------+------------+------------+----------+--------------+------------+
| MIN(marks) | MAX(marks) | SUM(marks) | COUNT(*) | COUNT(marks) | AVG(marks) |
+------------+------------+------------+----------+--------------+------------+
|      88.50 |      92.00 |     270.50 |        3 |            3 |  90.166667 |
+------------+------------+------------+----------+--------------+------------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: This single practical covers every core DDL/DML command asked in the syllabus โ€” practise each block independently for viva.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. The code selects the database with USE school; - MySQL replies Database changed.
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE DATABASE school;

Creates a new, empty database (a folder for tables) named school.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
2
Command
USE school;

Selects the database school - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
3
DDL ยท structure
CREATE TABLE student (
    rollno INT PRIMARY KEY,
    name   VARCHAR(30),
    class  INT,
    marks  DECIMAL(5,2)
);

Creates a new table student with 4 columns. Each column gets a name and a data type:

  • rollno โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • name โ†’ VARCHAR(30) (text up to 30 characters)
  • class โ†’ INT (whole numbers)
  • marks โ†’ DECIMAL(5,2) (decimal number, 5 digits in all with 2 after the point)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
4
DML ยท data change
INSERT INTO student VALUES (1,'Amit',12,88.5);
โ€ฆ (3 more INSERT statements of the same kind)

These 4 INSERT statements add 4 rows, one row each, into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: each INSERT says "Query OK, 1 row affected"
๐Ÿ“Œ ALTER: add a new column
5
DDL ยท structure
ALTER TABLE student ADD email VARCHAR(40);

Changes the STRUCTURE (design) of table student: adds a new column email (existing rows get NULL in it).

  • Data in other columns is not touched.
โœ” Result: Query OK, 0 rows affected ยท Records: 0 Duplicates: 0 Warnings: 0
๐Ÿ“Œ ALTER: modify data type
6
DDL ยท structure
ALTER TABLE student MODIFY marks DECIMAL(6,2);

Changes the STRUCTURE (design) of table student: changes the data type/size of column marks to DECIMAL(6,2).

  • Data in other columns is not touched.
โœ” Result: Query OK, 4 rows affected ยท Records: 4 Duplicates: 0 Warnings: 0
๐Ÿ“Œ ALTER: drop attribute
7
DDL ยท structure
ALTER TABLE student DROP COLUMN email;

Changes the STRUCTURE (design) of table student: removes column email along with all its data.

  • Data in other columns is not touched.
โœ” Result: Query OK, 0 rows affected ยท Records: 0 Duplicates: 0 Warnings: 0
๐Ÿ“Œ UPDATE
8
DML ยท data change
UPDATE student SET marks = 90.0 WHERE rollno = 3;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE rollno = 3 โ†’ finds only the rows that match.
  3. SET marks = 90.0 โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE rollno = 3 โ†’ 1 row(s) matched.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1265.50โœŽ
4Priya1278.00
โœ” Result: Query OK, 1 row affected ยท Rows matched: 1 Changed: 1 Warnings: 0
๐Ÿ“Œ ORDER BY
9
Query ยท read only
SELECT * FROM student ORDER BY marks DESC;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
  3. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 4 rows are taken.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1290.00
4Priya1278.00
โœ” Result: 4 rows in set
10
Query ยท read only
SELECT * FROM student ORDER BY name ASC;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
  3. ORDER BY name ASC โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 4 rows are taken.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1290.00
4Priya1278.00
โœ” Result: 4 rows in set
๐Ÿ“Œ DELETE
11
DML ยท data change
DELETE FROM student WHERE rollno = 4;

Removes rows from table student.

  1. FROM student โ†’ picks the table.
  2. WHERE rollno = 4 โ†’ finds the matching rows.
  3. Those rows are removed permanently โ†’ "Query OK, n rows affected".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE rollno = 4 โ†’ 1 row(s) matched.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1290.00
4Priya1278.00๐Ÿ—‘
โœ” Result: Query OK, 1 row affected
๐Ÿ“Œ GROUP BY
12
Query ยท read only
SELECT class, COUNT(*) FROM student GROUP BY class;

Fetches rows from student, grouped by class.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY class โ†’ makes groups: rows with the same class go into one group (one output row per group).
  3. SELECT class, COUNT(*) โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group.
  4. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 3 rows are taken.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1290.00
โœ” Result: 1 row in set
๐Ÿ“Œ Aggregate functions
13
Query ยท read only
SELECT MIN(marks), MAX(marks), SUM(marks), COUNT(*), COUNT(marks), AVG(marks) FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT MIN(marks), MAX(marks), SUM(marks), COUNT(*), COUNT(marks), AVG(marks) โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row.
  3. Functions used: MIN() finds the smallest value; MAX() finds the largest value; SUM() adds the values; COUNT(*) counts all rows; COUNT() counts the non-NULL values; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 3 rows are taken.

rollnonameclassmarks
1Amit1288.50
2Sara1292.00
3Rahul1290.00
โœ” Result: 1 row in set
Q23 PYTHON + MySQL

Integrate SQL with Python using the MySQL module โ€” insert and display employee records.

import mysql.connector

conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS employee (empno INT PRIMARY KEY, name VARCHAR(30), salary DECIMAL(8,2))")

n = int(input("How many employees to insert? "))
for i in range(n):
    empno = int(input("Emp No: "))
    name = input("Name: ")
    salary = float(input("Salary: "))
    cursor.execute("INSERT INTO employee VALUES (%s,%s,%s)", (empno, name, salary))

conn.commit()

cursor.execute("SELECT * FROM employee")
print("\nEmployee Records:")
for row in cursor.fetchall():
    print(row)

conn.close()
โ–ถ Sample Output
How many employees to insert? 2
Emp No: 101
Name: Ramesh
Salary: 45000
Emp No: 102
Name: Suman
Salary: 52000

Employee Records:
(101, 'Ramesh', Decimal('45000.00'))
(102, 'Suman', Decimal('52000.00'))
๐Ÿ’ก Explanation: mysql.connector bridges Python and MySQL; conn.commit() is mandatory after INSERT/UPDATE/DELETE to save changes permanently.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 4 values from the keyboard โ†’ n, empno, name, salary
โžœ
โ‘ก PROCESSuses a for loop; module mysql.connector
โžœ
โ‘ข OUTPUTprints the result on the screen, stores / reads data in MySQL
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q23.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿฌ Database
LineCodeWhat it does
1
import mysql.connector
๐Ÿ“ฆ Library / Data Loads the module mysql.connector - connecting Python with MySQL
3
conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
๐Ÿฌ Database Connects Python to the MySQL server using host, user, password and database "school"; the result is stored in variable conn
4
cursor = conn.cursor()
๐Ÿฌ Database Creates a cursor - the object that carries SQL queries to MySQL; the result is stored in variable cursor
6
cursor.execute("CREATE TABLE IF NOT EXISTS employee (empno INT PRIMARY KEY, name VARCHAR(30), salary DECIMAL(8,2))")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
8
n = int(input("How many employees to insert? "))
โŒจ๏ธ Input Shows "How many employees to insert? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
9
for i in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, i takes that value and the indented block runs once
10
empno = int(input("Emp No: "))
โŒจ๏ธ Input Shows "Emp No: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable empno
11
name = input("Name: ")
โŒจ๏ธ Input Shows the message "Name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
12
salary = float(input("Salary: "))
โŒจ๏ธ Input Shows "Salary: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable salary
13
cursor.execute("INSERT INTO employee VALUES (%s,%s,%s)", (empno, name, salary))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (empno, name, salary)
15
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
17
cursor.execute("SELECT * FROM employee")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
18
print("\nEmployee Records:")
๐Ÿ–ฅ๏ธ Output Displays the text "Employee Records:" on the screen
19
for row in cursor.fetchall():
๐Ÿ” Loop LOOP: takes each item of cursor.fetchall() one-by-one into row and runs the indented block for it
20
print(row)
๐Ÿ–ฅ๏ธ Output Displays the value of row on the screen
22
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
Q24 PYTHON + MySQL

Integrate SQL with Python โ€” search an employee using empno; display the record if present, else show a message.

import mysql.connector

conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
cursor = conn.cursor()

empno = int(input("Enter Emp No to search: "))
cursor.execute("SELECT * FROM employee WHERE empno = %s", (empno,))
row = cursor.fetchone()

if row:
    print("Record found:", row)
else:
    print("Employee not found")

conn.close()
โ–ถ Sample Output
Enter Emp No to search: 101
Record found: (101, 'Ramesh', Decimal('45000.00'))
๐Ÿ’ก Explanation: fetchone() returns None if no row matches โ€” a clean way to check 'record found or not'.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ empno
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; module mysql.connector
โžœ
โ‘ข OUTPUTprints the result on the screen, stores / reads data in MySQL
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q24.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“ฆ Library / Data๐Ÿฌ Database
LineCodeWhat it does
1
import mysql.connector
๐Ÿ“ฆ Library / Data Loads the module mysql.connector - connecting Python with MySQL
3
conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
๐Ÿฌ Database Connects Python to the MySQL server using host, user, password and database "school"; the result is stored in variable conn
4
cursor = conn.cursor()
๐Ÿฌ Database Creates a cursor - the object that carries SQL queries to MySQL; the result is stored in variable cursor
6
empno = int(input("Enter Emp No to search: "))
โŒจ๏ธ Input Shows "Enter Emp No to search: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable empno
7
cursor.execute("SELECT * FROM employee WHERE empno = %s", (empno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (empno,)
8
row = cursor.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable row
10
if row:
๐Ÿ”€ Decision CHECKS whether row is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
11
print("Record found:", row)
๐Ÿ–ฅ๏ธ Output Displays the text "Record found:", then the value of row on the screen
12
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
13
print("Employee not found")
๐Ÿ–ฅ๏ธ Output Displays the text "Employee not found" on the screen
15
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
Q25 PYTHON + MySQL

Integrate SQL with Python โ€” update a student using rollno and delete a record using rollno.

import mysql.connector

conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
cursor = conn.cursor()

print("1.Update Student   2.Delete Student")
ch = int(input("Enter choice: "))

if ch == 1:
    roll = int(input("Enter rollno to update: "))
    marks = float(input("Enter new marks: "))
    cursor.execute("UPDATE student SET marks = %s WHERE rollno = %s", (marks, roll))
    conn.commit()
    print("Rows affected:", cursor.rowcount)

elif ch == 2:
    roll = int(input("Enter rollno to delete: "))
    cursor.execute("DELETE FROM student WHERE rollno = %s", (roll,))
    conn.commit()
    print("Rows affected:", cursor.rowcount)

conn.close()
โ–ถ Sample Output
1.Update Student   2.Delete Student
Enter choice: 1
Enter rollno to update: 2
Enter new marks: 95
Rows affected: 1
๐Ÿ’ก Explanation: cursor.rowcount tells you how many rows were actually affected โ€” useful to confirm whether the rollno existed.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ ch, roll, marks
โžœ
โ‘ก PROCESSuses decisions with if / elif / else; module mysql.connector
โžœ
โ‘ข OUTPUTprints the result on the screen, stores / reads data in MySQL
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_cs_q25.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“ฆ Library / Data๐Ÿฌ Database
LineCodeWhat it does
1
import mysql.connector
๐Ÿ“ฆ Library / Data Loads the module mysql.connector - connecting Python with MySQL
3
conn = mysql.connector.connect(host="localhost", user="root", password="yourpassword", database="school")
๐Ÿฌ Database Connects Python to the MySQL server using host, user, password and database "school"; the result is stored in variable conn
4
cursor = conn.cursor()
๐Ÿฌ Database Creates a cursor - the object that carries SQL queries to MySQL; the result is stored in variable cursor
6
print("1.Update Student   2.Delete Student")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Update Student 2.Delete Student" on the screen
7
ch = int(input("Enter choice: "))
โŒจ๏ธ Input Shows "Enter choice: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable ch
9
if ch == 1:
๐Ÿ”€ Decision CHECKS whether ch is equal to 1. If True, the indented lines below run; otherwise Python jumps to the elif/else part
10
roll = int(input("Enter rollno to update: "))
โŒจ๏ธ Input Shows "Enter rollno to update: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
11
marks = float(input("Enter new marks: "))
โŒจ๏ธ Input Shows "Enter new marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable marks
12
cursor.execute("UPDATE student SET marks = %s WHERE rollno = %s", (marks, roll))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (marks, roll)
13
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
14
print("Rows affected:", cursor.rowcount)
๐Ÿ–ฅ๏ธ Output Displays the text "Rows affected:", then the value of cursor.rowcount on the screen
16
elif ch == 2:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to 2
17
roll = int(input("Enter rollno to delete: "))
โŒจ๏ธ Input Shows "Enter rollno to delete: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
18
cursor.execute("DELETE FROM student WHERE rollno = %s", (roll,))
๐Ÿฌ Database Sends a DELETE query (removes rows) to MySQL through the cursor; the %s places are filled safely with the values (roll,)
19
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
20
print("Rows affected:", cursor.rowcount)
๐Ÿ–ฅ๏ธ Output Displays the text "Rows affected:", then the value of cursor.rowcount on the screen
22
conn.close()
๐Ÿงฎ Store / Calculate Closes conn

๐Ÿ“ Project Reference

PROJECT (using concepts of Classes XI & XII) โ€” File Handling / Python-Database Connectivity

Suggested titles (from the practical list): Bank Management System, Book Shop Management System,
Computer Sales & Service System, Daily Travel Booking System, Employee Management System,
Hospital Management System, Library Management System, Quiz Project.

Guidelines: work in groups of 2-3, start at least 6 months before submission, solve a REAL local
problem (e.g. a shopkeeper's GST invoicing), avoid plagiarism/copyright issues.
Deliverables: Coding + Project Report + Viva Voce.
Viva reference: https://www.tutorialaicsip.com/cs-xii/computer-science-class-12-viva-voce/

Class XII โ€” Informatics Practices (065)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 45 Practicals (incl. 6 Data Visualization) + Project

๐Ÿ“˜ View Syllabus 2026-27 0%
๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

Q1 PYTHON

Create Pandas Series from (a) an ndarray (b) a List (labeled & positional index) (c) a Dictionary (d) a Scalar value.

import pandas as pd
import numpy as np

# (a) from ndarray
arr = np.array([10, 20, 30, 40])
s1 = pd.Series(arr)
print("(a) From ndarray:\n", s1)

# (b) from List with labeled index
lst = [5, 15, 25, 35]
s2 = pd.Series(lst, index=['a', 'b', 'c', 'd'])
print("\n(b) From List (labeled index):\n", s2)
print("Positional index access s2[1]:", s2.iloc[1])

# (c) from Dictionary
d = {'Mon': 100, 'Tue': 200, 'Wed': 150}
s3 = pd.Series(d)
print("\n(c) From Dictionary:\n", s3)

# (d) from Scalar value
s4 = pd.Series(7, index=[0, 1, 2, 3])
print("\n(d) From Scalar:\n", s4)
โ–ถ Sample Output
(a) From ndarray:
 0    10
1    20
2    30
3    40
dtype: int64

(b) From List (labeled index):
 a     5
b    15
c    25
d    35
dtype: int64
Positional index access s2[1]: 15

(c) From Dictionary:
 Mon    100
Tue    200
Wed    150
dtype: int64

(d) From Scalar:
 0    7
1    7
2    7
3    7
dtype: int64
๐Ÿ’ก Explanation: A Series is a 1-D labeled array. Dictionary keys automatically become the Series index; scalar values repeat for every index given.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q1.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ (a) from ndarray
5
arr = np.array([10, 20, 30, 40])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [10, 20, 30, 40]; the result is stored in variable arr
6
s1 = pd.Series(arr)
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from arr; the result is stored in variable s1
7
print("(a) From ndarray:\n", s1)
๐Ÿ–ฅ๏ธ Output Displays the text "(a) From ndarray:", then the value of s1 on the screen
๐Ÿ“Œ (b) from List with labeled index
10
lst = [5, 15, 25, 35]
๐Ÿงฎ Store / Calculate Stores a list [5, 15, 25, 35] in variable lst
11
s2 = pd.Series(lst, index=['a', 'b', 'c', 'd'])
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from lst; the result is stored in variable s2
12
print("\n(b) From List (labeled index):\n", s2)
๐Ÿ–ฅ๏ธ Output Displays the text "(b) From List (labeled index):", then the value of s2 on the screen
13
print("Positional index access s2[1]:", s2.iloc[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Positional index access s2[1]:", then the value of s2.iloc[1] on the screen
๐Ÿ“Œ (c) from Dictionary
16
d = {'Mon': 100, 'Tue': 200, 'Wed': 150}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Mon': 100, 'Tue': 200, 'Wed': 150} in variable d
17
s3 = pd.Series(d)
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from d; the result is stored in variable s3
18
print("\n(c) From Dictionary:\n", s3)
๐Ÿ–ฅ๏ธ Output Displays the text "(c) From Dictionary:", then the value of s3 on the screen
๐Ÿ“Œ (d) from Scalar value
21
s4 = pd.Series(7, index=[0, 1, 2, 3])
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from 7; the result is stored in variable s4
22
print("\n(d) From Scalar:\n", s4)
๐Ÿ–ฅ๏ธ Output Displays the text "(d) From Scalar:", then the value of s4 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
35
arr = np.array([10, 20, 30, 40])
arr = array([10, 20, 30, 40])
46
s1 = pd.Series(arr)
s1 = Series (4 values)
57
print("(a) From ndarray:\n", s1)
(a) From ndarray:
 0    10
1    20
2    30
3    40
dtype: int64
610
lst = [5, 15, 25, 35]
lst = [5, 15, 25, 35]
711
s2 = pd.Series(lst, index=['a', 'b', 'c', 'd'])
s2 = Series (4 values)
812
print("\n(b) From List (labeled index):\n", s2)
(b) From List (labeled index):
 a     5
b    15
c    25
d    35
dtype: int64
913
print("Positional index access s2[1]:", s2.iloc[1])
Positional index access s2[1]: 15
1016
d = {'Mon': 100, 'Tue': 200, 'Wed': 150}
d = {'Mon': 100, 'Tue': 200, 'Wed': 150}
1117
s3 = pd.Series(d)
s3 = Series (3 values)
1218
print("\n(c) From Dictionary:\n", s3)
(c) From Dictionary:
 Mon    100
Tue    200
Wed    150
dtype: int64
1321
s4 = pd.Series(7, index=[0, 1, 2, 3])
s4 = Series (4 values)
1422
print("\n(d) From Scalar:\n", s4)
(d) From Scalar:
 0    7
1    7
2    7
3    7
dtype: int64
Q2 PYTHON

Perform operations on a Series: (a) Slicing (minimum 5) (b) Filtering (all relational operators).

import pandas as pd

s = pd.Series([10, 20, 30, 40, 50, 60, 70], index=list('abcdefg'))
print("Series:\n", s)

# (a) Slicing (5 examples)
print("\ns[1:4]  :\n", s[1:4])
print("\ns[:3]   :\n", s[:3])
print("\ns[-3:]  :\n", s[-3:])
print("\ns['b':'e']:\n", s['b':'e'])
print("\ns[::2]  :\n", s[::2])

# (b) Filtering with all relational operators
print("\ns > 30 :\n", s[s > 30])
print("\ns < 30 :\n", s[s < 30])
print("\ns == 30:\n", s[s == 30])
print("\ns != 30:\n", s[s != 30])
print("\ns >= 40:\n", s[s >= 40])
print("\ns <= 40:\n", s[s <= 40])
โ–ถ Sample Output
Series:
 a    10
b    20
c    30
d    40
e    50
f    60
g    70
dtype: int64

s[1:4]  :
 b    20
c    30
d    40
dtype: int64

s[:3]   :
 a    10
b    20
c    30
dtype: int64

s[-3:]  :
 e    50
f    60
g    70
dtype: int64

s['b':'e']:
 b    20
c    30
d    40
e    50
dtype: int64

s[::2]  :
 a    10
c    30
e    50
g    70
dtype: int64

s > 30 :
 d    40
e    50
f    60
g    70
dtype: int64

s < 30 :
 a    10
b    20
dtype: int64

s == 30:
 c    30
dtype: int64

s != 30:
 a    10
b    20
d    40
e    50
f    60
g    70
dtype: int64

s >= 40:
 d    40
e    50
f    60
g    70
dtype: int64

s <= 40:
 a    10
b    20
c    30
d    40
dtype: int64
๐Ÿ’ก Explanation: Slicing with labels (s['b':'e']) is INCLUSIVE of the end label, unlike positional slicing which excludes the end index.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q2.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
s = pd.Series([10, 20, 30, 40, 50, 60, 70], index=list('abcdefg'))
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from [10, 20, 30, 40, 50, 60, 70]; the result is stored in variable s
4
print("Series:\n", s)
๐Ÿ–ฅ๏ธ Output Displays the text "Series:", then the value of s on the screen
๐Ÿ“Œ (a) Slicing (5 examples)
7
print("\ns[1:4]  :\n", s[1:4])
๐Ÿ–ฅ๏ธ Output Displays the text "s[1:4] :", then the value of s[1:4] on the screen
8
print("\ns[:3]   :\n", s[:3])
๐Ÿ–ฅ๏ธ Output Displays the text "s[:3] :", then the value of s[:3] on the screen
9
print("\ns[-3:]  :\n", s[-3:])
๐Ÿ–ฅ๏ธ Output Displays the text "s[-3:] :", then the value of s[-3:] on the screen
10
print("\ns['b':'e']:\n", s['b':'e'])
๐Ÿ–ฅ๏ธ Output Displays the text "s['b':'e']:", then the value of s['b':'e'] on the screen
11
print("\ns[::2]  :\n", s[::2])
๐Ÿ–ฅ๏ธ Output Displays the text "s[::2] :", then the value of s[::2] on the screen
๐Ÿ“Œ (b) Filtering with all relational operators
14
print("\ns > 30 :\n", s[s > 30])
๐Ÿ–ฅ๏ธ Output Displays the text "s > 30 :", then the value of s[s > 30] on the screen
15
print("\ns < 30 :\n", s[s < 30])
๐Ÿ–ฅ๏ธ Output Displays the text "s < 30 :", then the value of s[s < 30] on the screen
16
print("\ns == 30:\n", s[s == 30])
๐Ÿ–ฅ๏ธ Output Displays the text "s == 30:", then the value of s[s == 30] on the screen
17
print("\ns != 30:\n", s[s != 30])
๐Ÿ–ฅ๏ธ Output Displays the text "s != 30:", then the value of s[s != 30] on the screen
18
print("\ns >= 40:\n", s[s >= 40])
๐Ÿ–ฅ๏ธ Output Displays the text "s >= 40:", then the value of s[s >= 40] on the screen
19
print("\ns <= 40:\n", s[s <= 40])
๐Ÿ–ฅ๏ธ Output Displays the text "s <= 40:", then the value of s[s <= 40] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
s = pd.Series([10, 20, 30, 40, 50, 60, 70], index=list('abcdefg'))
s = Series (7 values)
34
print("Series:\n", s)
Series:
 a    10
b    20
c    30
d    40
e    50
f    60
g    70
dtype: int64
47
print("\ns[1:4]  :\n", s[1:4])
s[1:4]  :
 b    20
c    30
d    40
dtype: int64
58
print("\ns[:3]   :\n", s[:3])
s[:3]   :
 a    10
b    20
c    30
dtype: int64
69
print("\ns[-3:]  :\n", s[-3:])
s[-3:]  :
 e    50
f    60
g    70
dtype: int64
710
print("\ns['b':'e']:\n", s['b':'e'])
s['b':'e']:
 b    20
c    30
d    40
e    50
dtype: int64
811
print("\ns[::2]  :\n", s[::2])
s[::2]  :
 a    10
c    30
e    50
g    70
dtype: int64
914
print("\ns > 30 :\n", s[s > 30])
s > 30 :
 d    40
e    50
f    60
g    70
dtype: int64
1015
print("\ns < 30 :\n", s[s < 30])
s < 30 :
 a    10
b    20
dtype: int64
1116
print("\ns == 30:\n", s[s == 30])
s == 30:
 c    30
dtype: int64
1217
print("\ns != 30:\n", s[s != 30])
s != 30:
 a    10
b    20
d    40
e    50
f    60
g    70
dtype: int64
1318
print("\ns >= 40:\n", s[s >= 40])
s >= 40:
 d    40
e    50
f    60
g    70
dtype: int64
1419
print("\ns <= 40:\n", s[s <= 40])
s <= 40:
 a    10
b    20
c    30
d    40
dtype: int64
Q3 PYTHON

Create a Series containing a dictionary of students' results (name, class, percentage, result); print elements above 75%.

import pandas as pd

results = {
    "Amit": 88.5,
    "Sara": 92.0,
    "Rahul": 65.5,
    "Priya": 78.0,
    "Karan": 55.0
}

s = pd.Series(results)
print("All Results:\n", s)
print("\nStudents scoring above 75%:\n", s[s > 75])
โ–ถ Sample Output
All Results:
 Amit     88.5
Sara     92.0
Rahul    65.5
Priya    78.0
Karan    55.0
dtype: float64

Students scoring above 75%:
 Amit     88.5
Sara     92.0
Priya    78.0
dtype: float64
๐Ÿ’ก Explanation: A Series built directly from a dictionary of {name: percentage} lets us filter with a simple boolean condition s > 75.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
results = {
    "Amit": 88.5,
    "Sara": 92.0,
    "Rahul": 65.5,
    "Priya": 78.0,
    "Karan": 55.0
}
๐Ÿงฎ Store / Calculate Stores a dictionary { "Amit": 88.5, "Sara": 92.0, "Rahul": 65.5, โ€ฆ in variable results
11
s = pd.Series(results)
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from results; the result is stored in variable s
12
print("All Results:\n", s)
๐Ÿ–ฅ๏ธ Output Displays the text "All Results:", then the value of s on the screen
13
print("\nStudents scoring above 75%:\n", s[s > 75])
๐Ÿ–ฅ๏ธ Output Displays the text "Students scoring above 75%:", then the value of s[s > 75] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
24
"Amit": 88.5,
35
"Sara": 92.0,
46
"Rahul": 65.5,
57
"Priya": 78.0,
68
"Karan": 55.0
73
results = {
results = {'Amit': 88.5, 'Sara': 92.0, 'Rahul': 65.5, 'Priya': 78.0, 'Karan':โ€ฆ
811
s = pd.Series(results)
s = Series (5 values)
912
print("All Results:\n", s)
All Results:
 Amit     88.5
Sara     92.0
Rahul    65.5
Priya    78.0
Karan    55.0
dtype: float64
1013
print("\nStudents scoring above 75%:\n", s[s > 75])
Students scoring above 75%:
 Amit     88.5
Sara     92.0
Priya    78.0
dtype: float64
Q4 PYTHON

Create Pandas DataFrame & display from (a) ndarray (b) List (labeled & positional index) (c) Dictionary (d) another DataFrame.

import pandas as pd
import numpy as np

# (a) from ndarray
arr = np.array([[1, 2], [3, 4]])
df1 = pd.DataFrame(arr, columns=['A', 'B'])
print("(a) From ndarray:\n", df1)

# (b) from List with labeled index
lst = [[10, 'Amit'], [20, 'Sara']]
df2 = pd.DataFrame(lst, columns=['Marks', 'Name'], index=['s1', 's2'])
print("\n(b) From List (labeled index):\n", df2)
print("Positional row df2.iloc[0]:\n", df2.iloc[0])

# (c) from Dictionary
d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]}
df3 = pd.DataFrame(d)
print("\n(c) From Dictionary:\n", df3)

# (d) from another DataFrame (copy)
df4 = pd.DataFrame(df3)
print("\n(d) From another DataFrame:\n", df4)
โ–ถ Sample Output
(a) From ndarray:
    A  B
0  1  2
1  3  4

(b) From List (labeled index):
     Marks  Name
s1     10  Amit
s2     20  Sara
Positional row df2.iloc[0]:
 Marks      10
Name     Amit
Name: s1, dtype: object

(c) From Dictionary:
    Name  Marks
0  Amit     88
1  Sara     92

(d) From another DataFrame:
    Name  Marks
0  Amit     88
1  Sara     92
๐Ÿ’ก Explanation: A DataFrame is a 2-D table; each construction method (array/list/dict) is common in real datasets you'll import from CSV or SQL.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ (a) from ndarray
5
arr = np.array([[1, 2], [3, 4]])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[1, 2], [3, 4]]; the result is stored in variable arr
6
df1 = pd.DataFrame(arr, columns=['A', 'B'])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from arr; the result is stored in variable df1
7
print("(a) From ndarray:\n", df1)
๐Ÿ–ฅ๏ธ Output Displays the text "(a) From ndarray:", then the value of df1 on the screen
๐Ÿ“Œ (b) from List with labeled index
10
lst = [[10, 'Amit'], [20, 'Sara']]
๐Ÿงฎ Store / Calculate Stores a list [[10, 'Amit'], [20, 'Sara']] in variable lst
11
df2 = pd.DataFrame(lst, columns=['Marks', 'Name'], index=['s1', 's2'])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from lst; the result is stored in variable df2
12
print("\n(b) From List (labeled index):\n", df2)
๐Ÿ–ฅ๏ธ Output Displays the text "(b) From List (labeled index):", then the value of df2 on the screen
13
print("Positional row df2.iloc[0]:\n", df2.iloc[0])
๐Ÿ–ฅ๏ธ Output Displays the text "Positional row df2.iloc[0]:", then the value of df2.iloc[0] on the screen
๐Ÿ“Œ (c) from Dictionary
16
d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]} in variable d
17
df3 = pd.DataFrame(d)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from d; the result is stored in variable df3
18
print("\n(c) From Dictionary:\n", df3)
๐Ÿ–ฅ๏ธ Output Displays the text "(c) From Dictionary:", then the value of df3 on the screen
๐Ÿ“Œ (d) from another DataFrame (copy)
21
df4 = pd.DataFrame(df3)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from df3; the result is stored in variable df4
22
print("\n(d) From another DataFrame:\n", df4)
๐Ÿ–ฅ๏ธ Output Displays the text "(d) From another DataFrame:", then the value of df4 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
35
arr = np.array([[1, 2], [3, 4]])
arr = array([[1, 2], [3, 4]])
46
df1 = pd.DataFrame(arr, columns=['A', 'B'])
df1 = DataFrame (2 rows ร— 2 columns)
57
print("(a) From ndarray:\n", df1)
(a) From ndarray:
    A  B
0  1  2
1  3  4
610
lst = [[10, 'Amit'], [20, 'Sara']]
lst = [[10, 'Amit'], [20, 'Sara']]
711
df2 = pd.DataFrame(lst, columns=['Marks', 'Name'], index=['s1', 's2'])
df2 = DataFrame (2 rows ร— 2 columns)
812
print("\n(b) From List (labeled index):\n", df2)
(b) From List (labeled index):
     Marks  Name
s1     10  Amit
s2     20  Sara
913
print("Positional row df2.iloc[0]:\n", df2.iloc[0])
Positional row df2.iloc[0]:
 Marks      10
Name     Amit
Name: s1, dtype: object
1016
d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]}
d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]}
1117
df3 = pd.DataFrame(d)
df3 = DataFrame (2 rows ร— 2 columns)
1218
print("\n(c) From Dictionary:\n", df3)
(c) From Dictionary:
    Name  Marks
0  Amit     88
1  Sara     92
1321
df4 = pd.DataFrame(df3)
df4 = DataFrame (2 rows ร— 2 columns)
1422
print("\n(d) From another DataFrame:\n", df4)
(d) From another DataFrame:
    Name  Marks
0  Amit     88
1  Sara     92
Q5 PYTHON

Create a DataFrame of quarterly sales (item category, item name, expenditure); group by category and print total expenditure per category.

import pandas as pd

data = {
    'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'Stationery'],
    'Item': ['TV', 'Rice', 'Fan', 'Wheat', 'Pen'],
    'Expenditure': [25000, 3000, 2000, 2500, 500]
}
df = pd.DataFrame(data)
print("Sales Data:\n", df)

grouped = df.groupby('Category')['Expenditure'].sum()
print("\nTotal Expenditure per Category:\n", grouped)
โ–ถ Sample Output
Sales Data:
       Category   Item  Expenditure
0  Electronics     TV        25000
1      Grocery   Rice         3000
2  Electronics    Fan         2000
3      Grocery  Wheat         2500
4   Stationery    Pen          500

Total Expenditure per Category:
 Category
Electronics    27000
Grocery         5500
Stationery       500
Name: Expenditure, dtype: int64
๐Ÿ’ก Explanation: groupby('Category')['Expenditure'].sum() is the core pandas pattern for category-wise totals โ€” used constantly in real business reports.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {
    'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'Stationery'],
    'Item': ['TV', 'Rice', 'Fan', 'Wheat', 'Pen'],
    'Expenditโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { 'Category': ['Electronics', 'Grocery', 'Eleโ€ฆ in variable data
8
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
9
print("Sales Data:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "Sales Data:", then the value of df on the screen
11
grouped = df.groupby('Category')['Expenditure'].sum()
๐Ÿ“ฆ Library / Data Adds up all values of df.groupby('Category')['Expenditure']; the result is stored in variable grouped
12
print("\nTotal Expenditure per Category:\n", grouped)
๐Ÿ–ฅ๏ธ Output Displays the text "Total Expenditure per Category:", then the value of grouped on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
24
'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'Stationery'],
35
'Item': ['TV', 'Rice', 'Fan', 'Wheat', 'Pen'],
46
'Expenditure': [25000, 3000, 2000, 2500, 500]
53
data = {
data = {'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'โ€ฆ
68
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 3 columns)
79
print("Sales Data:\n", df)
Sales Data:
       Category   Item  Expenditure
0  Electronics     TV        25000
1      Grocery   Rice         3000
2  Electronics    Fan         2000
3      Grocery  Wheat         2500
4   Stationery    Pen          500
811
grouped = df.groupby('Category')['Expenditure'].sum()
grouped = Series (3 values)
912
print("\nTotal Expenditure per Category:\n", grouped)
Total Expenditure per Category:
 Category
Electronics    27000
Grocery         5500
Stationery       500
Name: Expenditure, dtype: int64
Q6 PYTHON

Create a DataFrame for examination results and display row labels, column labels, data types of each column and dimensions.

import pandas as pd

data = {
    'Name': ['Amit', 'Sara', 'Rahul'],
    'Marks': [88.5, 92.0, 65.5],
    'Result': ['Pass', 'Pass', 'Pass']
}
df = pd.DataFrame(data, index=['s1', 's2', 's3'])

print("DataFrame:\n", df)
print("\nRow labels   :", df.index.tolist())
print("Column labels:", df.columns.tolist())
print("Data types   :\n", df.dtypes)
print("Dimensions   :", df.shape, " (rows, columns)")
โ–ถ Sample Output
DataFrame:
      Name  Marks Result
s1   Amit   88.5   Pass
s2   Sara   92.0   Pass
s3  Rahul   65.5   Pass

Row labels   : ['s1', 's2', 's3']
Column labels: ['Name', 'Marks', 'Result']
Data types   :
 Name       object
Marks     float64
Result     object
dtype: object
Dimensions   : (3, 3)  (rows, columns)
๐Ÿ’ก Explanation: df.index, df.columns, df.dtypes and df.shape are the four attributes every 'describe the DataFrame' question needs.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {
    'Name': ['Amit', 'Sara', 'Rahul'],
    'Marks': [88.5, 92.0, 65.5],
    'Result': ['Pass', 'Pass', 'Pass']
}
๐Ÿงฎ Store / Calculate Stores a dictionary { 'Name': ['Amit', 'Sara', 'Rahul'], 'Marks':โ€ฆ in variable data
8
df = pd.DataFrame(data, index=['s1', 's2', 's3'])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
10
print("DataFrame:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "DataFrame:", then the value of df on the screen
11
print("\nRow labels   :", df.index.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Row labels :", then the value of df.index.tolist() on the screen
12
print("Column labels:", df.columns.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Column labels:", then the value of df.columns.tolist() on the screen
13
print("Data types   :\n", df.dtypes)
๐Ÿ–ฅ๏ธ Output Displays the text "Data types :", then the value of df.dtypes on the screen
14
print("Dimensions   :", df.shape, " (rows, columns)")
๐Ÿ–ฅ๏ธ Output Displays the text "Dimensions :", then the value of df.shape, then the text "(rows, columns)" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
24
'Name': ['Amit', 'Sara', 'Rahul'],
35
'Marks': [88.5, 92.0, 65.5],
46
'Result': ['Pass', 'Pass', 'Pass']
53
data = {
data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88.5, 92.0, 65.5], 'Rโ€ฆ
68
df = pd.DataFrame(data, index=['s1', 's2', 's3'])
df = DataFrame (3 rows ร— 3 columns)
710
print("DataFrame:\n", df)
DataFrame:
      Name  Marks Result
s1   Amit   88.5   Pass
s2   Sara   92.0   Pass
s3  Rahul   65.5   Pass
811
print("\nRow labels   :", df.index.tolist())
Row labels   : ['s1', 's2', 's3']
912
print("Column labels:", df.columns.tolist())
Column labels: ['Name', 'Marks', 'Result']
1013
print("Data types   :\n", df.dtypes)
Data types   :
 Name       object
Marks     float64
Result     object
dtype: object
1114
print("Dimensions   :", df.shape, " (rows, columns)")
Dimensions   : (3, 3)  (rows, columns)
Q7 PYTHON

Filter out rows based on different criteria such as duplicate rows.

import pandas as pd

data = {
    'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'],
    'Marks': [88, 92, 88, 65, 92]
}
df = pd.DataFrame(data)
print("Original DataFrame:\n", df)

print("\nDuplicate rows:\n", df[df.duplicated()])
print("\nDataFrame without duplicates:\n", df.drop_duplicates())
print("\nRows where Marks > 70:\n", df[df['Marks'] > 70])
โ–ถ Sample Output
Original DataFrame:
     Name  Marks
0   Amit     88
1   Sara     92
2   Amit     88
3  Rahul     65
4   Sara     92

Duplicate rows:
    Name  Marks
2  Amit     88
4  Sara     92

DataFrame without duplicates:
     Name  Marks
0   Amit     88
1   Sara     92
3  Rahul     65

Rows where Marks > 70:
    Name  Marks
0  Amit     88
1  Sara     92
2  Amit     88
4  Sara     92
๐Ÿ’ก Explanation: duplicated() flags repeated rows as True; drop_duplicates() removes them, keeping the first occurrence by default.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {
    'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'],
    'Marks': [88, 92, 88, 65, 92]
}
๐Ÿงฎ Store / Calculate Stores a dictionary { 'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'โ€ฆ in variable data
7
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
8
print("Original DataFrame:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "Original DataFrame:", then the value of df on the screen
10
print("\nDuplicate rows:\n", df[df.duplicated()])
๐Ÿ–ฅ๏ธ Output Displays the text "Duplicate rows:", then the value of df[df.duplicated()] on the screen
11
print("\nDataFrame without duplicates:\n", df.drop_duplicates())
๐Ÿ–ฅ๏ธ Output Displays the text "DataFrame without duplicates:", then the value of df.drop_duplicates() on the screen
12
print("\nRows where Marks > 70:\n", df[df['Marks'] > 70])
๐Ÿ–ฅ๏ธ Output Displays the text "Rows where Marks > 70:", then the value of df[df['Marks'] > 70] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
24
'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'],
35
'Marks': [88, 92, 88, 65, 92]
43
data = {
data = {'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'], 'Marks': [88, 9โ€ฆ
57
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 2 columns)
68
print("Original DataFrame:\n", df)
Original DataFrame:
     Name  Marks
0   Amit     88
1   Sara     92
2   Amit     88
3  Rahul     65
4   Sara     92
710
print("\nDuplicate rows:\n", df[df.duplicated()])
Duplicate rows:
    Name  Marks
2  Amit     88
4  Sara     92
811
print("\nDataFrame without duplicates:\n", df.drop_duplicates())
DataFrame without duplicates:
     Name  Marks
0   Amit     88
1   Sara     92
3  Rahul     65
912
print("\nRows where Marks > 70:\n", df[df['Marks'] > 70])
Rows where Marks > 70:
    Name  Marks
0  Amit     88
1  Sara     92
2  Amit     88
4  Sara     92
Q8 PYTHON

Importing and exporting data between pandas and a CSV file.

import pandas as pd

data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]}
df = pd.DataFrame(data)

# Export to CSV
df.to_csv("students.csv", index=False)
print("Data exported to students.csv")

# Import from CSV
df2 = pd.read_csv("students.csv")
print("\nData imported back:\n", df2)
โ–ถ Sample Output
Data exported to students.csv

Data imported back:
     Name  Marks
0   Amit     88
1   Sara     92
2  Rahul     65
๐Ÿ’ก Explanation: to_csv(index=False) avoids writing an extra unnamed index column; read_csv() reconstructs the DataFrame from disk.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': โ€ฆ in variable data
4
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
๐Ÿ“Œ Export to CSV
7
df.to_csv("students.csv", index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "students.csv"
8
print("Data exported to students.csv")
๐Ÿ–ฅ๏ธ Output Displays the text "Data exported to students.csv" on the screen
๐Ÿ“Œ Import from CSV
11
df2 = pd.read_csv("students.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "students.csv" into a DataFrame (table); the result is stored in variable df2
12
print("\nData imported back:\n", df2)
๐Ÿ–ฅ๏ธ Output Displays the text "Data imported back:", then the value of df2 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]}
data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]}
34
df = pd.DataFrame(data)
df = DataFrame (3 rows ร— 2 columns)
47
df.to_csv("students.csv", index=False)
58
print("Data exported to students.csv")
Data exported to students.csv
611
df2 = pd.read_csv("students.csv")
df2 = DataFrame (3 rows ร— 2 columns)
712
print("\nData imported back:\n", df2)
Data imported back:
     Name  Marks
0   Amit     88
1   Sara     92
2  Rahul     65
Q9 PYTHON

Given the school result data, analyse the performance of students on different parameters (e.g., subject-wise or class-wise).

import pandas as pd

data = {
    'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'],
    'Subject': ['CS', 'IP', 'CS', 'IP'],
    'Average': [82, 78, 75, 88]
}
df = pd.DataFrame(data)
print(df)

print("\nClass-wise average:\n", df.groupby('Class')['Average'].mean())
print("\nSubject-wise average:\n", df.groupby('Subject')['Average'].mean())
print("\nBest performing class-subject combo:\n", df.loc[df['Average'].idxmax()])
โ–ถ Sample Output
   Class Subject  Average
0  XII-A      CS       82
1  XII-A      IP       78
2  XII-B      CS       75
3  XII-B      IP       88

Class-wise average:
 Class
XII-A    80.0
XII-B    81.5
Name: Average, dtype: float64

Subject-wise average:
 Subject
CS    78.5
IP    83.0
Name: Average, dtype: float64

Best performing class-subject combo:
 Class      XII-B
Subject       IP
Average       88
Name: 3, dtype: object
๐Ÿ’ก Explanation: idxmax() returns the index of the row with the maximum value โ€” handy for finding a top performer.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {
    'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'],
    'Subject': ['CS', 'IP', 'CS', 'IP'],
    'Average': [82, 78, 75, 88]
}
๐Ÿงฎ Store / Calculate Stores a dictionary { 'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-Bโ€ฆ in variable data
8
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
9
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
11
print("\nClass-wise average:\n", df.groupby('Class')['Average'].mean())
๐Ÿ–ฅ๏ธ Output Displays the text "Class-wise average:", then the value of df.groupby('Class')['Average'].mean() on the screen
12
print("\nSubject-wise average:\n", df.groupby('Subject')['Average'].mean())
๐Ÿ–ฅ๏ธ Output Displays the text "Subject-wise average:", then the value of df.groupby('Subject')['Average'].mean() on the screen
13
print("\nBest performing class-subject combo:\n", df.loc[df['Average'].idxmax()])
๐Ÿ–ฅ๏ธ Output Displays the text "Best performing class-subject comโ€ฆ", then the value of df.loc[df['Average'].idxmax()] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
24
'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'],
35
'Subject': ['CS', 'IP', 'CS', 'IP'],
46
'Average': [82, 78, 75, 88]
53
data = {
data = {'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'], 'Subject': ['CS', 'โ€ฆ
68
df = pd.DataFrame(data)
df = DataFrame (4 rows ร— 3 columns)
79
print(df)
   Class Subject  Average
0  XII-A      CS       82
1  XII-A      IP       78
2  XII-B      CS       75
3  XII-B      IP       88
811
print("\nClass-wise average:\n", df.groupby('Class')['Average'].mean())
Class-wise average:
 Class
XII-A    80.0
XII-B    81.5
Name: Average, dtype: float64
912
print("\nSubject-wise average:\n", df.groupby('Subject')['Average'].mean())
Subject-wise average:
 Subject
CS    78.5
IP    83.0
Name: Average, dtype: float64
1013
print("\nBest performing class-subject combo:\n", df.loc[df['Average'].idxmax()])
Best performing class-subject combo:
 Class      XII-B
Subject       IP
Average       88
Name: 3, dtype: object
Q10 PYTHON

For the DataFrames created above, analyse and plot appropriate charts with title and legend.

import pandas as pd
import matplotlib.pyplot as plt

data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditure': [27000, 5500, 500]}
df = pd.DataFrame(data)

df.plot(kind='bar', x='Category', y='Expenditure', legend=True,
        title='Quarterly Expenditure by Category', color='orange')
plt.xlabel("Category")
plt.ylabel("Expenditure (Rs.)")
plt.tight_layout()
plt.savefig("expenditure_chart.png")
plt.show()
โ–ถ Sample Output
๐Ÿ’ก Explanation: df.plot(kind='bar') is pandas' built-in charting shortcut (uses matplotlib internally) โ€” title/legend/labels make it exam-complete.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditure': [27000, 5500, 500]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Category': ['Electronics', 'Grocery', 'Statโ€ฆ in variable data
5
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
7
df.plot(kind='bar', x='Category', y='Expenditure', legend=True,
        title='Quarterly Expenditure by Category', color='orange')
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
9
plt.xlabel("Category")
๐Ÿ–ฅ๏ธ Output Writes "Category" as the label of the X-axis
10
plt.ylabel("Expenditure (Rs.)")
๐Ÿ–ฅ๏ธ Output Writes "Expenditure (Rs.)" as the label of the Y-axis
11
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
12
plt.savefig("expenditure_chart.png")
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "expenditure_chart.png"
13
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
34
data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditure': [27000, 5500,
data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditureโ€ฆ
45
df = pd.DataFrame(data)
df = DataFrame (3 rows ร— 2 columns)
57
df.plot(kind='bar', x='Category', y='Expenditure', legend=True,
68
title='Quarterly Expenditure by Category', color='orange')
77
df.plot(kind='bar', x='Category', y='Expenditure', legend=True,
89
plt.xlabel("Category")
910
plt.ylabel("Expenditure (Rs.)")
1011
plt.tight_layout()
1112
plt.savefig("expenditure_chart.png")
1213
plt.show()
Q11 PYTHON

Take data of your interest from an open source (e.g. data.gov.in), aggregate & summarize it, then plot using Matplotlib.

import pandas as pd
import matplotlib.pyplot as plt

# Sample dataset (replace with a CSV downloaded from data.gov.in)
data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'],
        'Literacy_Rate': [86.2, 67.7, 82.3, 96.2]}
df = pd.DataFrame(data)

print("Summary statistics:\n", df['Literacy_Rate'].describe())

plt.bar(df['State'], df['Literacy_Rate'], color='navy')
plt.title("State-wise Literacy Rate")
plt.xlabel("State")
plt.ylabel("Literacy Rate (%)")
plt.tight_layout()
plt.show()
โ–ถ Sample Output
Summary statistics:
 count     4.000000
mean     83.100000
std      11.818347
min      67.700000
25%      78.650000
50%      84.250000
75%      88.700000
max      96.200000
Name: Literacy_Rate, dtype: float64
๐Ÿ’ก Explanation: describe() gives count/mean/std/min/max in one call โ€” the standard first step of any real dataset analysis.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
๐Ÿ“Œ Sample dataset (replace with a CSV downloaded from data.gov.in)
5
data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'],
        'Literacy_Rate': [86.2, 67.7, 82.3, 96.2]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerโ€ฆ in variable data
7
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
9
print("Summary statistics:\n", df['Literacy_Rate'].describe())
๐Ÿ–ฅ๏ธ Output Displays the text "Summary statistics:", then the value of df['Literacy_Rate'].describe() on the screen
11
plt.bar(df['State'], df['Literacy_Rate'], color='navy')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of df['State'], df['Literacy_Rate']
12
plt.title("State-wise Literacy Rate")
๐Ÿ–ฅ๏ธ Output Writes "State-wise Literacy Rate" as the title of the chart
13
plt.xlabel("State")
๐Ÿ–ฅ๏ธ Output Writes "State" as the label of the X-axis
14
plt.ylabel("Literacy Rate (%)")
๐Ÿ–ฅ๏ธ Output Writes "Literacy Rate (%)" as the label of the Y-axis
15
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
16
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
35
data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'],
46
'Literacy_Rate': [86.2, 67.7, 82.3, 96.2]}
55
data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'],
data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'], 'Literacy_Rate'โ€ฆ
67
df = pd.DataFrame(data)
df = DataFrame (4 rows ร— 2 columns)
79
print("Summary statistics:\n", df['Literacy_Rate'].describe())
Summary statistics:
 count     4.000000
mean     83.100000
std      11.818347
min      67.700000
25%      78.650000
50%      84.250000
75%      88.700000
max      96.200000
Name: Literacy_Rate, dtype: float64
811
plt.bar(df['State'], df['Literacy_Rate'], color='navy')
912
plt.title("State-wise Literacy Rate")
1013
plt.xlabel("State")
1114
plt.ylabel("Literacy Rate (%)")
1215
plt.tight_layout()
1316
plt.show()
Q12 PYTHON

Locate the 3 largest values in a DataFrame.

import pandas as pd

df = pd.DataFrame({'Marks': [55, 88, 92, 65, 78, 99]})
print("DataFrame:\n", df)

print("\n3 Largest values:\n", df['Marks'].nlargest(3))
โ–ถ Sample Output
DataFrame:
    Marks
0     55
1     88
2     92
3     65
4     78
5     99

3 Largest values:
 5    99
2    92
1    88
Name: Marks, dtype: int64
๐Ÿ’ก Explanation: nlargest(n) is far more efficient than sort_values() + head() for just picking the top few values.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
df = pd.DataFrame({'Marks': [55, 88, 92, 65, 78, 99]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'Marks': [55, 88, 92, 65, 78, 99]}; the result is stored in variable df
4
print("DataFrame:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "DataFrame:", then the value of df on the screen
6
print("\n3 Largest values:\n", df['Marks'].nlargest(3))
๐Ÿ–ฅ๏ธ Output Displays the text "3 Largest values:", then the value of df['Marks'].nlargest(3) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
df = pd.DataFrame({'Marks': [55, 88, 92, 65, 78, 99]})
df = DataFrame (6 rows ร— 1 columns)
34
print("DataFrame:\n", df)
DataFrame:
    Marks
0     55
1     88
2     92
3     65
4     78
5     99
46
print("\n3 Largest values:\n", df['Marks'].nlargest(3))
3 Largest values:
 5    99
2    92
1    88
Name: Marks, dtype: int64
Q13 PYTHON

Subtract the mean of a row from each element of that row in a DataFrame.

import pandas as pd

df = pd.DataFrame({'Q1': [10, 20, 30], 'Q2': [15, 25, 35], 'Q3': [20, 30, 40]})
print("Original:\n", df)

result = df.sub(df.mean(axis=1), axis=0)
print("\nAfter subtracting row mean:\n", result)
โ–ถ Sample Output
Original:
    Q1  Q2  Q3
0  10  15  20
1  20  25  30
2  30  35  40

After subtracting row mean:
     Q1   Q2   Q3
0 -5.0  0.0  5.0
1 -5.0  0.0  5.0
2 -5.0  0.0  5.0
๐Ÿ’ก Explanation: axis=1 in mean() computes across columns (row-wise mean); axis=0 in sub() aligns the subtraction per row.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
df = pd.DataFrame({'Q1': [10, 20, 30], 'Q2': [15, 25, 35], 'Q3': [20, 30, 40]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'Q1': [10, 20, 30], 'Q2': [15, 25, 35], 'Q3'โ€ฆ; the result is stored in variable df
4
print("Original:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "Original:", then the value of df on the screen
6
result = df.sub(df.mean(axis=1), axis=0)
๐Ÿ“ฆ Library / Data Calls df.sub(df.mean(axis=1)); the result is stored in variable result
7
print("\nAfter subtracting row mean:\n", result)
๐Ÿ–ฅ๏ธ Output Displays the text "After subtracting row mean:", then the value of result on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
df = pd.DataFrame({'Q1': [10, 20, 30], 'Q2': [15, 25, 35], 'Q3': [20, 30, 40]})
df = DataFrame (3 rows ร— 3 columns)
34
print("Original:\n", df)
Original:
    Q1  Q2  Q3
0  10  15  20
1  20  25  30
2  30  35  40
46
result = df.sub(df.mean(axis=1), axis=0)
result = DataFrame (3 rows ร— 3 columns)
57
print("\nAfter subtracting row mean:\n", result)
After subtracting row mean:
     Q1   Q2   Q3
0 -5.0  0.0  5.0
1 -5.0  0.0  5.0
2 -5.0  0.0  5.0
Q14 PYTHON

Replace all negative values with 0 in a DataFrame.

import pandas as pd

df = pd.DataFrame({'A': [10, -5, 20, -8], 'B': [-3, 15, -1, 9]})
print("Original:\n", df)

df[df < 0] = 0
print("\nAfter replacing negatives with 0:\n", df)
โ–ถ Sample Output
Original:
     A   B
0  10  -3
1  -5  15
2  20  -1
3  -8   9

After replacing negatives with 0:
     A   B
0  10   0
1   0  15
2  20   0
3   0   9
๐Ÿ’ก Explanation: Boolean indexing df[df < 0] = 0 replaces ALL matching cells in one line โ€” no loop needed.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
df = pd.DataFrame({'A': [10, -5, 20, -8], 'B': [-3, 15, -1, 9]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'A': [10, -5, 20, -8], 'B': [-3, 15, -1, 9]}; the result is stored in variable df
4
print("Original:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "Original:", then the value of df on the screen
6
df[df < 0] = 0
๐Ÿงฎ Store / Calculate Puts the number 0 into df[df < 0] (item df < 0 of df)
7
print("\nAfter replacing negatives with 0:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "After replacing negatives with 0:", then the value of df on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
df = pd.DataFrame({'A': [10, -5, 20, -8], 'B': [-3, 15, -1, 9]})
df = DataFrame (4 rows ร— 2 columns)
34
print("Original:\n", df)
Original:
     A   B
0  10  -3
1  -5  15
2  20  -1
3  -8   9
46
df[df < 0] = 0
57
print("\nAfter replacing negatives with 0:\n", df)
After replacing negatives with 0:
     A   B
0  10   0
1   0  15
2  20   0
3   0   9
Q15 PYTHON

Replace all missing values with 999 in a DataFrame.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [10, np.nan, 20], 'B': [np.nan, 15, 25]})
print("Original:\n", df)

df = df.fillna(999)
print("\nAfter replacing NaN with 999:\n", df)
โ–ถ Sample Output
Original:
       A     B
0  10.0   NaN
1   NaN  15.0
2  20.0  25.0

After replacing NaN with 999:
        A      B
0   10.0  999.0
1  999.0   15.0
2   20.0   25.0
๐Ÿ’ก Explanation: fillna() is the standard pandas method for handling missing (NaN) data โ€” extremely common in real datasets.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
4
df = pd.DataFrame({'A': [10, np.nan, 20], 'B': [np.nan, 15, 25]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'A': [10, np.nan, 20], 'B': [np.nan, 15, 25]}; the result is stored in variable df
5
print("Original:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "Original:", then the value of df on the screen
7
df = df.fillna(999)
๐Ÿ“ฆ Library / Data Fills the missing (NaN) values of df with 999; the result is stored in variable df
8
print("\nAfter replacing NaN with 999:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "After replacing NaN with 999:", then the value of df on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
34
df = pd.DataFrame({'A': [10, np.nan, 20], 'B': [np.nan, 15, 25]})
df = DataFrame (3 rows ร— 2 columns)
45
print("Original:\n", df)
Original:
       A     B
0  10.0   NaN
1   NaN  15.0
2  20.0  25.0
57
df = df.fillna(999)
68
print("\nAfter replacing NaN with 999:\n", df)
After replacing NaN with 999:
        A      B
0   10.0  999.0
1  999.0   15.0
2   20.0   25.0
Q16 PYTHON

Given df = {'Mouse':[150,200,300,400],'Keyboard':[180,200,190,300],'Scanner':[200,280,330,450]} indexed Jan-April โ€” answer 6 sub-parts.

import pandas as pd

d = {'Mouse':[150,200,300,400], 'Keyboard':[180,200,190,300], 'Scanner':[200,280,330,450]}
df = pd.DataFrame(d, index=['Jan','Feb','March','April'])
print(df)

# A. Access data of Mouse and Scanner columns
print("\nA.\n", df[['Mouse','Scanner']])

# B. Access Keyboard column using dot notation
print("\nB.\n", df.Keyboard)

# C. Access Scanner data using loc[]
print("\nC.\n", df.loc[:, 'Scanner'])

# D. All columns where Mouse data is more than 200
print("\nD.\n", df[df['Mouse'] > 200])

# E. Access columns using integer positions 0 and 2
print("\nE.\n", df.iloc[:, [0, 2]])

# F. Rows of Jan and March for Scanner and Keyboard
print("\nF.\n", df.loc[['Jan','March'], ['Scanner','Keyboard']])
โ–ถ Sample Output
       Mouse  Keyboard  Scanner
Jan      150       180      200
Feb      200       200      280
March    300       190      330
April    400       300      450

A.
        Mouse  Scanner
Jan      150      200
Feb      200      280
March    300      330
April    400      450

B.
 Jan      180
Feb      200
March    190
April    300
Name: Keyboard, dtype: int64

C.
 Jan      200
Feb      280
March    330
April    450
Name: Scanner, dtype: int64

D.
        Mouse  Keyboard  Scanner
March    300       190      330
April    400       300      450

E.
        Mouse  Scanner
Jan      150      200
Feb      200      280
March    300      330
April    400      450

F.
        Scanner  Keyboard
Jan        200       180
March      330       190
๐Ÿ’ก Explanation: Part B fixes the original typo 'df.Keybaord' to the correct 'df.Keyboard' โ€” dot notation only works when the column name has no spaces/special characters.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
d = {'Mouse':[150,200,300,400], 'Keyboard':[180,200,190,300], 'Scanner':[200,280,330,450]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Mouse':[150,200,300,400], 'Keyboard':[180,2โ€ฆ in variable d
4
df = pd.DataFrame(d, index=['Jan','Feb','March','April'])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from d; the result is stored in variable df
5
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
๐Ÿ“Œ A. Access data of Mouse and Scanner columns
8
print("\nA.\n", df[['Mouse','Scanner']])
๐Ÿ–ฅ๏ธ Output Displays the text "A.", then the value of df[['Mouse','Scanner']] on the screen
๐Ÿ“Œ B. Access Keyboard column using dot notation
11
print("\nB.\n", df.Keyboard)
๐Ÿ–ฅ๏ธ Output Displays the text "B.", then the value of df.Keyboard on the screen
๐Ÿ“Œ C. Access Scanner data using loc[]
14
print("\nC.\n", df.loc[:, 'Scanner'])
๐Ÿ–ฅ๏ธ Output Displays the text "C.", then the value of df.loc[:, 'Scanner'] on the screen
๐Ÿ“Œ D. All columns where Mouse data is more than 200
17
print("\nD.\n", df[df['Mouse'] > 200])
๐Ÿ–ฅ๏ธ Output Displays the text "D.", then the value of df[df['Mouse'] > 200] on the screen
๐Ÿ“Œ E. Access columns using integer positions 0 and 2
20
print("\nE.\n", df.iloc[:, [0, 2]])
๐Ÿ–ฅ๏ธ Output Displays the text "E.", then the value of df.iloc[:, [0, 2]] on the screen
๐Ÿ“Œ F. Rows of Jan and March for Scanner and Keyboard
23
print("\nF.\n", df.loc[['Jan','March'], ['Scanner','Keyboard']])
๐Ÿ–ฅ๏ธ Output Displays the text "F.", then the value of df.loc[['Jan','March'], ['Scanner','Keyboard'โ€ฆ on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
d = {'Mouse':[150,200,300,400], 'Keyboard':[180,200,190,300], 'Scanner':[200,280,330,450]}
d = {'Mouse': [150, 200, 300, 400], 'Keyboard': [180, 200, 190, 300], 'โ€ฆ
34
df = pd.DataFrame(d, index=['Jan','Feb','March','April'])
df = DataFrame (4 rows ร— 3 columns)
45
print(df)
       Mouse  Keyboard  Scanner
Jan      150       180      200
Feb      200       200      280
March    300       190      330
April    400       300      450
58
print("\nA.\n", df[['Mouse','Scanner']])
A.
        Mouse  Scanner
Jan      150      200
Feb      200      280
March    300      330
April    400      450
611
print("\nB.\n", df.Keyboard)
B.
 Jan      180
Feb      200
March    190
April    300
Name: Keyboard, dtype: int64
714
print("\nC.\n", df.loc[:, 'Scanner'])
C.
 Jan      200
Feb      280
March    330
April    450
Name: Scanner, dtype: int64
817
print("\nD.\n", df[df['Mouse'] > 200])
D.
        Mouse  Keyboard  Scanner
March    300       190      330
April    400       300      450
920
print("\nE.\n", df.iloc[:, [0, 2]])
E.
        Mouse  Scanner
Jan      150      200
Feb      200      280
March    300      330
April    400      450
1023
print("\nF.\n", df.loc[['Jan','March'], ['Scanner','Keyboard']])
F.
        Scanner  Keyboard
Jan        200       180
March      330       190
Q17 PYTHON

Create a DataFrame using lists (books data); display Class XII books, books priced above 250, and plot a line chart.

import pandas as pd
import matplotlib.pyplot as plt

books = {
    'BookName': ['Informatics Practices', 'Computer Science', 'Physics', 'Chemistry'],
    'Class': [12, 12, 11, 11],
    'Price': [320, 280, 240, 260]
}
df = pd.DataFrame(books)
print(df)

# 1. Display books for Class XII
print("\nClass XII books:\n", df[df['Class'] == 12])

# 2. Books priced more than 250
print("\nBooks priced > 250:\n", df[df['Price'] > 250])

# 3. Line chart
df.plot(kind='line', x='BookName', y='Price', marker='o', title='Book Price Trend')
plt.tight_layout()
plt.show()
โ–ถ Sample Output
                BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280
2                Physics     11    240
3              Chemistry     11    260

Class XII books:
                 BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280

Books priced > 250:
                 BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280
3              Chemistry     11    260
๐Ÿ’ก Explanation: Boolean masks df['Class']==12 and df['Price']>250 answer the two filtering sub-parts; plot(kind='line') draws the chart.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
books = {
    'BookName': ['Informatics Practices', 'Computer Science', 'Physics', 'Chemistry'],
    'Class': [12, 12, 11, 11],
    'Price': [320, 280, 240, โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { 'BookName': ['Informatics Practices', 'Compโ€ฆ in variable books
9
df = pd.DataFrame(books)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from books; the result is stored in variable df
10
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
๐Ÿ“Œ 1. Display books for Class XII
13
print("\nClass XII books:\n", df[df['Class'] == 12])
๐Ÿ–ฅ๏ธ Output Displays the text "Class XII books:", then the value of df[df['Class'] == 12] on the screen
๐Ÿ“Œ 2. Books priced more than 250
16
print("\nBooks priced > 250:\n", df[df['Price'] > 250])
๐Ÿ–ฅ๏ธ Output Displays the text "Books priced > 250:", then the value of df[df['Price'] > 250] on the screen
๐Ÿ“Œ 3. Line chart
19
df.plot(kind='line', x='BookName', y='Price', marker='o', title='Book Price Trend')
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
20
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
21
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
35
'BookName': ['Informatics Practices', 'Computer Science', 'Physics', 'Chemistry'],
46
'Class': [12, 12, 11, 11],
57
'Price': [320, 280, 240, 260]
64
books = {
books = {'BookName': ['Informatics Practices', 'Computer Science', 'Physicsโ€ฆ
79
df = pd.DataFrame(books)
df = DataFrame (4 rows ร— 3 columns)
810
print(df)
                BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280
2                Physics     11    240
3              Chemistry     11    260
913
print("\nClass XII books:\n", df[df['Class'] == 12])
Class XII books:
                 BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280
1016
print("\nBooks priced > 250:\n", df[df['Price'] > 250])
Books priced > 250:
                 BookName  Class  Price
0  Informatics Practices     12    320
1       Computer Science     12    280
3              Chemistry     11    260
1119
df.plot(kind='line', x='BookName', y='Price', marker='o', title='Book Price Trend')
1220
plt.tight_layout()
1321
plt.show()
Q18 PYTHON

Country/Population/BirthRate DataFrame โ€” display China & India data, Brazil & Pakistan columns, export CSV, plot bar chart.

import pandas as pd
import matplotlib.pyplot as plt

data = {
    'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'],
    'Population': [1412, 1408, 215, 231, 331],   # in millions
    'BirthRate': [10.6, 16.4, 13.6, 27.5, 12.0]
}
df = pd.DataFrame(data)
print(df)

# 1. Complete data for China and India
print("\nChina & India:\n", df[df['Country'].isin(['China', 'India'])])

# 2. Country, Population, BirthRate of Brazil and Pakistan
print("\nBrazil & Pakistan:\n", df[df['Country'].isin(['Brazil', 'Pakistan'])][['Country','Population','BirthRate']])

# 3. Export to CSV
df.to_csv("country_data.csv", index=False)

# 4. Bar chart: Country vs Population
plt.bar(df['Country'], df['Population'], color='green')
plt.title("Country vs Population")
plt.xlabel("Country")
plt.ylabel("Population (millions)")
plt.grid(axis='y')
plt.tight_layout()
plt.show()
โ–ถ Sample Output
    Country  Population  BirthRate
0     China        1412       10.6
1     India        1408       16.4
2    Brazil         215       13.6
3  Pakistan         231       27.5
4       USA         331       12.0

China & India:
   Country  Population  BirthRate
0   China        1412       10.6
1   India        1408       16.4

Brazil & Pakistan:
     Country  Population  BirthRate
2    Brazil         215       13.6
3  Pakistan         231       27.5
๐Ÿ’ก Explanation: isin() is the cleanest way to filter rows matching MULTIPLE specific values in one column.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
data = {
    'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'],
    'Population': [1412, 1408, 215, 231, 331],   # in millions
    'BirthRate': [10.โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { 'Country': ['China', 'India', 'Brazil', 'Paโ€ฆ in variable data
9
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
10
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
๐Ÿ“Œ 1. Complete data for China and India
13
print("\nChina & India:\n", df[df['Country'].isin(['China', 'India'])])
๐Ÿ–ฅ๏ธ Output Displays the text "China & India:", then the value of df[df['Country'].isin(['China', 'India'])] on the screen
๐Ÿ“Œ 2. Country, Population, BirthRate of Brazil and Pakistan
16
print("\nBrazil & Pakistan:\n", df[df['Country'].isin(['Brazil', 'Pakistan'])][['Country','Population','BirthRate']])
๐Ÿ–ฅ๏ธ Output Displays the text "Brazil & Pakistan:", then the value of df[df['Country'].isin(['Brazil', 'Pakistan'])โ€ฆ on the screen
๐Ÿ“Œ 3. Export to CSV
19
df.to_csv("country_data.csv", index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "country_data.csv"
๐Ÿ“Œ 4. Bar chart: Country vs Population
22
plt.bar(df['Country'], df['Population'], color='green')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of df['Country'], df['Population']
23
plt.title("Country vs Population")
๐Ÿ–ฅ๏ธ Output Writes "Country vs Population" as the title of the chart
24
plt.xlabel("Country")
๐Ÿ–ฅ๏ธ Output Writes "Country" as the label of the X-axis
25
plt.ylabel("Population (millions)")
๐Ÿ–ฅ๏ธ Output Writes "Population (millions)" as the label of the Y-axis
26
plt.grid(axis='y')
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
27
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
28
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
35
'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'],
46
'Population': [1412, 1408, 215, 231, 331],   # in millions
57
'BirthRate': [10.6, 16.4, 13.6, 27.5, 12.0]
64
data = {
data = {'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'], 'Populโ€ฆ
79
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 3 columns)
810
print(df)
    Country  Population  BirthRate
0     China        1412       10.6
1     India        1408       16.4
2    Brazil         215       13.6
3  Pakistan         231       27.5
4       USA         331       12.0
913
print("\nChina & India:\n", df[df['Country'].isin(['China', 'India'])])
China & India:
   Country  Population  BirthRate
0   China        1412       10.6
1   India        1408       16.4
1016
print("\nBrazil & Pakistan:\n", df[df['Country'].isin(['Brazil', 'Pakistan'])][['Country',
Brazil & Pakistan:
     Country  Population  BirthRate
2    Brazil         215       13.6
3  Pakistan         231       27.5
1119
df.to_csv("country_data.csv", index=False)
1222
plt.bar(df['Country'], df['Population'], color='green')
1323
plt.title("Country vs Population")
1424
plt.xlabel("Country")
1525
plt.ylabel("Population (millions)")
1626
plt.grid(axis='y')
1727
plt.tight_layout()
1828
plt.show()
Q19 SQL

SQL: To create a school database and access it.

CREATE DATABASE school;
USE school;
SHOW DATABASES;
โ–ถ Sample Output
mysql> CREATE DATABASE school;
Query OK, 1 row affected (0.00 sec)

mysql> USE school;
Database changed

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
๐Ÿ’ก Explanation: Same foundation command as Class XI โ€” every SQL practical starts by creating/selecting the database.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. The code selects the database with USE school; - MySQL replies Database changed.
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE DATABASE school;

Creates a new, empty database (a folder for tables) named school.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
2
Command
USE school;

Selects the database school - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
3
Query ยท read only
SHOW DATABASES;

Lists all the databases on the MySQL server.

โœ” Result: 5 rows in set
Q20 SQL

SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key).

CREATE TABLE student (
    student_id INT PRIMARY KEY,
    class      INT,
    section    CHAR(1),
    gender     CHAR(1),
    name       VARCHAR(30),
    dob        DATE,
    marks      DECIMAL(5,2),
    email      VARCHAR(40)
);
DESC student;
โ–ถ Sample Output
mysql> CREATE TABLE student (
    ->     student_id INT PRIMARY KEY,
    ->     class      INT,
    ->     section    CHAR(1),
    ->     gender     CHAR(1),
    ->     name       VARCHAR(30),
    ->     dob        DATE,
    ->     marks      DECIMAL(5,2),
    ->     email      VARCHAR(40)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> DESC student;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int          | NO   | PRI | NULL    |       |
| class      | int          | YES  |     | NULL    |       |
| section    | char(1)      | YES  |     | NULL    |       |
| gender     | char(1)      | YES  |     | NULL    |       |
| name       | varchar(30)  | YES  |     | NULL    |       |
| dob        | date         | YES  |     | NULL    |       |
| marks      | decimal(5,2) | YES  |     | NULL    |       |
| email      | varchar(40)  | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
๐Ÿ’ก Explanation: Identical table structure as XI โ€” Class XII builds MySQL functions and joins on top of this same base table.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE TABLE student (
    student_id INT PRIMARY KEY,
    class      INT,
    section    CHAR(1),
    gender     CHAR(1),
    name       VARCHAR(30),
    dob        DATE,
    marks      DECIMAL(5,2),
    email      VARCHAR(40)
);

Creates a new table student with 8 columns. Each column gets a name and a data type:

  • student_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • class โ†’ INT (whole numbers)
  • section โ†’ CHAR(1) (text up to 1 characters)
  • gender โ†’ CHAR(1) (text up to 1 characters)
  • name โ†’ VARCHAR(30) (text up to 30 characters)
  • dob โ†’ DATE (date (YYYY-MM-DD))
  • marks โ†’ DECIMAL(5,2) (decimal number, 5 digits in all with 2 after the point)
  • email โ†’ VARCHAR(40) (text up to 40 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
2
Query ยท read only
DESC student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 8 rows in set
Q21 SQL

SQL: To insert the details of at least 10 students in the above table.

INSERT INTO student VALUES (1,12,'A','M','Amit Kumar','2008-05-14',88.5,'amit@kvsb.in');
INSERT INTO student VALUES (2,12,'B','F','Sara Khan','2008-08-21',92.0,'sara@kvsb.in');
INSERT INTO student VALUES (3,12,'A','M','Rahul Sharma','2007-12-02',65.5,'rahul@kvsb.in');
INSERT INTO student VALUES (4,12,'A','F','Priya Singh','2008-03-11',78.0,'priya@kvsb.in');
INSERT INTO student VALUES (5,12,'B','M','Anand Verma','2008-07-19',55.0,'anand@kvsb.in');
INSERT INTO student VALUES (6,12,'A','F','Angad Kaur','2008-01-25',81.0,'angad@kvsb.in');
INSERT INTO student VALUES (7,12,'B','M','Vivek Yadav','2007-11-30',48.0,'vivek@kvsb.in');
INSERT INTO student VALUES (8,12,'A','F','Neha Gupta','2008-09-09',95.0,'neha@kvsb.in');
INSERT INTO student VALUES (9,12,'B','M','Karan Mehta','2008-04-17',60.0,'karan@kvsb.in');
INSERT INTO student VALUES (10,12,'A','F','Divya Rao','2007-10-05',73.5,'divya@kvsb.in');
โ–ถ Sample Output
mysql> INSERT INTO student VALUES (1,12,'A','M','Amit Kumar','2008-05-14',88.5,'amit@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (2,12,'B','F','Sara Khan','2008-08-21',92.0,'sara@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (3,12,'A','M','Rahul Sharma','2007-12-02',65.5,'rahul@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (4,12,'A','F','Priya Singh','2008-03-11',78.0,'priya@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (5,12,'B','M','Anand Verma','2008-07-19',55.0,'anand@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (6,12,'A','F','Angad Kaur','2008-01-25',81.0,'angad@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (7,12,'B','M','Vivek Yadav','2007-11-30',48.0,'vivek@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (8,12,'A','F','Neha Gupta','2008-09-09',95.0,'neha@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (9,12,'B','M','Karan Mehta','2008-04-17',60.0,'karan@kvsb.in');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO student VALUES (10,12,'A','F','Divya Rao','2007-10-05',73.5,'divya@kvsb.in');
Query OK, 1 row affected (0.00 sec)
๐Ÿ’ก Explanation: Match column order to CREATE TABLE order exactly; dates always in 'YYYY-MM-DD' quoted format.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DML ยท data change
INSERT INTO student VALUES (1,12,'A','M','Amit Kumar','2008-05-14',88.5,'amit@kvsb.in');
โ€ฆ (9 more INSERT statements of the same kind)

These 10 INSERT statements add 10 rows, one row each, into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: each INSERT says "Query OK, 1 row affected"
Q22 SQL

SQL: To display the entire content of the table.

SELECT * FROM student;
โ–ถ Sample Output
mysql> SELECT * FROM student;
+------------+-------+---------+--------+--------------+------------+-------+---------------+
| student_id | class | section | gender | name         | dob        | marks | email         |
+------------+-------+---------+--------+--------------+------------+-------+---------------+
|          1 |    12 | A       | M      | Amit Kumar   | 2008-05-14 | 88.50 | amit@kvsb.in  |
|          2 |    12 | B       | F      | Sara Khan    | 2008-08-21 | 92.00 | sara@kvsb.in  |
|          3 |    12 | A       | M      | Rahul Sharma | 2007-12-02 | 65.50 | rahul@kvsb.in |
|          4 |    12 | A       | F      | Priya Singh  | 2008-03-11 | 78.00 | priya@kvsb.in |
|          5 |    12 | B       | M      | Anand Verma  | 2008-07-19 | 55.00 | anand@kvsb.in |
|          6 |    12 | A       | F      | Angad Kaur   | 2008-01-25 | 81.00 | angad@kvsb.in |
|          7 |    12 | B       | M      | Vivek Yadav  | 2007-11-30 | 48.00 | vivek@kvsb.in |
|          8 |    12 | A       | F      | Neha Gupta   | 2008-09-09 | 95.00 | neha@kvsb.in  |
|          9 |    12 | B       | M      | Karan Mehta  | 2008-04-17 | 60.00 | karan@kvsb.in |
|         10 |    12 | A       | F      | Divya Rao    | 2007-10-05 | 73.50 | divya@kvsb.in |
+------------+-------+---------+--------+--------------+------------+-------+---------------+
10 rows in set (0.00 sec)
๐Ÿ’ก Explanation: SELECT * fetches all columns and rows.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT * FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 10 rows in set
Q23 SQL

SQL: To display Rno, Name and Marks of students scoring marks more than 50.

SELECT student_id, name, marks FROM student WHERE marks > 50;
โ–ถ Sample Output
mysql> SELECT student_id, name, marks FROM student WHERE marks > 50;
+------------+--------------+-------+
| student_id | name         | marks |
+------------+--------------+-------+
|          1 | Amit Kumar   | 88.50 |
|          2 | Sara Khan    | 92.00 |
|          3 | Rahul Sharma | 65.50 |
|          4 | Priya Singh  | 78.00 |
|          5 | Anand Verma  | 55.00 |
|          6 | Angad Kaur   | 81.00 |
|          8 | Neha Gupta   | 95.00 |
|          9 | Karan Mehta  | 60.00 |
|         10 | Divya Rao    | 73.50 |
+------------+--------------+-------+
9 rows in set (0.00 sec)
๐Ÿ’ก Explanation: Simple WHERE filter.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, marks FROM student WHERE marks > 50;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks > 50 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, marks โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 9 rows in set
Q24 SQL

SQL: To find the average of marks from the student table.

SELECT AVG(marks) AS Average_Marks FROM student;
โ–ถ Sample Output
mysql> SELECT AVG(marks) AS Average_Marks FROM student;
+---------------+
| Average_Marks |
+---------------+
|     73.650000 |
+---------------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: AVG() aggregate function.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT AVG(marks) AS Average_Marks FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT AVG(marks) AS Average_Marks โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
Q25 SQL

SQL: To find the number of students who are from section 'A'.

SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
โ–ถ Sample Output
mysql> SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
+-----------------+
| Total_Section_A |
+-----------------+
|               6 |
+-----------------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: COUNT(*) with WHERE filter.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';

Fetches the summary values from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE section = 'A' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT COUNT(*) AS Total_Section_A โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
Q26 SQL

SQL: To display information of all students whose name starts with 'AN'.

SELECT * FROM student WHERE name LIKE 'AN%';
โ–ถ Sample Output
mysql> SELECT * FROM student WHERE name LIKE 'AN%';
+------------+-------+---------+--------+-------------+------------+-------+---------------+
| student_id | class | section | gender | name        | dob        | marks | email         |
+------------+-------+---------+--------+-------------+------------+-------+---------------+
|          5 |    12 | B       | M      | Anand Verma | 2008-07-19 | 55.00 | anand@kvsb.in |
|          6 |    12 | A       | F      | Angad Kaur  | 2008-01-25 | 81.00 | angad@kvsb.in |
+------------+-------+---------+--------+-------------+------------+-------+---------------+
2 rows in set (0.00 sec)
๐Ÿ’ก Explanation: LIKE with % wildcard.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT * FROM student WHERE name LIKE 'AN%';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE name LIKE 'AN%' (starts with "AN") โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 2 rows in set
Q27 SQL

SQL: To display Rno, Name, DOB of students born between '2008-01-01' and '2008-12-31'.

SELECT student_id, name, dob FROM student WHERE dob BETWEEN '2008-01-01' AND '2008-12-31';
โ–ถ Sample Output
mysql> SELECT student_id, name, dob FROM student WHERE dob BETWEEN '2008-01-01' AND '2008-12-31';
+------------+-------------+------------+
| student_id | name        | dob        |
+------------+-------------+------------+
|          1 | Amit Kumar  | 2008-05-14 |
|          2 | Sara Khan   | 2008-08-21 |
|          4 | Priya Singh | 2008-03-11 |
|          5 | Anand Verma | 2008-07-19 |
|          6 | Angad Kaur  | 2008-01-25 |
|          8 | Neha Gupta  | 2008-09-09 |
|          9 | Karan Mehta | 2008-04-17 |
+------------+-------------+------------+
7 rows in set (0.00 sec)
๐Ÿ’ก Explanation: BETWEEN is inclusive on both ends.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, dob FROM student WHERE dob BETWEEN '2008-01-01' AND '2008-12-31';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE dob BETWEEN '2008-01-01' AND '2008-12-31' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, dob โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 7 rows in set
Q28 SQL

SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names.

SELECT student_id, name, dob, marks, email FROM student WHERE gender = 'M' ORDER BY name ASC;
โ–ถ Sample Output
mysql> SELECT student_id, name, dob, marks, email FROM student WHERE gender = 'M' ORDER BY name ASC;
+------------+--------------+------------+-------+---------------+
| student_id | name         | dob        | marks | email         |
+------------+--------------+------------+-------+---------------+
|          1 | Amit Kumar   | 2008-05-14 | 88.50 | amit@kvsb.in  |
|          5 | Anand Verma  | 2008-07-19 | 55.00 | anand@kvsb.in |
|          9 | Karan Mehta  | 2008-04-17 | 60.00 | karan@kvsb.in |
|          3 | Rahul Sharma | 2007-12-02 | 65.50 | rahul@kvsb.in |
|          7 | Vivek Yadav  | 2007-11-30 | 48.00 | vivek@kvsb.in |
+------------+--------------+------------+-------+---------------+
5 rows in set (0.00 sec)
๐Ÿ’ก Explanation: ORDER BY ASC + WHERE gender filter.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, dob, marks, email FROM student WHERE gender = 'M' ORDER BY name ASC;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE gender = 'M' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, dob, marks, email โ†’ picks the columns / calculates the values to show.
  4. ORDER BY name ASC โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 5 rows in set
Q29 SQL

SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks.

SELECT student_id, gender, name, dob, marks, email FROM student ORDER BY marks DESC;
โ–ถ Sample Output
mysql> SELECT student_id, gender, name, dob, marks, email FROM student ORDER BY marks DESC;
+------------+--------+--------------+------------+-------+---------------+
| student_id | gender | name         | dob        | marks | email         |
+------------+--------+--------------+------------+-------+---------------+
|          8 | F      | Neha Gupta   | 2008-09-09 | 95.00 | neha@kvsb.in  |
|          2 | F      | Sara Khan    | 2008-08-21 | 92.00 | sara@kvsb.in  |
|          1 | M      | Amit Kumar   | 2008-05-14 | 88.50 | amit@kvsb.in  |
|          6 | F      | Angad Kaur   | 2008-01-25 | 81.00 | angad@kvsb.in |
|          4 | F      | Priya Singh  | 2008-03-11 | 78.00 | priya@kvsb.in |
|         10 | F      | Divya Rao    | 2007-10-05 | 73.50 | divya@kvsb.in |
|          3 | M      | Rahul Sharma | 2007-12-02 | 65.50 | rahul@kvsb.in |
|          9 | M      | Karan Mehta  | 2008-04-17 | 60.00 | karan@kvsb.in |
|          5 | M      | Anand Verma  | 2008-07-19 | 55.00 | anand@kvsb.in |
|          7 | M      | Vivek Yadav  | 2007-11-30 | 48.00 | vivek@kvsb.in |
+------------+--------+--------------+------------+-------+---------------+
10 rows in set (0.00 sec)
๐Ÿ’ก Explanation: ORDER BY DESC for merit ranking.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, gender, name, dob, marks, email FROM student ORDER BY marks DESC;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT student_id, gender, name, dob, marks, email โ†’ picks the columns / calculates the values to show.
  3. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 10 rows in set
Q30 SQL

SQL: To display the unique sections available in the table.

SELECT DISTINCT section FROM student;
โ–ถ Sample Output
mysql> SELECT DISTINCT section FROM student;
+---------+
| section |
+---------+
| A       |
| B       |
+---------+
2 rows in set (0.00 sec)
๐Ÿ’ก Explanation: DISTINCT removes duplicate values.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT DISTINCT section FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT section โ†’ picks the columns / calculates the values to show.
  3. DISTINCT โ†’ removes repeated rows, so each value appears only once.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 2 rows in set
Q31 SQL

SQL: To display the name and class of students whose marks are less than 33.

SELECT name, class FROM student WHERE marks < 33;
โ–ถ Sample Output
mysql> SELECT name, class FROM student WHERE marks < 33;
Empty set (0.00 sec)
๐Ÿ’ก Explanation: Simple WHERE condition for 'failed' students.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT name, class FROM student WHERE marks < 33;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks < 33 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, class โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: Empty set
Q32 SQL

SQL: To display the structure of the student table.

DESC student;
โ–ถ Sample Output
mysql> DESC student;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int          | NO   | PRI | NULL    |       |
| class      | int          | YES  |     | NULL    |       |
| section    | char(1)      | YES  |     | NULL    |       |
| gender     | char(1)      | YES  |     | NULL    |       |
| name       | varchar(30)  | YES  |     | NULL    |       |
| dob        | date         | YES  |     | NULL    |       |
| marks      | decimal(5,2) | YES  |     | NULL    |       |
| email      | varchar(40)  | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
๐Ÿ’ก Explanation: Shows column structure, types & keys.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
DESC student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 8 rows in set
Q33 SQL

SQL: To display the Name and DOB of students who were born in 2008.

SELECT name, dob FROM student WHERE YEAR(dob) = 2008;
โ–ถ Sample Output
mysql> SELECT name, dob FROM student WHERE YEAR(dob) = 2008;
+-------------+------------+
| name        | dob        |
+-------------+------------+
| Amit Kumar  | 2008-05-14 |
| Sara Khan   | 2008-08-21 |
| Priya Singh | 2008-03-11 |
| Anand Verma | 2008-07-19 |
| Angad Kaur  | 2008-01-25 |
| Neha Gupta  | 2008-09-09 |
| Karan Mehta | 2008-04-17 |
+-------------+------------+
7 rows in set (0.00 sec)
๐Ÿ’ก Explanation: YEAR() date function.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT name, dob FROM student WHERE YEAR(dob) = 2008;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE YEAR(dob) = 2008 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, dob โ†’ picks the columns / calculates the values to show.
  4. Functions used: YEAR() takes the year from a date.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 7 rows in set
Q34 SQL

Write MySQL queries demonstrating: (a) Aggregate Functions (b) Mathematical Functions (c) Text Functions (d) Date & Time Functions (e) GROUP BY.

-- (a) Aggregate Functions
SELECT COUNT(*), SUM(marks), AVG(marks), MIN(marks), MAX(marks) FROM student;

-- (b) Mathematical Functions
SELECT POWER(2,3), SQRT(49), ROUND(88.567,1), MOD(10,3), ABS(-25), TRUNCATE(9.999,2);

-- (c) Text Functions
SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM('  Amit  ')
FROM student LIMIT 3;

-- (d) Date & Time Functions
SELECT NOW(), CURDATE(), YEAR(dob), MONTH(dob), DAY(dob), DATEDIFF(CURDATE(), dob) AS Age_in_days
FROM student LIMIT 3;

-- (e) GROUP BY query on a table
SELECT section, COUNT(*), AVG(marks) FROM student GROUP BY section;
โ–ถ Sample Output
mysql> SELECT COUNT(*), SUM(marks), AVG(marks), MIN(marks), MAX(marks) FROM student;
+----------+------------+------------+------------+------------+
| COUNT(*) | SUM(marks) | AVG(marks) | MIN(marks) | MAX(marks) |
+----------+------------+------------+------------+------------+
|       10 |     736.50 |  73.650000 |      48.00 |      95.00 |
+----------+------------+------------+------------+------------+
1 row in set (0.00 sec)

mysql> SELECT POWER(2,3), SQRT(49), ROUND(88.567,1), MOD(10,3), ABS(-25), TRUNCATE(9.999,2);
+------------+----------+-----------------+-----------+----------+-------------------+
| POWER(2,3) | SQRT(49) | ROUND(88.567,1) | MOD(10,3) | ABS(-25) | TRUNCATE(9.999,2) |
+------------+----------+-----------------+-----------+----------+-------------------+
|          8 |        7 |            88.6 |         1 |       25 |              9.99 |
+------------+----------+-----------------+-----------+----------+-------------------+
1 row in set (0.00 sec)

mysql> SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM('  Amit  ')
    -> FROM student LIMIT 3;
+--------------+--------------+--------------+---------------------+---------------------+------------------+
| UCASE(name)  | LCASE(name)  | LENGTH(name) | SUBSTRING(name,1,4) | CONCAT(name,'-XII') | TRIM('  Amit  ') |
+--------------+--------------+--------------+---------------------+---------------------+------------------+
| AMIT KUMAR   | amit kumar   |           10 | Amit                | Amit Kumar-XII      | Amit             |
| SARA KHAN    | sara khan    |            9 | Sara                | Sara Khan-XII       | Amit             |
| RAHUL SHARMA | rahul sharma |           12 | Rahu                | Rahul Sharma-XII    | Amit             |
+--------------+--------------+--------------+---------------------+---------------------+------------------+
3 rows in set (0.00 sec)

mysql> SELECT NOW(), CURDATE(), YEAR(dob), MONTH(dob), DAY(dob), DATEDIFF(CURDATE(), dob) AS Age_in_days
    -> FROM student LIMIT 3;
+---------------------+------------+-----------+------------+----------+-------------+
| NOW()               | CURDATE()  | YEAR(dob) | MONTH(dob) | DAY(dob) | Age_in_days |
+---------------------+------------+-----------+------------+----------+-------------+
| 2026-11-16 09:37:36 | 2026-11-16 |      2008 |          5 |       14 |        6760 |
| 2026-11-16 09:37:36 | 2026-11-16 |      2008 |          8 |       21 |        6661 |
| 2026-11-16 09:37:36 | 2026-11-16 |      2007 |         12 |        2 |        6924 |
+---------------------+------------+-----------+------------+----------+-------------+
3 rows in set (0.00 sec)

mysql> SELECT section, COUNT(*), AVG(marks) FROM student GROUP BY section;
+---------+----------+------------+
| section | COUNT(*) | AVG(marks) |
+---------+----------+------------+
| A       |        6 |  80.250000 |
| B       |        4 |  63.750000 |
+---------+----------+------------+
2 rows in set (0.00 sec)
๐Ÿ’ก Explanation: This practical is a ready-reference sheet โ€” memorise one example of each function-category for the board practical exam.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
๐Ÿ“Œ (a) Aggregate Functions
1
Query ยท read only
SELECT COUNT(*), SUM(marks), AVG(marks), MIN(marks), MAX(marks) FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT COUNT(*), SUM(marks), AVG(marks), MIN(marks), MAX(marks) โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row.
  3. Functions used: COUNT(*) counts all rows; SUM() adds the values; AVG() finds the average; MIN() finds the smallest value; MAX() finds the largest value.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
๐Ÿ“Œ (b) Mathematical Functions
2
Query ยท read only
SELECT POWER(2,3), SQRT(49), ROUND(88.567,1), MOD(10,3), ABS(-25), TRUNCATE(9.999,2);

Calculates and shows the values directly (no table needed).

  1. SELECT POWER(2,3), SQRT(49), ROUND(88.567,1), MOD(10,3), ABS(-25), TRUNCATE(9.999,2) โ†’ picks the columns / calculates the values to show.
  2. Functions used: POWER(a, b) = a raised to b; SQRT() gives the square root; ROUND(x, d) rounds x to d decimal places; MOD(a, b) gives the remainder of a รท b; ABS() removes the minus sign; TRUNCATE(x, d) cuts x to d decimals without rounding.
โœ” Result: 1 row in set
๐Ÿ“Œ (c) Text Functions
3
Query ยท read only
SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM('  Amit  ')
FROM student LIMIT 3;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM(' Amit ') โ†’ picks the columns / calculates the values to show.
  3. Functions used: UCASE()/UPPER() changes text to capitals; LCASE()/LOWER() changes text to small letters; LENGTH() counts characters; SUBSTRING(text, start, n) takes n characters from position start; CONCAT() joins texts together; TRIM() removes spaces at both ends.
  4. LIMIT 3 โ†’ shows only the first 3 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 3 rows in set
๐Ÿ“Œ (d) Date & Time Functions
4
Query ยท read only
SELECT NOW(), CURDATE(), YEAR(dob), MONTH(dob), DAY(dob), DATEDIFF(CURDATE(), dob) AS Age_in_days
FROM student LIMIT 3;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT NOW(), CURDATE(), YEAR(dob), MONTH(dob), DAY(dob), DATEDIFF(CURDATE(), dob) AS Age_in_days โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: NOW() gives current date & time; CURDATE() gives today's date; YEAR() takes the year from a date; MONTH() takes the month number; DAY() takes the day of the month; DATEDIFF(d1, d2) gives days between two dates.
  4. LIMIT 3 โ†’ shows only the first 3 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 3 rows in set
๐Ÿ“Œ (e) GROUP BY query on a table
5
Query ยท read only
SELECT section, COUNT(*), AVG(marks) FROM student GROUP BY section;

Fetches rows from student, grouped by section.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY section โ†’ makes groups: rows with the same section go into one group (one output row per group).
  3. SELECT section, COUNT(*), AVG(marks) โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group.
  4. Functions used: COUNT(*) counts all rows; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 2 rows in set

๐Ÿ“Š Data Visualization Practicals (Matplotlib) — Q35 to Q40

As per CBSE Class XII IP syllabus: line plot, bar graph, histogram; customising plots with colour, style, width, label, title and legend; saving plots. Every program was run and the real charts are shown.

Q35 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (Line Chart): The maximum temperature (in degree C) of Delhi and Shimla for one week is given below. Plot both cities on the same line chart with different colours, line styles, markers and line widths. Add title, axis labels, legend and grid, and save the chart as temp_line.png. Days: Mon-Sun | Delhi: 36, 38, 40, 39, 41, 42, 40 | Shimla: 22, 24, 23, 25, 26, 24, 23

import matplotlib.pyplot as plt

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
delhi = [36, 38, 40, 39, 41, 42, 40]
shimla = [22, 24, 23, 25, 26, 24, 23]

print("Delhi : average =", round(sum(delhi) / len(delhi), 2), "| highest =", max(delhi), "on", days[delhi.index(max(delhi))])
print("Shimla: average =", round(sum(shimla) / len(shimla), 2), "| highest =", max(shimla), "on", days[shimla.index(max(shimla))])

plt.figure(figsize=(8, 4.5))
plt.plot(days, delhi, color='red', linestyle='-', linewidth=2.5, marker='o', markersize=8, label='Delhi')
plt.plot(days, shimla, color='blue', linestyle='--', linewidth=2, marker='s', markersize=7, label='Shimla')
for x, y in zip(days, delhi):
    plt.text(x, y + 0.7, y, ha='center', color='red')
for x, y in zip(days, shimla):
    plt.text(x, y + 0.7, y, ha='center', color='blue')
plt.title('Maximum Temperature in a Week', fontsize=14, color='darkgreen')
plt.xlabel('Day of the week')
plt.ylabel('Temperature (degree C)')
plt.ylim(15, 46)
plt.legend(loc='center right')
plt.grid(True, linestyle=':')
plt.savefig('temp_line.png')
plt.show()
print("Chart saved as temp_line.png")
โ–ถ Sample Output (text + charts)
Delhi : average = 39.43 | highest = 42 on Sat
Shimla: average = 23.86 | highest = 26 on Fri
Chart saved as temp_line.png
Output chart: temp_line.png
Output chart: temp_line.png
๐Ÿ’ก Explanation: plot() draws a line chart (default plot type). color, linestyle ('-', '--', ':'), linewidth and marker customise each line; label + legend() identify the lines; savefig() must come before show(). A line chart is best for showing change over time.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q35.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
๐Ÿงฎ Store / Calculate Stores a list ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sโ€ฆ in variable days
4
delhi = [36, 38, 40, 39, 41, 42, 40]
๐Ÿงฎ Store / Calculate Stores a list [36, 38, 40, 39, 41, 42, 40] in variable delhi
5
shimla = [22, 24, 23, 25, 26, 24, 23]
๐Ÿงฎ Store / Calculate Stores a list [22, 24, 23, 25, 26, 24, 23] in variable shimla
7
print("Delhi : average =", round(sum(delhi) / len(delhi), 2), "| highest =", max(delhi), "on", days[delhi.index(max(delhi))])
๐Ÿ–ฅ๏ธ Output Displays the text "Delhi : average =", then the value of round(sum(delhi) / len(delhi), 2), then the text "| highest =", then the value of max(delhi), then the text "on", then the value of days[delhi.index(max(delhi))] on the screen
8
print("Shimla: average =", round(sum(shimla) / len(shimla), 2), "| highest =", max(shimla), "on", days[shimla.index(max(shimla))])
๐Ÿ–ฅ๏ธ Output Displays the text "Shimla: average =", then the value of round(sum(shimla) / len(shimla), 2), then the text "| highest =", then the value of max(shimla), then the text "on", then the value of days[shimla.index(max(shimla))] on the screen
10
plt.figure(figsize=(8, 4.5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
11
plt.plot(days, delhi, color='red', linestyle='-', linewidth=2.5, marker='o', markersize=8, label='Delhi')
๐Ÿ–ฅ๏ธ Output Draws a line chart of days, delhi
12
plt.plot(days, shimla, color='blue', linestyle='--', linewidth=2, marker='s', markersize=7, label='Shimla')
๐Ÿ–ฅ๏ธ Output Draws a line chart of days, shimla
13
for x, y in zip(days, delhi):
๐Ÿ” Loop LOOP that walks through days, delhi together; x, y get one item from each
14
plt.text(x, y + 0.7, y, ha='center', color='red')
๐Ÿ–ฅ๏ธ Output Writes text on the chart
15
for x, y in zip(days, shimla):
๐Ÿ” Loop LOOP that walks through days, shimla together; x, y get one item from each
16
plt.text(x, y + 0.7, y, ha='center', color='blue')
๐Ÿ–ฅ๏ธ Output Writes text on the chart
17
plt.title('Maximum Temperature in a Week', fontsize=14, color='darkgreen')
๐Ÿ–ฅ๏ธ Output Writes 'Maximum Temperature in a Week' as the title of the chart
18
plt.xlabel('Day of the week')
๐Ÿ–ฅ๏ธ Output Writes 'Day of the week' as the label of the X-axis
19
plt.ylabel('Temperature (degree C)')
๐Ÿ–ฅ๏ธ Output Writes 'Temperature (degree C)' as the label of the Y-axis
20
plt.ylim(15, 46)
๐Ÿ–ฅ๏ธ Output Sets the range of the Y-axis
21
plt.legend(loc='center right')
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
22
plt.grid(True, linestyle=':')
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
23
plt.savefig('temp_line.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'temp_line.png'
24
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
25
print("Chart saved as temp_line.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Chart saved as temp_line.png" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import matplotlib.pyplot as plt
23
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
34
delhi = [36, 38, 40, 39, 41, 42, 40]
delhi = [36, 38, 40, 39, 41, 42, 40]
45
shimla = [22, 24, 23, 25, 26, 24, 23]
shimla = [22, 24, 23, 25, 26, 24, 23]
57
print("Delhi : average =", round(sum(delhi) / len(delhi), 2), "| highest =", max(delhi), "
Delhi : average = 39.43 | highest = 42 on Sat
68
print("Shimla: average =", round(sum(shimla) / len(shimla), 2), "| highest =", max(shimla)
Shimla: average = 23.86 | highest = 26 on Fri
710
plt.figure(figsize=(8, 4.5))
811
plt.plot(days, delhi, color='red', linestyle='-', linewidth=2.5, marker='o', markersize=8,
912
plt.plot(days, shimla, color='blue', linestyle='--', linewidth=2, marker='s', markersize=7
1013
for x, y in zip(days, delhi):
next item taken
x = 'Mon', y = 36
1114
plt.text(x, y + 0.7, y, ha='center', color='red')
1213
for x, y in zip(days, delhi):
next item taken
x = 'Tue', y = 38
1314
plt.text(x, y + 0.7, y, ha='center', color='red')
1413
for x, y in zip(days, delhi):
next item taken
x = 'Wed', y = 40
1514
plt.text(x, y + 0.7, y, ha='center', color='red')
1613
for x, y in zip(days, delhi):
next item taken
x = 'Thu', y = 39
1714
plt.text(x, y + 0.7, y, ha='center', color='red')
1813
for x, y in zip(days, delhi):
next item taken
x = 'Fri', y = 41
1914
plt.text(x, y + 0.7, y, ha='center', color='red')
2013
for x, y in zip(days, delhi):
next item taken
x = 'Sat', y = 42
2114
plt.text(x, y + 0.7, y, ha='center', color='red')
2213
for x, y in zip(days, delhi):
next item taken
x = 'Sun', y = 40
2314
plt.text(x, y + 0.7, y, ha='center', color='red')
2413
for x, y in zip(days, delhi):
no items left โ†’ loop ends
2515
for x, y in zip(days, shimla):
next item taken
x = 'Mon', y = 22
2616
plt.text(x, y + 0.7, y, ha='center', color='blue')
2715
for x, y in zip(days, shimla):
next item taken
x = 'Tue', y = 24
2816
plt.text(x, y + 0.7, y, ha='center', color='blue')
2915
for x, y in zip(days, shimla):
next item taken
x = 'Wed', y = 23
3016
plt.text(x, y + 0.7, y, ha='center', color='blue')
3115
for x, y in zip(days, shimla):
next item taken
x = 'Thu', y = 25
3216
plt.text(x, y + 0.7, y, ha='center', color='blue')

โ€ฆ Python runs 16 more line-steps in the same way (loops repeat the same lines). Final values: days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], delhi = [36, 38, 40, 39, 41, 42, 40], shimla = [22, 24, 23, 25, 26, 24, 23], x = 'Sun', y = 23

Q36 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (Bar Chart - CBSE SQP 2024-25 pattern): The number of books read by students in one month is given below. Draw a bar chart with a different colour for each bar, show the value on top of each bar, label the axes, give the title 'Number of Books Read by Students' and save it as books_bar.png. Karan 12, Lina 9, Raj 5, Simran 3, Tanya 10, Vivek 7

import matplotlib.pyplot as plt

students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek']      # Statement-1 : import matplotlib.pyplot
books_read = [12, 9, 5, 3, 10, 7]                                   # Statement-2 : heights of bars

print("Total books read :", sum(books_read))
print("Top reader       :", students[books_read.index(max(books_read))], "with", max(books_read), "books")
print("Average per child:", round(sum(books_read) / len(books_read), 2))

colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00']
plt.figure(figsize=(8, 4.5))
plt.bar(students, books_read, color=colours, edgecolor='black', width=0.6)
for i, v in enumerate(books_read):
    plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
plt.xlabel('Student Name')
plt.ylabel('Books Read')                                           # Statement-3 : ylabel
plt.title('Number of Books Read by Students')                      # Statement-4 : title
plt.savefig('books_bar.png')
plt.show()
print("Chart saved as books_bar.png")
โ–ถ Sample Output (text + charts)
Total books read : 46
Top reader       : Karan with 12 books
Average per child: 7.67
Chart saved as books_bar.png
Output chart: books_bar.png
Output chart: books_bar.png
๐Ÿ’ก Explanation: bar(x, height) draws vertical bars; color can be a list (one colour per bar), edgecolor and width change the look. xlabel(), ylabel() and title() add labels (CBSE SQP asked exactly these blanks). plt.text() writes the value on each bar.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q36.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek']      # Statement-1 : import matplotlib.pyplot
๐Ÿงฎ Store / Calculate Stores a list ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'โ€ฆ in variable students
4
books_read = [12, 9, 5, 3, 10, 7]                                   # Statement-2 : heights of bars
๐Ÿงฎ Store / Calculate Stores a list [12, 9, 5, 3, 10, 7] in variable books_read
6
print("Total books read :", sum(books_read))
๐Ÿ–ฅ๏ธ Output Displays the text "Total books read :", then the value of sum(books_read) on the screen
7
print("Top reader       :", students[books_read.index(max(books_read))], "with", max(books_read), "books")
๐Ÿ–ฅ๏ธ Output Displays the text "Top reader :", then the value of students[books_read.index(max(books_read))], then the text "with", then the value of max(books_read), then the text "books" on the screen
8
print("Average per child:", round(sum(books_read) / len(books_read), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Average per child:", then the value of round(sum(books_read) / len(books_read), 2) on the screen
10
colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00']
๐Ÿงฎ Store / Calculate Stores a list ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', โ€ฆ in variable colours
11
plt.figure(figsize=(8, 4.5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
12
plt.bar(students, books_read, color=colours, edgecolor='black', width=0.6)
๐Ÿ–ฅ๏ธ Output Draws a bar chart of students, books_read
13
for i, v in enumerate(books_read):
๐Ÿ” Loop LOOP over books_read with position: in each round i, v get (position, item)
14
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
๐Ÿ–ฅ๏ธ Output Writes text on the chart
15
plt.xlabel('Student Name')
๐Ÿ–ฅ๏ธ Output Writes 'Student Name' as the label of the X-axis
16
plt.ylabel('Books Read')                                           # Statement-3 : ylabel
๐Ÿ–ฅ๏ธ Output Writes 'Books Read' as the label of the Y-axis
17
plt.title('Number of Books Read by Students')                      # Statement-4 : title
๐Ÿ–ฅ๏ธ Output Writes 'Number of Books Read by Students' as the title of the chart
18
plt.savefig('books_bar.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'books_bar.png'
19
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
20
print("Chart saved as books_bar.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Chart saved as books_bar.png" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import matplotlib.pyplot as plt
23
students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek']      # Statement-1 : impor
students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek']
34
books_read = [12, 9, 5, 3, 10, 7]                                   # Statement-2 : height
books_read = [12, 9, 5, 3, 10, 7]
46
print("Total books read :", sum(books_read))
Total books read : 46
57
print("Top reader       :", students[books_read.index(max(books_read))], "with", max(books
Top reader       : Karan with 12 books
68
print("Average per child:", round(sum(books_read) / len(books_read), 2))
Average per child: 7.67
710
colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00']
colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00']
811
plt.figure(figsize=(8, 4.5))
912
plt.bar(students, books_read, color=colours, edgecolor='black', width=0.6)
1013
for i, v in enumerate(books_read):
next item taken
i = 0, v = 12
1114
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
1213
for i, v in enumerate(books_read):
next item taken
i = 1, v = 9
1314
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
1413
for i, v in enumerate(books_read):
next item taken
i = 2, v = 5
1514
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
1613
for i, v in enumerate(books_read):
next item taken
i = 3, v = 3
1714
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
1813
for i, v in enumerate(books_read):
next item taken
i = 4, v = 10
1914
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
2013
for i, v in enumerate(books_read):
next item taken
i = 5, v = 7
2114
plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold')
2213
for i, v in enumerate(books_read):
no items left โ†’ loop ends
2315
plt.xlabel('Student Name')
2416
plt.ylabel('Books Read')                                           # Statement-3 : ylabel
2517
plt.title('Number of Books Read by Students')                      # Statement-4 : title
2618
plt.savefig('books_bar.png')
2719
plt.show()
2820
print("Chart saved as books_bar.png")
Chart saved as books_bar.png
Q37 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (Multiple Bar Chart from a DataFrame): Create a DataFrame of medals won by five countries (Gold, Silver, Bronze - sample data). Plot a grouped (multiple) bar chart with three bars for each country using numpy.arange and bar width, add a legend, title and labels. Also display the country with the maximum total medals.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'],
                   'Gold': [28, 40, 22, 18, 13], 'Silver': [38, 27, 25, 23, 21], 'Bronze': [41, 23, 30, 31, 16]})
df['Total'] = df['Gold'] + df['Silver'] + df['Bronze']
print(df)
print("\nCountry with maximum medals:", df.loc[df['Total'].idxmax(), 'Country'], "(", df['Total'].max(), ")")

x = np.arange(len(df))
w = 0.25
plt.figure(figsize=(9, 4.8))
plt.bar(x - w, df['Gold'], width=w, color='gold', edgecolor='black', label='Gold')
plt.bar(x, df['Silver'], width=w, color='silver', edgecolor='black', label='Silver')
plt.bar(x + w, df['Bronze'], width=w, color='#cd7f32', edgecolor='black', label='Bronze')
plt.xticks(x, df['Country'])
plt.xlabel('Country')
plt.ylabel('Number of medals')
plt.title('Medal Tally (sample data) - Multiple Bar Chart')
plt.legend()
plt.grid(axis='y', linestyle='--', alpha=0.6)
plt.savefig('medals_bar.png')
plt.show()
โ–ถ Sample Output (text + charts)
  Country  Gold  Silver  Bronze  Total
0   India    28      38      41    107
1   China    40      27      23     90
2   Japan    22      25      30     77
3   Korea    18      23      31     72
4    Iran    13      21      16     50

Country with maximum medals: India ( 107 )
Output chart: medals_bar.png
Output chart: medals_bar.png
๐Ÿ’ก Explanation: For a multiple bar chart, the x positions are shifted by the bar width (x - w, x, x + w) so bars stand side by side; xticks() puts country names in the middle. Data is taken from a DataFrame column (df['Gold']) - the usual CBSE practical pattern.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q37.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
5
df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'],
                   'Gold': [28, 40, 22, 18, 13], 'Silver': [38, 27, 25, 23, 21], โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'Country': ['India', 'China', 'Japan', 'Koreโ€ฆ; the result is stored in variable df
7
df['Total'] = df['Gold'] + df['Silver'] + df['Bronze']
๐Ÿงฎ Store / Calculate Puts the value of df['Gold'] + df['Silver'] + df['Bronze'] (calculated using +) into df['Total'] (item 'Total' of df)
8
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
9
print("\nCountry with maximum medals:", df.loc[df['Total'].idxmax(), 'Country'], "(", df['Total'].max(), ")")
๐Ÿ–ฅ๏ธ Output Displays the text "Country with maximum medals:", then the value of df.loc[df['Total'].idxmax(), 'Country'], then the text "(", then the value of df['Total'].max(), then the text ")" on the screen
11
x = np.arange(len(df))
๐Ÿ“ฆ Library / Data Makes a NumPy array of numbers from range(len(df)); the result is stored in variable x
12
w = 0.25
๐Ÿงฎ Store / Calculate Stores the number 0.25 in variable w
13
plt.figure(figsize=(9, 4.8))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
14
plt.bar(x - w, df['Gold'], width=w, color='gold', edgecolor='black', label='Gold')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x - w, df['Gold']
15
plt.bar(x, df['Silver'], width=w, color='silver', edgecolor='black', label='Silver')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x, df['Silver']
16
plt.bar(x + w, df['Bronze'], width=w, color='#cd7f32', edgecolor='black', label='Bronze')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x + w, df['Bronze']
17
plt.xticks(x, df['Country'])
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
18
plt.xlabel('Country')
๐Ÿ–ฅ๏ธ Output Writes 'Country' as the label of the X-axis
19
plt.ylabel('Number of medals')
๐Ÿ–ฅ๏ธ Output Writes 'Number of medals' as the label of the Y-axis
20
plt.title('Medal Tally (sample data) - Multiple Bar Chart')
๐Ÿ–ฅ๏ธ Output Writes 'Medal Tally (sample data) - Multiple Bar Chaโ€ฆ as the title of the chart
21
plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
22
plt.grid(axis='y', linestyle='--', alpha=0.6)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
23
plt.savefig('medals_bar.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'medals_bar.png'
24
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
33
import matplotlib.pyplot as plt
45
df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'],
56
'Gold': [28, 40, 22, 18, 13], 'Silver': [38, 27, 25, 23, 21], 'Bronze': [41, 23, 30, 31, 1
65
df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'],
df = DataFrame (5 rows ร— 4 columns)
77
df['Total'] = df['Gold'] + df['Silver'] + df['Bronze']
df = DataFrame (5 rows ร— 5 columns)
88
print(df)
  Country  Gold  Silver  Bronze  Total
0   India    28      38      41    107
1   China    40      27      23     90
2   Japan    22      25      30     77
3   Korea    18      23      31     72
4    Iran    13      21      16     50
99
print("\nCountry with maximum medals:", df.loc[df['Total'].idxmax(), 'Country'], "(", df['
Country with maximum medals: India ( 107 )
1011
x = np.arange(len(df))
x = array([0, 1, 2, 3, 4])
1112
w = 0.25
w = 0.25
1213
plt.figure(figsize=(9, 4.8))
1314
plt.bar(x - w, df['Gold'], width=w, color='gold', edgecolor='black', label='Gold')
1415
plt.bar(x, df['Silver'], width=w, color='silver', edgecolor='black', label='Silver')
1516
plt.bar(x + w, df['Bronze'], width=w, color='#cd7f32', edgecolor='black', label='Bronze')
1617
plt.xticks(x, df['Country'])
1718
plt.xlabel('Country')
1819
plt.ylabel('Number of medals')
1920
plt.title('Medal Tally (sample data) - Multiple Bar Chart')
2021
plt.legend()
2122
plt.grid(axis='y', linestyle='--', alpha=0.6)
2223
plt.savefig('medals_bar.png')
2324
plt.show()
Q38 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (Histogram): The weights (in kg) of 40 students of a class are given in the program. Plot a histogram with bins [30, 35, 40, 45, 50, 55, 60, 65, 70], colour and edge colour, title and labels. Also print the frequency of each class interval and plot a second histogram of the same data using histtype='step' and cumulative=True.

import numpy as np
import matplotlib.pyplot as plt

weights = [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, 44, 58, 63, 41, 50, 53, 46, 39, 57,
           48, 52, 66, 43, 49, 54, 47, 36, 59, 51, 45, 62, 50, 48, 44, 56, 40, 53, 69, 47]
bins = [30, 35, 40, 45, 50, 55, 60, 65, 70]
freq, edges = np.histogram(weights, bins=bins)
print("Students:", len(weights), "| Minimum:", min(weights), "| Maximum:", max(weights), "| Mean:", np.mean(weights))
print("\nClass interval   Frequency")
for i in range(len(freq)):
    print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])

plt.figure(figsize=(8, 4.5))
plt.hist(weights, bins=bins, color='#4dabf7', edgecolor='black')
plt.title('Weights of Students of Class XII')
plt.xlabel('Weight (kg)')
plt.ylabel('Number of students')
plt.xticks(bins)
plt.savefig('weight_hist.png')
plt.show()

plt.figure(figsize=(8, 4.5))
plt.hist(weights, bins=bins, histtype='step', cumulative=True, linewidth=2.5, color='purple')
plt.title('Cumulative Histogram (histtype = step)')
plt.xlabel('Weight (kg)')
plt.ylabel('Cumulative number of students')
plt.xticks(bins)
plt.grid(linestyle=':')
plt.savefig('weight_hist_step.png')
plt.show()
โ–ถ Sample Output (text + charts)
Students: 40 | Minimum: 36 | Maximum: 69 | Mean: 49.85

Class interval   Frequency
   30 - 35          0   
   35 - 40          4   ****
   40 - 45          6   ******
   45 - 50         11   ***********
   50 - 55          9   *********
   55 - 60          5   *****
   60 - 65          3   ***
   65 - 70          2   **
Output chart: weight_hist.png
Output chart: weight_hist.png
Output chart: weight_hist_step.png
Output chart: weight_hist_step.png
๐Ÿ’ก Explanation: hist(data, bins=...) groups values into class intervals and draws the frequency of each interval as touching bars (unlike a bar chart). edgecolor separates the bars; histtype='step' draws only the outline and cumulative=True shows the running total.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; modules numpy, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q38.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
weights = [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, 44, 58, 63, 41, 50, 53, 46, 39, 57,
           48, 52, 66, 43, 49, 54, 47, 36, 59, 51, 45, 62, 50, 48,โ€ฆ
๐Ÿงฎ Store / Calculate Stores a list [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, โ€ฆ in variable weights
6
bins = [30, 35, 40, 45, 50, 55, 60, 65, 70]
๐Ÿงฎ Store / Calculate Stores a list [30, 35, 40, 45, 50, 55, 60, 65, 70] in variable bins
7
freq, edges = np.histogram(weights, bins=bins)
๐Ÿ“ฆ Library / Data Calls np.histogram(weights); the result is stored in variables freq, edges
8
print("Students:", len(weights), "| Minimum:", min(weights), "| Maximum:", max(weights), "| Mean:", np.mean(weights))
๐Ÿ–ฅ๏ธ Output Displays the text "Students:", then the value of len(weights), then the text "| Minimum:", then the value of min(weights), then the text "| Maximum:", then the value of max(weights), then the text "| Mean:", then the value of np.mean(weights) on the screen
9
print("\nClass interval   Frequency")
๐Ÿ–ฅ๏ธ Output Displays the text "Class interval Frequency" on the screen
10
for i in range(len(freq)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(freq) - 1; for each number, i takes that value and the indented block runs once
11
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
๐Ÿ–ฅ๏ธ Output Displays the value of f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} "โ€ฆ on the screen
13
plt.figure(figsize=(8, 4.5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
14
plt.hist(weights, bins=bins, color='#4dabf7', edgecolor='black')
๐Ÿ–ฅ๏ธ Output Draws a histogram of weights
15
plt.title('Weights of Students of Class XII')
๐Ÿ–ฅ๏ธ Output Writes 'Weights of Students of Class XII' as the title of the chart
16
plt.xlabel('Weight (kg)')
๐Ÿ–ฅ๏ธ Output Writes 'Weight (kg)' as the label of the X-axis
17
plt.ylabel('Number of students')
๐Ÿ–ฅ๏ธ Output Writes 'Number of students' as the label of the Y-axis
18
plt.xticks(bins)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
19
plt.savefig('weight_hist.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'weight_hist.png'
20
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
22
plt.figure(figsize=(8, 4.5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
23
plt.hist(weights, bins=bins, histtype='step', cumulative=True, linewidth=2.5, color='purple')
๐Ÿ–ฅ๏ธ Output Draws a histogram of weights
24
plt.title('Cumulative Histogram (histtype = step)')
๐Ÿ–ฅ๏ธ Output Writes 'Cumulative Histogram (histtype = step)' as the title of the chart
25
plt.xlabel('Weight (kg)')
๐Ÿ–ฅ๏ธ Output Writes 'Weight (kg)' as the label of the X-axis
26
plt.ylabel('Cumulative number of students')
๐Ÿ–ฅ๏ธ Output Writes 'Cumulative number of students' as the label of the Y-axis
27
plt.xticks(bins)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
28
plt.grid(linestyle=':')
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
29
plt.savefig('weight_hist_step.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'weight_hist_step.png'
30
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import numpy as np
22
import matplotlib.pyplot as plt
34
weights = [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, 44, 58, 63, 41, 50, 53, 46, 39, 57,
weights = [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, 44, 58, 63, 41, 50, 53โ€ฆ
46
bins = [30, 35, 40, 45, 50, 55, 60, 65, 70]
bins = [30, 35, 40, 45, 50, 55, 60, 65, 70]
57
freq, edges = np.histogram(weights, bins=bins)
freq = array([0, 4, 6, 11, 9, 5, 3, 2]), edges = array of shape (9,)
68
print("Students:", len(weights), "| Minimum:", min(weights), "| Maximum:", max(weights), "
Students: 40 | Minimum: 36 | Maximum: 69 | Mean: 49.85
79
print("\nClass interval   Frequency")
Class interval   Frequency
810
for i in range(len(freq)):
next item taken
i = 0
911
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   30 - 35          0   
1010
for i in range(len(freq)):
next item taken
i = 1
1111
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   35 - 40          4   ****
1210
for i in range(len(freq)):
next item taken
i = 2
1311
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   40 - 45          6   ******
1410
for i in range(len(freq)):
next item taken
i = 3
1511
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   45 - 50         11   ***********
1610
for i in range(len(freq)):
next item taken
i = 4
1711
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   50 - 55          9   *********
1810
for i in range(len(freq)):
next item taken
i = 5
1911
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   55 - 60          5   *****
2010
for i in range(len(freq)):
next item taken
i = 6
2111
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   60 - 65          3   ***
2210
for i in range(len(freq)):
next item taken
i = 7
2311
print(f"   {edges[i]} - {edges[i + 1]}        {freq[i]:>3}   " + "*" * freq[i])
   65 - 70          2   **
2410
for i in range(len(freq)):
no items left โ†’ loop ends
2513
plt.figure(figsize=(8, 4.5))
2614
plt.hist(weights, bins=bins, color='#4dabf7', edgecolor='black')
2715
plt.title('Weights of Students of Class XII')
2816
plt.xlabel('Weight (kg)')
2917
plt.ylabel('Number of students')
3018
plt.xticks(bins)
3119
plt.savefig('weight_hist.png')
3220
plt.show()

โ€ฆ Python runs 9 more line-steps in the same way (loops repeat the same lines). Final values: weights = [42, 48, 51, 37, 45, 55, 60, 52, 47, 49, 38, 44, 58, 63, 41, 50, 53โ€ฆ, bins = [30, 35, 40, 45, 50, 55, 60, 65, 70], freq = array([0, 4, 6, 11, 9, 5, 3, 2]), edges = array of shape (9,), i = 7

Q39 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (Plotting a DataFrame): Zone-wise quarterly sales (in lakh) are stored in a DataFrame. Plot (a) a line chart of all zones using df.plot() with markers and (b) a horizontal bar chart of the total sales of each zone using plot(kind='barh'). Give titles, labels and legend.

import pandas as pd
import matplotlib.pyplot as plt

sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55],
                      'East': [30, 35, 33, 42], 'West': [50, 48, 57, 63]},
                     index=['Q1', 'Q2', 'Q3', 'Q4'])
print(sales)
total = sales.sum().sort_values()
print("\nTotal sales of each zone:\n", total)
print("Best quarter:", sales.sum(axis=1).idxmax())

sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5),
           color=['#e03131', '#2f9e44', '#1971c2', '#f08c00'])
plt.title('Quarterly Sales of Each Zone')
plt.xlabel('Quarter')
plt.ylabel('Sales (Rs. lakh)')
plt.grid(linestyle=':')
plt.savefig('zone_line.png')
plt.show()

total.plot(kind='barh', color=['#74c0fc', '#63e6be', '#ffa94d', '#ff6b6b'], edgecolor='black', figsize=(8, 4))
plt.title('Total Annual Sales by Zone')
plt.xlabel('Sales (Rs. lakh)')
plt.ylabel('Zone')
plt.tight_layout()
plt.savefig('zone_barh.png')
plt.show()
โ–ถ Sample Output (text + charts)
    North  South  East  West
Q1     45     38    30    50
Q2     52     41    35    48
Q3     61     47    33    57
Q4     58     55    42    63

Total sales of each zone:
 East     140
South    181
North    216
West     218
dtype: int64
Best quarter: Q4
Output chart: zone_line.png
Output chart: zone_line.png
Output chart: zone_barh.png
Output chart: zone_barh.png
๐Ÿ’ก Explanation: A DataFrame can be plotted directly: df.plot() draws one line per column with an automatic legend; kind='bar' / 'barh' / 'hist' changes the chart type. plt.xlabel(), plt.title() etc. still customise the plot.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q39.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55],
                      'East': [30, 35, 33, 42], 'West': [50, 48, 57, 63]},
      โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'North': [45, 52, 61, 58], 'South': [38, 41,โ€ฆ; the result is stored in variable sales
7
print(sales)
๐Ÿ–ฅ๏ธ Output Displays the value of sales on the screen
8
total = sales.sum().sort_values()
๐Ÿงฎ Store / Calculate Sorts sales.sum() by ; the result is stored in variable total
9
print("\nTotal sales of each zone:\n", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Total sales of each zone:", then the value of total on the screen
10
print("Best quarter:", sales.sum(axis=1).idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Best quarter:", then the value of sales.sum(axis=1).idxmax() on the screen
12
sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5),
           color=['#e03131', '#2f9e44', '#1971c2', '#f08c00'])
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
14
plt.title('Quarterly Sales of Each Zone')
๐Ÿ–ฅ๏ธ Output Writes 'Quarterly Sales of Each Zone' as the title of the chart
15
plt.xlabel('Quarter')
๐Ÿ–ฅ๏ธ Output Writes 'Quarter' as the label of the X-axis
16
plt.ylabel('Sales (Rs. lakh)')
๐Ÿ–ฅ๏ธ Output Writes 'Sales (Rs. lakh)' as the label of the Y-axis
17
plt.grid(linestyle=':')
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
18
plt.savefig('zone_line.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'zone_line.png'
19
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
21
total.plot(kind='barh', color=['#74c0fc', '#63e6be', '#ffa94d', '#ff6b6b'], edgecolor='black', figsize=(8, 4))
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
22
plt.title('Total Annual Sales by Zone')
๐Ÿ–ฅ๏ธ Output Writes 'Total Annual Sales by Zone' as the title of the chart
23
plt.xlabel('Sales (Rs. lakh)')
๐Ÿ–ฅ๏ธ Output Writes 'Sales (Rs. lakh)' as the label of the X-axis
24
plt.ylabel('Zone')
๐Ÿ–ฅ๏ธ Output Writes 'Zone' as the label of the Y-axis
25
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
26
plt.savefig('zone_barh.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'zone_barh.png'
27
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
34
sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55],
45
'East': [30, 35, 33, 42], 'West': [50, 48, 57, 63]},
54
sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55],
66
index=['Q1', 'Q2', 'Q3', 'Q4'])
74
sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55],
sales = DataFrame (4 rows ร— 4 columns)
87
print(sales)
    North  South  East  West
Q1     45     38    30    50
Q2     52     41    35    48
Q3     61     47    33    57
Q4     58     55    42    63
98
total = sales.sum().sort_values()
total = Series (4 values)
109
print("\nTotal sales of each zone:\n", total)
Total sales of each zone:
 East     140
South    181
North    216
West     218
dtype: int64
1110
print("Best quarter:", sales.sum(axis=1).idxmax())
Best quarter: Q4
1212
sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5),
1313
color=['#e03131', '#2f9e44', '#1971c2', '#f08c00'])
1412
sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5),
1514
plt.title('Quarterly Sales of Each Zone')
1615
plt.xlabel('Quarter')
1716
plt.ylabel('Sales (Rs. lakh)')
1817
plt.grid(linestyle=':')
1918
plt.savefig('zone_line.png')
2019
plt.show()
2121
total.plot(kind='barh', color=['#74c0fc', '#63e6be', '#ffa94d', '#ff6b6b'], edgecolor='bla
2222
plt.title('Total Annual Sales by Zone')
2323
plt.xlabel('Sales (Rs. lakh)')
2424
plt.ylabel('Zone')
2525
plt.tight_layout()
2626
plt.savefig('zone_barh.png')
2727
plt.show()
Q40 PYTHON๐Ÿ“Š DATA VISUALIZATION

Data Visualization (CSV to Chart): Import the file student_data.csv (RollNo, Name, Gender, Maths, Science, AI) into a DataFrame. Display the data, the subject-wise average and the gender-wise average. Plot (a) a bar chart of the subject-wise average marks and (b) a line chart comparing Maths and AI marks of every student. Save both charts.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('student_data.csv')
print(df)
avg = df[['Maths', 'Science', 'AI']].mean().round(2)
print("\nSubject-wise average:\n", avg)
print("\nGender-wise average:\n", df.groupby('Gender')[['Maths', 'Science', 'AI']].mean().round(2))

plt.figure(figsize=(7, 4.2))
plt.bar(avg.index, avg.values, color=['#f03e3e', '#37b24d', '#1c7ed6'], width=0.5, edgecolor='black')
for i, v in enumerate(avg.values):
    plt.text(i, v + 1, v, ha='center', fontweight='bold')
plt.ylim(0, 100)
plt.title('Subject-wise Average Marks')
plt.xlabel('Subject')
plt.ylabel('Average marks')
plt.savefig('csv_avg_bar.png')
plt.show()

plt.figure(figsize=(9, 4.5))
plt.plot(df['Name'], df['Maths'], 'g-o', label='Maths')
plt.plot(df['Name'], df['AI'], 'm--^', label='AI')
plt.xticks(rotation=45)
plt.title('Maths vs AI Marks of Students')
plt.xlabel('Student')
plt.ylabel('Marks')
plt.legend()
plt.grid(alpha=0.4)
plt.tight_layout()
plt.savefig('csv_line.png')
plt.show()
โ–ถ Sample Output (text + charts)
    RollNo     Name Gender  Maths  Science  AI
0        1    Aarav      M     78       82  91
1        2   Bhavya      F     88       79  95
2        3   Chetan      M     65       70  72
3        4     Diya      F     92       94  98
4        5  Eklavya      M     55       61  68
5        6    Farah      F     81       85  89
6        7    Gagan      M     73       69  80
7        8     Hina      F     95       90  97
8        9    Ishan      M     60       58  66
9       10     Jiya      F     84       88  90
10      11    Kunal      M     70       74  77
11      12  Lavanya      F     89       92  94
12      13    Manav      M     58       63  71
13      14    Navya      F     76       80  85
14      15       Om      M     82       77  88

Subject-wise average:
 Maths      76.40
Science    77.47
AI         84.07
dtype: float64

Gender-wise average:
         Maths  Science     AI
Gender                       
F       86.43    86.86  92.57
M       67.62    69.25  76.62
Output chart: csv_avg_bar.png
Output chart: csv_avg_bar.png
Output chart: csv_line.png
Output chart: csv_line.png
๐Ÿ’ก Explanation: read_csv() imports the CSV file into a DataFrame; mean() and groupby('Gender').mean() aggregate the data before plotting - this is the 'import / aggregate / plot' practical given in the CBSE list.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q40.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
df = pd.read_csv('student_data.csv')
๐Ÿ“ฆ Library / Data Reads the CSV file 'student_data.csv' into a DataFrame (table); the result is stored in variable df
5
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
6
avg = df[['Maths', 'Science', 'AI']].mean().round(2)
๐Ÿงฎ Store / Calculate Rounds the values of df[['Maths', 'Science', 'AI']].mean() to 2 decimal places; the result is stored in variable avg
7
print("\nSubject-wise average:\n", avg)
๐Ÿ–ฅ๏ธ Output Displays the text "Subject-wise average:", then the value of avg on the screen
8
print("\nGender-wise average:\n", df.groupby('Gender')[['Maths', 'Science', 'AI']].mean().round(2))
๐Ÿ–ฅ๏ธ Output Displays the text "Gender-wise average:", then the value of df.groupby('Gender')[['Maths', 'Science', 'AIโ€ฆ on the screen
10
plt.figure(figsize=(7, 4.2))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
11
plt.bar(avg.index, avg.values, color=['#f03e3e', '#37b24d', '#1c7ed6'], width=0.5, edgecolor='black')
๐Ÿ–ฅ๏ธ Output Draws a bar chart of avg.index, avg.values
12
for i, v in enumerate(avg.values):
๐Ÿ” Loop LOOP over avg.values with position: in each round i, v get (position, item)
13
plt.text(i, v + 1, v, ha='center', fontweight='bold')
๐Ÿ–ฅ๏ธ Output Writes text on the chart
14
plt.ylim(0, 100)
๐Ÿ–ฅ๏ธ Output Sets the range of the Y-axis
15
plt.title('Subject-wise Average Marks')
๐Ÿ–ฅ๏ธ Output Writes 'Subject-wise Average Marks' as the title of the chart
16
plt.xlabel('Subject')
๐Ÿ–ฅ๏ธ Output Writes 'Subject' as the label of the X-axis
17
plt.ylabel('Average marks')
๐Ÿ–ฅ๏ธ Output Writes 'Average marks' as the label of the Y-axis
18
plt.savefig('csv_avg_bar.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'csv_avg_bar.png'
19
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
21
plt.figure(figsize=(9, 4.5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
22
plt.plot(df['Name'], df['Maths'], 'g-o', label='Maths')
๐Ÿ–ฅ๏ธ Output Draws a line chart of df['Name'], df['Maths'], 'g-o'
23
plt.plot(df['Name'], df['AI'], 'm--^', label='AI')
๐Ÿ–ฅ๏ธ Output Draws a line chart of df['Name'], df['AI'], 'm--^'
24
plt.xticks(rotation=45)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
25
plt.title('Maths vs AI Marks of Students')
๐Ÿ–ฅ๏ธ Output Writes 'Maths vs AI Marks of Students' as the title of the chart
26
plt.xlabel('Student')
๐Ÿ–ฅ๏ธ Output Writes 'Student' as the label of the X-axis
27
plt.ylabel('Marks')
๐Ÿ–ฅ๏ธ Output Writes 'Marks' as the label of the Y-axis
28
plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
29
plt.grid(alpha=0.4)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
30
plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
31
plt.savefig('csv_line.png')
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file 'csv_line.png'
32
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import matplotlib.pyplot as plt
34
df = pd.read_csv('student_data.csv')
df = DataFrame (15 rows ร— 6 columns)
45
print(df)
    RollNo     Name Gender  Maths  Science  AI
0        1    Aarav      M     78       82  91
1        2   Bhavya      F     88       79  95
2        3   Chetan      M     65       70  72
3        4     Diya      F     92       94  98
4        5  Eklavya      M     55       61  68
5        6    Fโ€ฆ
56
avg = df[['Maths', 'Science', 'AI']].mean().round(2)
avg = Series (3 values)
67
print("\nSubject-wise average:\n", avg)
Subject-wise average:
 Maths      76.40
Science    77.47
AI         84.07
dtype: float64
78
print("\nGender-wise average:\n", df.groupby('Gender')[['Maths', 'Science', 'AI']].mean().
Gender-wise average:
         Maths  Science     AI
Gender                       
F       86.43    86.86  92.57
M       67.62    69.25  76.62
810
plt.figure(figsize=(7, 4.2))
911
plt.bar(avg.index, avg.values, color=['#f03e3e', '#37b24d', '#1c7ed6'], width=0.5, edgecol
1012
for i, v in enumerate(avg.values):
next item taken
i = 0, v = np.float64(76.4)
1113
plt.text(i, v + 1, v, ha='center', fontweight='bold')
1212
for i, v in enumerate(avg.values):
next item taken
i = 1, v = np.float64(77.47)
1313
plt.text(i, v + 1, v, ha='center', fontweight='bold')
1412
for i, v in enumerate(avg.values):
next item taken
i = 2, v = np.float64(84.07)
1513
plt.text(i, v + 1, v, ha='center', fontweight='bold')
1612
for i, v in enumerate(avg.values):
no items left โ†’ loop ends
1714
plt.ylim(0, 100)
1815
plt.title('Subject-wise Average Marks')
1916
plt.xlabel('Subject')
2017
plt.ylabel('Average marks')
2118
plt.savefig('csv_avg_bar.png')
2219
plt.show()
2321
plt.figure(figsize=(9, 4.5))
2422
plt.plot(df['Name'], df['Maths'], 'g-o', label='Maths')
2523
plt.plot(df['Name'], df['AI'], 'm--^', label='AI')
2624
plt.xticks(rotation=45)
2725
plt.title('Maths vs AI Marks of Students')
2826
plt.xlabel('Student')
2927
plt.ylabel('Marks')
3028
plt.legend()
3129
plt.grid(alpha=0.4)
3230
plt.tight_layout()

โ€ฆ Python runs 2 more line-steps in the same way (loops repeat the same lines). Final values: df = DataFrame (15 rows ร— 6 columns), avg = Series (3 values), i = 2, v = np.float64(84.07)

Q41 SQL NEW 2026-27

SQL: To delete the details of a particular student from the student table (e.g. student_id = 7).

SELECT student_id, name, marks FROM student WHERE student_id = 7;
DELETE FROM student WHERE student_id = 7;
SELECT COUNT(*) AS Students_Left FROM student;
-- Put the record back so later practicals give the same results
INSERT INTO student VALUES (7,12,'B','M','Vivek Yadav','2007-11-30',48.0,'vivek@kvsb.in');
โ–ถ Sample Output
mysql> SELECT student_id, name, marks FROM student WHERE student_id = 7;
+------------+-------------+-------+
| student_id | name        | marks |
+------------+-------------+-------+
|          7 | Vivek Yadav | 48.00 |
+------------+-------------+-------+
1 row in set (0.00 sec)

mysql> DELETE FROM student WHERE student_id = 7;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT COUNT(*) AS Students_Left FROM student;
+---------------+
| Students_Left |
+---------------+
|             9 |
+---------------+
1 row in set (0.00 sec)

mysql> INSERT INTO student VALUES (7,12,'B','M','Vivek Yadav','2007-11-30',48.0,'vivek@kvsb.in');
Query OK, 1 row affected (0.00 sec)
๐Ÿ’ก Explanation: DELETE removes whole rows. Always use a WHERE clause โ€” DELETE FROM student; without WHERE empties the full table (the structure stays). We re-insert the row so the next practicals show the same data.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, marks FROM student WHERE student_id = 7;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE student_id = 7 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, marks โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
2
DML ยท data change
DELETE FROM student WHERE student_id = 7;

Removes rows from table student.

  1. FROM student โ†’ picks the table.
  2. WHERE student_id = 7 โ†’ finds the matching rows.
  3. Those rows are removed permanently โ†’ "Query OK, n rows affected".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE student_id = 7 โ†’ 1 row(s) matched.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in๐Ÿ—‘
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: Query OK, 1 row affected
3
Query ยท read only
SELECT COUNT(*) AS Students_Left FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT COUNT(*) AS Students_Left โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 9 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
โœ” Result: 1 row in set
๐Ÿ“Œ Put the record back so later practicals give the same results
4
DML ยท data change
INSERT INTO student VALUES (7,12,'B','M','Vivek Yadav','2007-11-30',48.0,'vivek@kvsb.in');

Adds one new row into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 1 row affected
Q42 SQL NEW 2026-27

SQL: To display the details of students who scored more than 80 marks.

SELECT student_id, name, section, marks
FROM student
WHERE marks > 80
ORDER BY marks DESC;
โ–ถ Sample Output
mysql> SELECT student_id, name, section, marks
    -> FROM student
    -> WHERE marks > 80
    -> ORDER BY marks DESC;
+------------+------------+---------+-------+
| student_id | name       | section | marks |
+------------+------------+---------+-------+
|          8 | Neha Gupta | A       | 95.00 |
|          2 | Sara Khan  | B       | 92.00 |
|          1 | Amit Kumar | A       | 88.50 |
|          6 | Angad Kaur | A       | 81.00 |
+------------+------------+---------+-------+
4 rows in set (0.00 sec)
๐Ÿ’ก Explanation: WHERE filters rows with a condition (>, <, =, >=, <=, <>). ORDER BY marks DESC shows toppers first โ€” like preparing a merit list.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT student_id, name, section, marks
FROM student
WHERE marks > 80
ORDER BY marks DESC;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks > 80 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT student_id, name, section, marks โ†’ picks the columns / calculates the values to show.
  4. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
โœ” Result: 4 rows in set
Q43 SQL NEW 2026-27

SQL: To find the minimum, maximum, sum and average of the marks in the student table.

SELECT MIN(marks)           AS Minimum,
       MAX(marks)           AS Maximum,
       SUM(marks)           AS Total,
       ROUND(AVG(marks), 2) AS Average
FROM student;
โ–ถ Sample Output
mysql> SELECT MIN(marks)           AS Minimum,
    ->        MAX(marks)           AS Maximum,
    ->        SUM(marks)           AS Total,
    ->        ROUND(AVG(marks), 2) AS Average
    -> FROM student;
+---------+---------+--------+---------+
| Minimum | Maximum | Total  | Average |
+---------+---------+--------+---------+
|   48.00 |   95.00 | 736.50 |   73.65 |
+---------+---------+--------+---------+
1 row in set (0.00 sec)
๐Ÿ’ก Explanation: Aggregate (multi-row) functions take a whole column and return one value. ROUND(AVG(marks),2) keeps the average to 2 decimal places.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
Query ยท read only
SELECT MIN(marks)           AS Minimum,
       MAX(marks)           AS Maximum,
       SUM(marks)           AS Total,
       ROUND(AVG(marks), 2) AS Average
FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT MIN(marks) AS Minimum, MAX(marks) AS Maximum, SUM(marks) AS Total, ROUND(AVG(marks), 2) AS Average โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: MIN() finds the smallest value; MAX() finds the largest value; SUM() adds the values; ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 10 rows are taken.

student_idclasssectiongendernamedobmarksemail
112AMAmit Kumar2008-05-1488.50amit@kvsb.in
212BFSara Khan2008-08-2192.00sara@kvsb.in
312AMRahul Sharma2007-12-0265.50rahul@kvsb.in
412AFPriya Singh2008-03-1178.00priya@kvsb.in
512BMAnand Verma2008-07-1955.00anand@kvsb.in
612AFAngad Kaur2008-01-2581.00angad@kvsb.in
812AFNeha Gupta2008-09-0995.00neha@kvsb.in
912BMKaran Mehta2008-04-1760.00karan@kvsb.in
1012AFDivya Rao2007-10-0573.50divya@kvsb.in
712BMVivek Yadav2007-11-3048.00vivek@kvsb.in
โœ” Result: 1 row in set
Q44 SQL NEW 2026-27

SQL: To find the total number of customers from each country in the table customer (customer_id, customer_name, country) using GROUP BY.

CREATE TABLE customer (
    customer_id   INT PRIMARY KEY,
    customer_name VARCHAR(30),
    country       VARCHAR(20)
);
INSERT INTO customer VALUES
 (101,'Ravi Traders','India'), (102,'Lee Mart','Singapore'),
 (103,'Sharma Stores','India'), (104,'John Supplies','USA'),
 (105,'Tan Foods','Singapore'), (106,'Gupta Agencies','India'),
 (107,'Mary Books','USA'), (108,'Ali Exports','UAE');

SELECT country, COUNT(*) AS Total_Customers
FROM customer
GROUP BY country
ORDER BY Total_Customers DESC, country;
โ–ถ Sample Output
mysql> CREATE TABLE customer (
    ->     customer_id   INT PRIMARY KEY,
    ->     customer_name VARCHAR(30),
    ->     country       VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO customer VALUES
    ->  (101,'Ravi Traders','India'), (102,'Lee Mart','Singapore'),
    ->  (103,'Sharma Stores','India'), (104,'John Supplies','USA'),
    ->  (105,'Tan Foods','Singapore'), (106,'Gupta Agencies','India'),
    ->  (107,'Mary Books','USA'), (108,'Ali Exports','UAE');
Query OK, 8 rows affected (0.00 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> SELECT country, COUNT(*) AS Total_Customers
    -> FROM customer
    -> GROUP BY country
    -> ORDER BY Total_Customers DESC, country;
+-----------+-----------------+
| country   | Total_Customers |
+-----------+-----------------+
| India     |               3 |
| Singapore |               2 |
| USA       |               2 |
| UAE       |               1 |
+-----------+-----------------+
4 rows in set (0.00 sec)
๐Ÿ’ก Explanation: GROUP BY makes one group per country and COUNT(*) counts the rows in each group. Add HAVING COUNT(*) > 1 to show only countries with more than one customer.
NEW ๐Ÿ” How these queries run - step by step, with animation

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
  2. First select your database, e.g. USE school; (the table must already be created).
  3. Type each statement and end it with a semicolon ; then press Enter. A long query can go on many lines - MySQL shows -> until it sees ;.
  4. Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
  5. Write the query + output in your practical file.
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
1
DDL ยท structure
CREATE TABLE customer (
    customer_id   INT PRIMARY KEY,
    customer_name VARCHAR(30),
    country       VARCHAR(20)
);

Creates a new table customer with 3 columns. Each column gets a name and a data type:

  • customer_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • customer_name โ†’ VARCHAR(30) (text up to 30 characters)
  • country โ†’ VARCHAR(20) (text up to 20 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
2
DML ยท data change
INSERT INTO customer VALUES
 (101,'Ravi Traders','India'), (102,'Lee Mart','Singapore'),
 (103,'Sharma Stores','India'), (104,'John Supplies','USA'),
 (105,'Tan Foods','Singapore'), (106,'Gupta Agencies','India'),
 (107,'Mary Books','USA'), (108,'Ali Exports','UAE');

Adds 8 new rows into table customer.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 8 rows affected ยท Records: 8 Duplicates: 0 Warnings: 0
3
Query ยท read only
SELECT country, COUNT(*) AS Total_Customers
FROM customer
GROUP BY country
ORDER BY Total_Customers DESC, country;

Fetches rows from customer, grouped by country, in sorted order.

  1. FROM customer โ†’ MySQL first opens table customer and looks at all its rows.
  2. GROUP BY country โ†’ makes groups: rows with the same country go into one group (one output row per group).
  3. SELECT country, COUNT(*) AS Total_Customers โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
  5. ORDER BY Total_Customers DESC, country โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table customer - all 8 rows are taken.

customer_idcustomer_namecountry
101Ravi TradersIndia
102Lee MartSingapore
103Sharma StoresIndia
104John SuppliesUSA
105Tan FoodsSingapore
106Gupta AgenciesIndia
107Mary BooksUSA
108Ali ExportsUAE
โœ” Result: 4 rows in set
Q45 PYTHON NEW 2026-27

Create a Series and print all the elements that are above the 75th percentile.

import pandas as pd

marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50],
                  index=['Amit', 'Sara', 'Neha', 'Rahul', 'Priya',
                         'Karan', 'Divya', 'Vivek', 'Angad', 'Anand'])
print("Marks Series:")
print(marks)

q75 = marks.quantile(0.75)          # 75th percentile
print("\n75th percentile value =", q75)

print("\nStudents above the 75th percentile:")
print(marks[marks > q75])
โ–ถ Sample Output
Marks Series:
Amit     45
Sara     78
Neha     92
Rahul    66
Priya    88
Karan    59
Divya    95
Vivek    71
Angad    83
Anand    50
dtype: int64

75th percentile value = 86.75

Students above the 75th percentile:
Neha     92
Priya    88
Divya    95
dtype: int64
๐Ÿ’ก Explanation: quantile(0.75) returns the value below which 75% of the data lies. The Boolean mask marks > q75 keeps only the top 25% โ€” a quick way to find the toppers of a class.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ip_q45.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50],
                  index=['Amit', 'Sara', 'Neha', 'Rahul', 'Priya',
                         'Karaโ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas Series (one labelled column) from [45, 78, 92, 66, 88, 59, 95, 71, 83, 50]; the result is stored in variable marks
6
print("Marks Series:")
๐Ÿ–ฅ๏ธ Output Displays the text "Marks Series:" on the screen
7
print(marks)
๐Ÿ–ฅ๏ธ Output Displays the value of marks on the screen
9
q75 = marks.quantile(0.75)          # 75th percentile
๐Ÿงฎ Store / Calculate Finds the quantile 0.75 of marks; the result is stored in variable q75
10
print("\n75th percentile value =", q75)
๐Ÿ–ฅ๏ธ Output Displays the text "75th percentile value =", then the value of q75 on the screen
12
print("\nStudents above the 75th percentile:")
๐Ÿ–ฅ๏ธ Output Displays the text "Students above the 75th percentilโ€ฆ" on the screen
13
print(marks[marks > q75])
๐Ÿ–ฅ๏ธ Output Displays the value of marks[marks > q75] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50],
34
index=['Amit', 'Sara', 'Neha', 'Rahul', 'Priya',
43
marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50],
marks = Series (10 values)
56
print("Marks Series:")
Marks Series:
67
print(marks)
Amit     45
Sara     78
Neha     92
Rahul    66
Priya    88
Karan    59
Divya    95
Vivek    71
Angad    83
Anand    50
dtype: int64
79
q75 = marks.quantile(0.75)          # 75th percentile
q75 = np.float64(86.75)
810
print("\n75th percentile value =", q75)
75th percentile value = 86.75
912
print("\nStudents above the 75th percentile:")
Students above the 75th percentile:
1013
print(marks[marks > q75])
Neha     92
Priya    88
Divya    95
dtype: int64

๐Ÿ“ Project Reference

PROJECT โ€” Informatics Practices (KVS Project Reference)

Use the official KVS test project link to generate/practice a sample project:
http://python.mykvs.in/uploads/showpapers/testproject.php

Recommended IP project areas: school fee/attendance analytics using Pandas + Matplotlib,
CSV/MySQL-backed data dashboards, and simple data-visualisation tools built on the SQL
student table created in practicals 20-33 above.

๐Ÿค– Class IX โ€” Artificial Intelligence (417)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 31 Practicals (24 Python programs + 7 activities) as per CBSE curriculum 2026-27

๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

๐Ÿ“‘ CBSE Practical Assessment Scheme โ€” Class IX AI (417)

ComponentMarks
Practical File (minimum 15 programs)15
Practical Examination - any 3 programs on input/output, variables, operators, expressions, data types, flow of control and lists15
Viva Voce5
Project Work / Field Visit / Student Portfolio (related to SDGs)15
TOTAL (Practical)50

Theory 50 + Practical 50 = 100. Every Python program below was run and its real output is shown; activities give the procedure and a model answer for the practical file.

Q1 PYTHON

PRINT: Write a program to print personal information like Name, Father's Name, Class and School Name.

# Program 1 : Personal information using print()
print("------ MY PERSONAL INFORMATION ------")
print("Name          : Aarav Sharma")
print("Father's Name : Mr. Rajesh Sharma")
print("Class         : IX - A")
print("School Name   : PM SHRI Kendriya Vidyalaya Shalimar Bagh")
print("-------------------------------------")
โ–ถ Sample Output
------ MY PERSONAL INFORMATION ------
Name          : Aarav Sharma
Father's Name : Mr. Rajesh Sharma
Class         : IX - A
School Name   : PM SHRI Kendriya Vidyalaya Shalimar Bagh
-------------------------------------
๐Ÿ’ก Explanation: print() displays text on the screen. Text is written inside double quotes; a single quote in Father's is allowed inside double quotes. Each print() starts on a new line.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q1.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 1 : Personal information using print()
2
print("------ MY PERSONAL INFORMATION ------")
๐Ÿ–ฅ๏ธ Output Displays the text "------ MY PERSONAL INFORMATION --โ€ฆ" on the screen
3
print("Name          : Aarav Sharma")
๐Ÿ–ฅ๏ธ Output Displays the text "Name : Aarav Sharma" on the screen
4
print("Father's Name : Mr. Rajesh Sharma")
๐Ÿ–ฅ๏ธ Output Displays the text "Father's Name : Mr. Rajesh Sharma" on the screen
5
print("Class         : IX - A")
๐Ÿ–ฅ๏ธ Output Displays the text "Class : IX - A" on the screen
6
print("School Name   : PM SHRI Kendriya Vidyalaya Shalimar Bagh")
๐Ÿ–ฅ๏ธ Output Displays the text "School Name : PM SHRI Kendriya Viโ€ฆ" on the screen
7
print("-------------------------------------")
๐Ÿ–ฅ๏ธ Output Displays the text "---------------------------------โ€ฆ" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
print("------ MY PERSONAL INFORMATION ------")
------ MY PERSONAL INFORMATION ------
23
print("Name          : Aarav Sharma")
Name          : Aarav Sharma
34
print("Father's Name : Mr. Rajesh Sharma")
Father's Name : Mr. Rajesh Sharma
45
print("Class         : IX - A")
Class         : IX - A
56
print("School Name   : PM SHRI Kendriya Vidyalaya Shalimar Bagh")
School Name   : PM SHRI Kendriya Vidyalaya Shalimar Bagh
67
print("-------------------------------------")
-------------------------------------
Q2 PYTHON

PRINT: Write a program to print the following patterns using multiple print commands (right-angled triangle and inverted triangle of stars).

# Program 2 : Star patterns with multiple print() commands
print("Pattern 1")
print("*")
print("* *")
print("* * *")
print("* * * *")
print("* * * * *")
print()
print("Pattern 2")
print("* * * * *")
print("* * * *")
print("* * *")
print("* *")
print("*")
โ–ถ Sample Output
Pattern 1
*
* *
* * *
* * * *
* * * * *

Pattern 2
* * * * *
* * * *
* * *
* *
*
๐Ÿ’ก Explanation: Each print() prints one row. print() with nothing inside prints a blank line to separate the two patterns. (Later, using a for loop, the same pattern can be printed with: for i in range(1,6): print('* ' * i).)
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q2.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 2 : Star patterns with multiple print() commands
2
print("Pattern 1")
๐Ÿ–ฅ๏ธ Output Displays the text "Pattern 1" on the screen
3
print("*")
๐Ÿ–ฅ๏ธ Output Displays the text "*" on the screen
4
print("* *")
๐Ÿ–ฅ๏ธ Output Displays the text "* *" on the screen
5
print("* * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * *" on the screen
6
print("* * * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * * *" on the screen
7
print("* * * * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * * * *" on the screen
8
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
9
print("Pattern 2")
๐Ÿ–ฅ๏ธ Output Displays the text "Pattern 2" on the screen
10
print("* * * * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * * * *" on the screen
11
print("* * * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * * *" on the screen
12
print("* * *")
๐Ÿ–ฅ๏ธ Output Displays the text "* * *" on the screen
13
print("* *")
๐Ÿ–ฅ๏ธ Output Displays the text "* *" on the screen
14
print("*")
๐Ÿ–ฅ๏ธ Output Displays the text "*" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
print("Pattern 1")
Pattern 1
23
print("*")
*
34
print("* *")
* *
45
print("* * *")
* * *
56
print("* * * *")
* * * *
67
print("* * * * *")
* * * * *
78
print()
89
print("Pattern 2")
Pattern 2
910
print("* * * * *")
* * * * *
1011
print("* * * *")
* * * *
1112
print("* * *")
* * *
1213
print("* *")
* *
1314
print("*")
*
Q3 PYTHON

PRINT: Write a program to find the square of number 7.

# Program 3 : Square of 7
num = 7
square = num * num          # or num ** 2
print("Number =", num)
print("Square of", num, "is", square)
โ–ถ Sample Output
Number = 7
Square of 7 is 49
๐Ÿ’ก Explanation: A variable num stores 7. The * operator multiplies (7 x 7 = 49). The exponent operator ** can also be used: num ** 2.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 3 : Square of 7
2
num = 7
๐Ÿงฎ Store / Calculate Stores the number 7 in variable num
3
square = num * num          # or num ** 2
๐Ÿงฎ Store / Calculate Stores the value of num * num (calculated using ร—) in variable square
4
print("Number =", num)
๐Ÿ–ฅ๏ธ Output Displays the text "Number =", then the value of num on the screen
5
print("Square of", num, "is", square)
๐Ÿ–ฅ๏ธ Output Displays the text "Square of", then the value of num, then the text "is", then the value of square on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
num = 7
num = 7
23
square = num * num          # or num ** 2
square = 49
34
print("Number =", num)
Number = 7
45
print("Square of", num, "is", square)
Square of 7 is 49
Q4 PYTHON

PRINT: Write a program to find the sum of two numbers 15 and 20.

# Program 4 : Sum of two numbers
a = 15
b = 20
total = a + b
print("First number  =", a)
print("Second number =", b)
print("Sum =", total)
โ–ถ Sample Output
First number  = 15
Second number = 20
Sum = 35
๐Ÿ’ก Explanation: Two variables are added with the + arithmetic operator and the result is stored in the variable total.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 4 : Sum of two numbers
2
a = 15
๐Ÿงฎ Store / Calculate Stores the number 15 in variable a
3
b = 20
๐Ÿงฎ Store / Calculate Stores the number 20 in variable b
4
total = a + b
๐Ÿงฎ Store / Calculate Stores the value of a + b (calculated using +) in variable total
5
print("First number  =", a)
๐Ÿ–ฅ๏ธ Output Displays the text "First number =", then the value of a on the screen
6
print("Second number =", b)
๐Ÿ–ฅ๏ธ Output Displays the text "Second number =", then the value of b on the screen
7
print("Sum =", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum =", then the value of total on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
a = 15
a = 15
23
b = 20
b = 20
34
total = a + b
total = 35
45
print("First number  =", a)
First number  = 15
56
print("Second number =", b)
Second number = 20
67
print("Sum =", total)
Sum = 35
Q5 PYTHON

PRINT: Write a program to convert length given in kilometers into meters.

# Program 5 : Kilometre to metre conversion
km = 5.5                    # length in kilometres
meters = km * 1000          # 1 km = 1000 m
print("Length in kilometres =", km, "km")
print("Length in metres     =", meters, "m")
โ–ถ Sample Output
Length in kilometres = 5.5 km
Length in metres     = 5500.0 m
๐Ÿ’ก Explanation: 1 kilometre = 1000 metres, so multiplying by 1000 converts km to m. Since km is a float (5.5), the result 5500.0 is also a float.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 5 : Kilometre to metre conversion
2
km = 5.5                    # length in kilometres
๐Ÿงฎ Store / Calculate Stores the number 5.5 in variable km
3
meters = km * 1000          # 1 km = 1000 m
๐Ÿงฎ Store / Calculate Stores the value of km * 1000 (calculated using ร—) in variable meters
4
print("Length in kilometres =", km, "km")
๐Ÿ–ฅ๏ธ Output Displays the text "Length in kilometres =", then the value of km, then the text "km" on the screen
5
print("Length in metres     =", meters, "m")
๐Ÿ–ฅ๏ธ Output Displays the text "Length in metres =", then the value of meters, then the text "m" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
km = 5.5                    # length in kilometres
km = 5.5
23
meters = km * 1000          # 1 km = 1000 m
meters = 5500.0
34
print("Length in kilometres =", km, "km")
Length in kilometres = 5.5 km
45
print("Length in metres     =", meters, "m")
Length in metres     = 5500.0 m
Q6 PYTHON

PRINT: Write a program to print the table of 5 up to five terms.

# Program 6 : Table of 5 (five terms)
n = 5
print("Table of", n)
print(n, "x 1 =", n * 1)
print(n, "x 2 =", n * 2)
print(n, "x 3 =", n * 3)
print(n, "x 4 =", n * 4)
print(n, "x 5 =", n * 5)
โ–ถ Sample Output
Table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
๐Ÿ’ก Explanation: Arithmetic expressions can be written directly inside print(). The comma in print() inserts a space between the values.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 6 : Table of 5 (five terms)
2
n = 5
๐Ÿงฎ Store / Calculate Stores the number 5 in variable n
3
print("Table of", n)
๐Ÿ–ฅ๏ธ Output Displays the text "Table of", then the value of n on the screen
4
print(n, "x 1 =", n * 1)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "x 1 =", then the value of n * 1 on the screen
5
print(n, "x 2 =", n * 2)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "x 2 =", then the value of n * 2 on the screen
6
print(n, "x 3 =", n * 3)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "x 3 =", then the value of n * 3 on the screen
7
print(n, "x 4 =", n * 4)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "x 4 =", then the value of n * 4 on the screen
8
print(n, "x 5 =", n * 5)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "x 5 =", then the value of n * 5 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
n = 5
n = 5
23
print("Table of", n)
Table of 5
34
print(n, "x 1 =", n * 1)
5 x 1 = 5
45
print(n, "x 2 =", n * 2)
5 x 2 = 10
56
print(n, "x 3 =", n * 3)
5 x 3 = 15
67
print(n, "x 4 =", n * 4)
5 x 4 = 20
78
print(n, "x 5 =", n * 5)
5 x 5 = 25
Q7 PYTHON

PRINT: Write a program to calculate Simple Interest if principle_amount = 2000, rate_of_interest = 4.5 and time = 10.

# Program 7 : Simple Interest
principle_amount = 2000
rate_of_interest = 4.5
time = 10
simple_interest = (principle_amount * rate_of_interest * time) / 100
amount = principle_amount + simple_interest
print("Principle amount =", principle_amount)
print("Rate of interest =", rate_of_interest, "%")
print("Time             =", time, "years")
print("Simple Interest  =", simple_interest)
print("Total amount     =", amount)
โ–ถ Sample Output
Principle amount = 2000
Rate of interest = 4.5 %
Time             = 10 years
Simple Interest  = 900.0
Total amount     = 2900.0
๐Ÿ’ก Explanation: Formula: SI = (P x R x T) / 100 = (2000 x 4.5 x 10) / 100 = 900.0. Total amount = P + SI = 2900.0.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 7 : Simple Interest
2
principle_amount = 2000
๐Ÿงฎ Store / Calculate Stores the number 2000 in variable principle_amount
3
rate_of_interest = 4.5
๐Ÿงฎ Store / Calculate Stores the number 4.5 in variable rate_of_interest
4
time = 10
๐Ÿงฎ Store / Calculate Stores the number 10 in variable time
5
simple_interest = (principle_amount * rate_of_interest * time) / 100
๐Ÿงฎ Store / Calculate Stores the value of (principle_amount * rate_of_interest * time) โ€ฆ (calculated using รท) in variable simple_interest
6
amount = principle_amount + simple_interest
๐Ÿงฎ Store / Calculate Stores the value of principle_amount + simple_interest (calculated using +) in variable amount
7
print("Principle amount =", principle_amount)
๐Ÿ–ฅ๏ธ Output Displays the text "Principle amount =", then the value of principle_amount on the screen
8
print("Rate of interest =", rate_of_interest, "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Rate of interest =", then the value of rate_of_interest, then the text "%" on the screen
9
print("Time             =", time, "years")
๐Ÿ–ฅ๏ธ Output Displays the text "Time =", then the value of time, then the text "years" on the screen
10
print("Simple Interest  =", simple_interest)
๐Ÿ–ฅ๏ธ Output Displays the text "Simple Interest =", then the value of simple_interest on the screen
11
print("Total amount     =", amount)
๐Ÿ–ฅ๏ธ Output Displays the text "Total amount =", then the value of amount on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
principle_amount = 2000
principle_amount = 2000
23
rate_of_interest = 4.5
rate_of_interest = 4.5
34
time = 10
time = 10
45
simple_interest = (principle_amount * rate_of_interest * time) / 100
simple_interest = 900.0
56
amount = principle_amount + simple_interest
amount = 2900.0
67
print("Principle amount =", principle_amount)
Principle amount = 2000
78
print("Rate of interest =", rate_of_interest, "%")
Rate of interest = 4.5 %
89
print("Time             =", time, "years")
Time             = 10 years
910
print("Simple Interest  =", simple_interest)
Simple Interest  = 900.0
1011
print("Total amount     =", amount)
Total amount     = 2900.0
Q8 PYTHON

INPUT: Write a program to calculate the Area and Perimeter of a rectangle.

# Program 8 : Area and perimeter of a rectangle
length = float(input("Enter length of the rectangle : "))
breadth = float(input("Enter breadth of the rectangle: "))
area = length * breadth
perimeter = 2 * (length + breadth)
print("Area of rectangle      =", area)
print("Perimeter of rectangle =", perimeter)
โ–ถ Sample Output
Enter length of the rectangle : 12
Enter breadth of the rectangle: 8
Area of rectangle      = 96.0
Perimeter of rectangle = 40.0
๐Ÿ’ก Explanation: input() always returns a string, so float() converts it to a decimal number. Area = l x b, Perimeter = 2 (l + b).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ length, breadth
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 12, 8 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 8 : Area and perimeter of a rectangle
2
length = float(input("Enter length of the rectangle : "))
โŒจ๏ธ Input Shows "Enter length of the rectangle : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable length
3
breadth = float(input("Enter breadth of the rectangle: "))
โŒจ๏ธ Input Shows "Enter breadth of the rectangle: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable breadth
4
area = length * breadth
๐Ÿงฎ Store / Calculate Stores the value of length * breadth (calculated using ร—) in variable area
5
perimeter = 2 * (length + breadth)
๐Ÿงฎ Store / Calculate Stores the value of 2 * (length + breadth) (calculated using ร—) in variable perimeter
6
print("Area of rectangle      =", area)
๐Ÿ–ฅ๏ธ Output Displays the text "Area of rectangle =", then the value of area on the screen
7
print("Perimeter of rectangle =", perimeter)
๐Ÿ–ฅ๏ธ Output Displays the text "Perimeter of rectangle =", then the value of perimeter on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
length = float(input("Enter length of the rectangle : "))
length = 12.0
Enter length of the rectangle : 12
23
breadth = float(input("Enter breadth of the rectangle: "))
breadth = 8.0
Enter breadth of the rectangle: 8
34
area = length * breadth
area = 96.0
45
perimeter = 2 * (length + breadth)
perimeter = 40.0
56
print("Area of rectangle      =", area)
Area of rectangle      = 96.0
67
print("Perimeter of rectangle =", perimeter)
Perimeter of rectangle = 40.0
Q9 PYTHON

INPUT: Write a program to calculate the Area of a triangle with Base and Height.

# Program 9 : Area of a triangle
base = float(input("Enter base of the triangle  : "))
height = float(input("Enter height of the triangle: "))
area = 0.5 * base * height
print("Area of triangle =", area)
โ–ถ Sample Output
Enter base of the triangle  : 10
Enter height of the triangle: 6
Area of triangle = 30.0
๐Ÿ’ก Explanation: Area of a triangle = 1/2 x base x height. 0.5 is used in place of 1/2.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ base, height
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10, 6 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 9 : Area of a triangle
2
base = float(input("Enter base of the triangle  : "))
โŒจ๏ธ Input Shows "Enter base of the triangle : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable base
3
height = float(input("Enter height of the triangle: "))
โŒจ๏ธ Input Shows "Enter height of the triangle: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable height
4
area = 0.5 * base * height
๐Ÿงฎ Store / Calculate Stores the value of 0.5 * base * height (calculated using ร—) in variable area
5
print("Area of triangle =", area)
๐Ÿ–ฅ๏ธ Output Displays the text "Area of triangle =", then the value of area on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
base = float(input("Enter base of the triangle  : "))
base = 10.0
Enter base of the triangle  : 10
23
height = float(input("Enter height of the triangle: "))
height = 6.0
Enter height of the triangle: 6
34
area = 0.5 * base * height
area = 30.0
45
print("Area of triangle =", area)
Area of triangle = 30.0
Q10 PYTHON

INPUT: Write a program to calculate the average marks of 3 subjects.

# Program 10 : Average marks of 3 subjects
eng = float(input("Enter marks in English    : "))
maths = float(input("Enter marks in Maths      : "))
sci = float(input("Enter marks in Science    : "))
total = eng + maths + sci
average = total / 3
print("Total marks   =", total)
print("Average marks =", round(average, 2))
โ–ถ Sample Output
Enter marks in English    : 78
Enter marks in Maths      : 92
Enter marks in Science    : 85
Total marks   = 255.0
Average marks = 85.0
๐Ÿ’ก Explanation: Average = sum of marks / number of subjects. round(value, 2) shows the answer up to 2 decimal places.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ eng, maths, sci
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 78, 92, 85 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 10 : Average marks of 3 subjects
2
eng = float(input("Enter marks in English    : "))
โŒจ๏ธ Input Shows "Enter marks in English : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable eng
3
maths = float(input("Enter marks in Maths      : "))
โŒจ๏ธ Input Shows "Enter marks in Maths : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable maths
4
sci = float(input("Enter marks in Science    : "))
โŒจ๏ธ Input Shows "Enter marks in Science : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable sci
5
total = eng + maths + sci
๐Ÿงฎ Store / Calculate Stores the value of eng + maths + sci (calculated using +) in variable total
6
average = total / 3
๐Ÿงฎ Store / Calculate Stores the value of total / 3 (calculated using รท) in variable average
7
print("Total marks   =", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Total marks =", then the value of total on the screen
8
print("Average marks =", round(average, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Average marks =", then the value of round(average, 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
eng = float(input("Enter marks in English    : "))
eng = 78.0
Enter marks in English    : 78
23
maths = float(input("Enter marks in Maths      : "))
maths = 92.0
Enter marks in Maths      : 92
34
sci = float(input("Enter marks in Science    : "))
sci = 85.0
Enter marks in Science    : 85
45
total = eng + maths + sci
total = 255.0
56
average = total / 3
average = 85.0
67
print("Total marks   =", total)
Total marks   = 255.0
78
print("Average marks =", round(average, 2))
Average marks = 85.0
Q11 PYTHON

INPUT: Write a program to calculate the discounted amount with discount %.

# Program 11 : Discounted amount
price = float(input("Enter the marked price (Rs.): "))
disc_percent = float(input("Enter discount %          : "))
discount = price * disc_percent / 100
final_amount = price - discount
print("Discount given   = Rs.", discount)
print("Amount to be paid = Rs.", final_amount)
โ–ถ Sample Output
Enter the marked price (Rs.): 1500
Enter discount %          : 20
Discount given   = Rs. 300.0
Amount to be paid = Rs. 1200.0
๐Ÿ’ก Explanation: Discount = Price x Discount% / 100 and Amount to pay = Price - Discount. For Rs.1500 at 20%: discount = 300, amount = 1200.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ price, disc_percent
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1500, 20 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 11 : Discounted amount
2
price = float(input("Enter the marked price (Rs.): "))
โŒจ๏ธ Input Shows "Enter the marked price (Rs.): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable price
3
disc_percent = float(input("Enter discount %          : "))
โŒจ๏ธ Input Shows "Enter discount % : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable disc_percent
4
discount = price * disc_percent / 100
๐Ÿงฎ Store / Calculate Stores the value of price * disc_percent / 100 (calculated using รท) in variable discount
5
final_amount = price - discount
๐Ÿงฎ Store / Calculate Stores the value of price - discount (calculated using -) in variable final_amount
6
print("Discount given   = Rs.", discount)
๐Ÿ–ฅ๏ธ Output Displays the text "Discount given = Rs.", then the value of discount on the screen
7
print("Amount to be paid = Rs.", final_amount)
๐Ÿ–ฅ๏ธ Output Displays the text "Amount to be paid = Rs.", then the value of final_amount on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
price = float(input("Enter the marked price (Rs.): "))
price = 1500.0
Enter the marked price (Rs.): 1500
23
disc_percent = float(input("Enter discount %          : "))
disc_percent = 20.0
Enter discount %          : 20
34
discount = price * disc_percent / 100
discount = 300.0
45
final_amount = price - discount
final_amount = 1200.0
56
print("Discount given   = Rs.", discount)
Discount given   = Rs. 300.0
67
print("Amount to be paid = Rs.", final_amount)
Amount to be paid = Rs. 1200.0
Q12 PYTHON

INPUT: Write a program to calculate the Surface Area and Volume of a Cuboid.

# Program 12 : Surface area and volume of a cuboid
l = float(input("Enter length  : "))
b = float(input("Enter breadth : "))
h = float(input("Enter height  : "))
surface_area = 2 * (l*b + b*h + h*l)
volume = l * b * h
print("Total surface area of cuboid =", surface_area)
print("Volume of cuboid             =", volume)
โ–ถ Sample Output
Enter length  : 5
Enter breadth : 4
Enter height  : 3
Total surface area of cuboid = 94.0
Volume of cuboid             = 60.0
๐Ÿ’ก Explanation: Total Surface Area = 2(lb + bh + hl) and Volume = l x b x h.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ l, b, h
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 5, 4, 3 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 12 : Surface area and volume of a cuboid
2
l = float(input("Enter length  : "))
โŒจ๏ธ Input Shows "Enter length : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable l
3
b = float(input("Enter breadth : "))
โŒจ๏ธ Input Shows "Enter breadth : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable b
4
h = float(input("Enter height  : "))
โŒจ๏ธ Input Shows "Enter height : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable h
5
surface_area = 2 * (l*b + b*h + h*l)
๐Ÿงฎ Store / Calculate Stores the value of 2 * (l*b + b*h + h*l) (calculated using ร—) in variable surface_area
6
volume = l * b * h
๐Ÿงฎ Store / Calculate Stores the value of l * b * h (calculated using ร—) in variable volume
7
print("Total surface area of cuboid =", surface_area)
๐Ÿ–ฅ๏ธ Output Displays the text "Total surface area of cuboid =", then the value of surface_area on the screen
8
print("Volume of cuboid             =", volume)
๐Ÿ–ฅ๏ธ Output Displays the text "Volume of cuboid =", then the value of volume on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
l = float(input("Enter length  : "))
l = 5.0
Enter length  : 5
23
b = float(input("Enter breadth : "))
b = 4.0
Enter breadth : 4
34
h = float(input("Enter height  : "))
h = 3.0
Enter height  : 3
45
surface_area = 2 * (l*b + b*h + h*l)
surface_area = 94.0
56
volume = l * b * h
volume = 60.0
67
print("Total surface area of cuboid =", surface_area)
Total surface area of cuboid = 94.0
78
print("Volume of cuboid             =", volume)
Volume of cuboid             = 60.0
Q13 PYTHON

LIST: Create a list of children selected for science quiz - Arjun, Sonakshi, Vikram, Sandhya, Sonal, Isha, Kartik. Perform in sequence: print the whole list, delete 'Vikram', add 'Jay' at the end, remove the item at the second position.

# Program 13 : Operations on a list of names
quiz = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"]
print("Whole list           :", quiz)

quiz.remove("Vikram")          # delete by value
print("After deleting Vikram:", quiz)

quiz.append("Jay")             # add at the end
print("After adding Jay     :", quiz)

del quiz[1]                    # second position = index 1
print("After removing item at 2nd position:", quiz)
โ–ถ Sample Output
Whole list           : ['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
After deleting Vikram: ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
After adding Jay     : ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
After removing item at 2nd position: ['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
๐Ÿ’ก Explanation: remove() deletes an item by its value, append() adds at the end and del list[index] deletes by position. Indexing starts at 0, so the 2nd position is index 1 (Sonakshi).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 13 : Operations on a list of names
2
quiz = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"]
๐Ÿงฎ Store / Calculate Stores a list ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sโ€ฆ in variable quiz
3
print("Whole list           :", quiz)
๐Ÿ–ฅ๏ธ Output Displays the text "Whole list :", then the value of quiz on the screen
5
quiz.remove("Vikram")          # delete by value
๐Ÿงฎ Store / Calculate Removes the first "Vikram" from quiz
6
print("After deleting Vikram:", quiz)
๐Ÿ–ฅ๏ธ Output Displays the text "After deleting Vikram:", then the value of quiz on the screen
8
quiz.append("Jay")             # add at the end
๐Ÿงฎ Store / Calculate Adds "Jay" at the end of list quiz
9
print("After adding Jay     :", quiz)
๐Ÿ–ฅ๏ธ Output Displays the text "After adding Jay :", then the value of quiz on the screen
11
del quiz[1]                    # second position = index 1
๐Ÿงฎ Store / Calculate Deletes quiz[1]
12
print("After removing item at 2nd position:", quiz)
๐Ÿ–ฅ๏ธ Output Displays the text "After removing item at 2nd positiโ€ฆ", then the value of quiz on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
quiz = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"]
quiz = ['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
23
print("Whole list           :", quiz)
Whole list           : ['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
35
quiz.remove("Vikram")          # delete by value
quiz = ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
46
print("After deleting Vikram:", quiz)
After deleting Vikram: ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
58
quiz.append("Jay")             # add at the end
quiz = ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
69
print("After adding Jay     :", quiz)
After adding Jay     : ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
711
del quiz[1]                    # second position = index 1
quiz = ['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
812
print("After removing item at 2nd position:", quiz)
After removing item at 2nd position: ['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
Q14 PYTHON

LIST: Create a list num=[23,12,5,9,65,44]. Print the length of the list, the elements from second to fourth position using positive indexing and the elements from third to fifth position using negative indexing.

# Program 14 : Length and slicing of a list
num = [23, 12, 5, 9, 65, 44]
print("List   :", num)
print("Length of the list =", len(num))
# 2nd to 4th position -> index 1 to 3 (stop value 4 is excluded)
print("2nd to 4th (positive indexing):", num[1:4])
# 3rd to 5th position -> negative index -4 to -2 (stop -1 excluded)
print("3rd to 5th (negative indexing):", num[-4:-1])
โ–ถ Sample Output
List   : [23, 12, 5, 9, 65, 44]
Length of the list = 6
2nd to 4th (positive indexing): [12, 5, 9]
3rd to 5th (negative indexing): [5, 9, 65]
๐Ÿ’ก Explanation: len() gives the number of items. Slicing list[start:stop] stops one before stop. Positive index of 3rd item is 2, and its negative index is -4 (counting from the end: 44 is -1).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 14 : Length and slicing of a list
2
num = [23, 12, 5, 9, 65, 44]
๐Ÿงฎ Store / Calculate Stores a list [23, 12, 5, 9, 65, 44] in variable num
3
print("List   :", num)
๐Ÿ–ฅ๏ธ Output Displays the text "List :", then the value of num on the screen
4
print("Length of the list =", len(num))
๐Ÿ–ฅ๏ธ Output Displays the text "Length of the list =", then the value of len(num) on the screen
๐Ÿ“Œ 2nd to 4th position -> index 1 to 3 (stop value 4 is excluded)
6
print("2nd to 4th (positive indexing):", num[1:4])
๐Ÿ–ฅ๏ธ Output Displays the text "2nd to 4th (positive indexing):", then the value of num[1:4] on the screen
๐Ÿ“Œ 3rd to 5th position -> negative index -4 to -2 (stop -1 excluded)
8
print("3rd to 5th (negative indexing):", num[-4:-1])
๐Ÿ–ฅ๏ธ Output Displays the text "3rd to 5th (negative indexing):", then the value of num[-4:-1] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
num = [23, 12, 5, 9, 65, 44]
num = [23, 12, 5, 9, 65, 44]
23
print("List   :", num)
List   : [23, 12, 5, 9, 65, 44]
34
print("Length of the list =", len(num))
Length of the list = 6
46
print("2nd to 4th (positive indexing):", num[1:4])
2nd to 4th (positive indexing): [12, 5, 9]
58
print("3rd to 5th (negative indexing):", num[-4:-1])
3rd to 5th (negative indexing): [5, 9, 65]
Q15 PYTHON

LIST: Create a list of first 10 even numbers, add 1 to each list item and print the final list.

# Program 15 : Add 1 to every item of a list
even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print("First 10 even numbers:", even)
for i in range(len(even)):
    even[i] = even[i] + 1
print("After adding 1       :", even)
โ–ถ Sample Output
First 10 even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
After adding 1       : [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
๐Ÿ’ก Explanation: A for loop with range(len(list)) visits every index; each item is replaced by item + 1, so all even numbers become odd numbers.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 15 : Add 1 to every item of a list
2
even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
๐Ÿงฎ Store / Calculate Stores a list [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] in variable even
3
print("First 10 even numbers:", even)
๐Ÿ–ฅ๏ธ Output Displays the text "First 10 even numbers:", then the value of even on the screen
4
for i in range(len(even)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(even) - 1; for each number, i takes that value and the indented block runs once
5
even[i] = even[i] + 1
๐Ÿงฎ Store / Calculate Puts the value of even[i] + 1 (calculated using +) into even[i] (item i of even)
6
print("After adding 1       :", even)
๐Ÿ–ฅ๏ธ Output Displays the text "After adding 1 :", then the value of even on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
23
print("First 10 even numbers:", even)
First 10 even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
34
for i in range(len(even)):
next item taken
i = 0
45
even[i] = even[i] + 1
even = [3, 4, 6, 8, 10, 12, 14, 16, 18, 20]
54
for i in range(len(even)):
next item taken
i = 1
65
even[i] = even[i] + 1
even = [3, 5, 6, 8, 10, 12, 14, 16, 18, 20]
74
for i in range(len(even)):
next item taken
i = 2
85
even[i] = even[i] + 1
even = [3, 5, 7, 8, 10, 12, 14, 16, 18, 20]
94
for i in range(len(even)):
next item taken
i = 3
105
even[i] = even[i] + 1
even = [3, 5, 7, 9, 10, 12, 14, 16, 18, 20]
114
for i in range(len(even)):
next item taken
i = 4
125
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 12, 14, 16, 18, 20]
134
for i in range(len(even)):
next item taken
i = 5
145
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 13, 14, 16, 18, 20]
154
for i in range(len(even)):
next item taken
i = 6
165
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 13, 15, 16, 18, 20]
174
for i in range(len(even)):
next item taken
i = 7
185
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 13, 15, 17, 18, 20]
194
for i in range(len(even)):
next item taken
i = 8
205
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20]
214
for i in range(len(even)):
next item taken
i = 9
225
even[i] = even[i] + 1
even = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
234
for i in range(len(even)):
no items left โ†’ loop ends
246
print("After adding 1       :", even)
After adding 1       : [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
Q16 PYTHON

LIST: Create a list List_1=[10,20,30,40]. Add the elements [14,15,12] using extend function. Now sort the final list in ascending order and print it.

# Program 16 : extend() and sort()
List_1 = [10, 20, 30, 40]
List_1.extend([14, 15, 12])
print("After extend :", List_1)
List_1.sort()
print("Sorted list  :", List_1)
โ–ถ Sample Output
After extend : [10, 20, 30, 40, 14, 15, 12]
Sorted list  : [10, 12, 14, 15, 20, 30, 40]
๐Ÿ’ก Explanation: extend() adds all elements of another list at the end. sort() arranges the list in ascending order (use sort(reverse=True) for descending).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 16 : extend() and sort()
2
List_1 = [10, 20, 30, 40]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 30, 40] in variable List_1
3
List_1.extend([14, 15, 12])
๐Ÿงฎ Store / Calculate Adds all items of [14, 15, 12] at the end of List_1
4
print("After extend :", List_1)
๐Ÿ–ฅ๏ธ Output Displays the text "After extend :", then the value of List_1 on the screen
5
List_1.sort()
๐Ÿงฎ Store / Calculate Sorts list List_1 in place
6
print("Sorted list  :", List_1)
๐Ÿ–ฅ๏ธ Output Displays the text "Sorted list :", then the value of List_1 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
List_1 = [10, 20, 30, 40]
List_1 = [10, 20, 30, 40]
23
List_1.extend([14, 15, 12])
List_1 = [10, 20, 30, 40, 14, 15, 12]
34
print("After extend :", List_1)
After extend : [10, 20, 30, 40, 14, 15, 12]
45
List_1.sort()
List_1 = [10, 12, 14, 15, 20, 30, 40]
56
print("Sorted list  :", List_1)
Sorted list  : [10, 12, 14, 15, 20, 30, 40]
Q17 PYTHON

IF: Write a program to check if a person can vote.

# Program 17 : Voting eligibility
name = input("Enter your name: ")
age = int(input("Enter your age : "))
if age >= 18:
    print(name, "is eligible to vote.")
else:
    print(name, "is not eligible to vote. Wait for", 18 - age, "more year(s).")
โ–ถ Sample Output
Enter your name: Riya
Enter your age : 15
Riya is not eligible to vote. Wait for 3 more year(s).
๐Ÿ’ก Explanation: The if-else statement checks the condition age >= 18. Only one of the two blocks runs. Indentation (4 spaces) marks the block.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ name, age
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Riya, 15 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 17 : Voting eligibility
2
name = input("Enter your name: ")
โŒจ๏ธ Input Shows the message "Enter your name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
3
age = int(input("Enter your age : "))
โŒจ๏ธ Input Shows "Enter your age : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable age
4
if age >= 18:
๐Ÿ”€ Decision CHECKS whether age is greater than or equal to 18. If True, the indented lines below run; otherwise Python jumps to the elif/else part
5
print(name, "is eligible to vote.")
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "is eligible to vote." on the screen
6
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
7
print(name, "is not eligible to vote. Wait for", 18 - age, "more year(s).")
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "is not eligible to vote. Wait for", then the value of 18 - age, then the text "more year(s)." on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
name = input("Enter your name: ")
name = 'Riya'
Enter your name: Riya
23
age = int(input("Enter your age : "))
age = 15
Enter your age : 15
34
if age >= 18:
condition is FALSE โ†’ skips this block
47
print(name, "is not eligible to vote. Wait for", 18 - age, "more year(s).")
Riya is not eligible to vote. Wait for 3 more year(s).
Q18 PYTHON

IF: Write a program to check the grade of a student.

# Program 18 : Grade of a student
marks = float(input("Enter percentage marks: "))
if marks >= 90:
    grade = "A1"
elif marks >= 80:
    grade = "A2"
elif marks >= 70:
    grade = "B1"
elif marks >= 60:
    grade = "B2"
elif marks >= 50:
    grade = "C1"
elif marks >= 33:
    grade = "C2"
else:
    grade = "E (Needs improvement)"
print("Grade =", grade)
โ–ถ Sample Output
Enter percentage marks: 84.5
Grade = A2
๐Ÿ’ก Explanation: if-elif-else checks conditions from top to bottom and runs only the first true block. The grade bands are similar to the CBSE grading scale.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ marks
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 84.5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 18 : Grade of a student
2
marks = float(input("Enter percentage marks: "))
โŒจ๏ธ Input Shows "Enter percentage marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable marks
3
if marks >= 90:
๐Ÿ”€ Decision CHECKS whether marks is greater than or equal to 90. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
grade = "A1"
๐Ÿงฎ Store / Calculate Stores the text "A1" in variable grade
5
elif marks >= 80:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether marks is greater than or equal to 80
6
grade = "A2"
๐Ÿงฎ Store / Calculate Stores the text "A2" in variable grade
7
elif marks >= 70:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether marks is greater than or equal to 70
8
grade = "B1"
๐Ÿงฎ Store / Calculate Stores the text "B1" in variable grade
9
elif marks >= 60:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether marks is greater than or equal to 60
10
grade = "B2"
๐Ÿงฎ Store / Calculate Stores the text "B2" in variable grade
11
elif marks >= 50:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether marks is greater than or equal to 50
12
grade = "C1"
๐Ÿงฎ Store / Calculate Stores the text "C1" in variable grade
13
elif marks >= 33:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether marks is greater than or equal to 33
14
grade = "C2"
๐Ÿงฎ Store / Calculate Stores the text "C2" in variable grade
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
grade = "E (Needs improvement)"
๐Ÿงฎ Store / Calculate Stores the text "E (Needs improvement)" in variable grade
17
print("Grade =", grade)
๐Ÿ–ฅ๏ธ Output Displays the text "Grade =", then the value of grade on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
marks = float(input("Enter percentage marks: "))
marks = 84.5
Enter percentage marks: 84.5
23
if marks >= 90:
condition is FALSE โ†’ skips this block
35
elif marks >= 80:
condition is TRUE โ†’ enters the block
46
grade = "A2"
grade = 'A2'
517
print("Grade =", grade)
Grade = A2
Q19 PYTHON

IF: Input a number and check if the number is positive, negative or zero and display an appropriate message.

# Program 19 : Positive, negative or zero
n = float(input("Enter a number: "))
if n > 0:
    print(n, "is a POSITIVE number")
elif n < 0:
    print(n, "is a NEGATIVE number")
else:
    print("The number is ZERO")
โ–ถ Sample Output
Enter a number: -7
-7.0 is a NEGATIVE number
๐Ÿ’ก Explanation: Three possibilities need if - elif - else. Comparison operators > and < return True or False.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type -7 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 19 : Positive, negative or zero
2
n = float(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable n
3
if n > 0:
๐Ÿ”€ Decision CHECKS whether n is greater than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
print(n, "is a POSITIVE number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a POSITIVE number" on the screen
5
elif n < 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether n is less than 0
6
print(n, "is a NEGATIVE number")
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text "is a NEGATIVE number" on the screen
7
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
8
print("The number is ZERO")
๐Ÿ–ฅ๏ธ Output Displays the text "The number is ZERO" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
n = float(input("Enter a number: "))
n = -7.0
Enter a number: -7
23
if n > 0:
condition is FALSE โ†’ skips this block
35
elif n < 0:
condition is TRUE โ†’ enters the block
46
print(n, "is a NEGATIVE number")
-7.0 is a NEGATIVE number
Q20 PYTHON

FOR: Write a program to print the first 10 natural numbers.

# Program 20 : First 10 natural numbers
print("First 10 natural numbers:")
for i in range(1, 11):
    print(i, end=" ")
print()
โ–ถ Sample Output
First 10 natural numbers:
1 2 3 4 5 6 7 8 9 10
๐Ÿ’ก Explanation: range(1, 11) generates 1 to 10 (11 is excluded). end=' ' keeps the numbers on the same line.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 20 : First 10 natural numbers
2
print("First 10 natural numbers:")
๐Ÿ–ฅ๏ธ Output Displays the text "First 10 natural numbers:" on the screen
3
for i in range(1, 11):
๐Ÿ” Loop LOOP: gives the numbers 1 to 10; for each number, i takes that value and the indented block runs once
4
print(i, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of i on the screen (ends with " " instead of a new line)
5
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
print("First 10 natural numbers:")
First 10 natural numbers:
23
for i in range(1, 11):
next item taken
i = 1
34
print(i, end=" ")
1 
43
for i in range(1, 11):
next item taken
i = 2
54
print(i, end=" ")
2 
63
for i in range(1, 11):
next item taken
i = 3
74
print(i, end=" ")
3 
83
for i in range(1, 11):
next item taken
i = 4
94
print(i, end=" ")
4 
103
for i in range(1, 11):
next item taken
i = 5
114
print(i, end=" ")
5 
123
for i in range(1, 11):
next item taken
i = 6
134
print(i, end=" ")
6 
143
for i in range(1, 11):
next item taken
i = 7
154
print(i, end=" ")
7 
163
for i in range(1, 11):
next item taken
i = 8
174
print(i, end=" ")
8 
183
for i in range(1, 11):
next item taken
i = 9
194
print(i, end=" ")
9 
203
for i in range(1, 11):
next item taken
i = 10
214
print(i, end=" ")
10 
223
for i in range(1, 11):
no items left โ†’ loop ends
235
print()
Q21 PYTHON

FOR: Write a program to print the first 10 even numbers.

# Program 21 : First 10 even numbers
print("First 10 even numbers:")
for i in range(2, 21, 2):
    print(i, end=" ")
print()
โ–ถ Sample Output
First 10 even numbers:
2 4 6 8 10 12 14 16 18 20
๐Ÿ’ก Explanation: range(start, stop, step): starting at 2 with a step of 2 gives 2, 4, ... 20.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q21.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 21 : First 10 even numbers
2
print("First 10 even numbers:")
๐Ÿ–ฅ๏ธ Output Displays the text "First 10 even numbers:" on the screen
3
for i in range(2, 21, 2):
๐Ÿ” Loop LOOP: gives the numbers from 2 up to (not including) 21, jumping by 2; for each number, i takes that value and the indented block runs once
4
print(i, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of i on the screen (ends with " " instead of a new line)
5
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
print("First 10 even numbers:")
First 10 even numbers:
23
for i in range(2, 21, 2):
next item taken
i = 2
34
print(i, end=" ")
2 
43
for i in range(2, 21, 2):
next item taken
i = 4
54
print(i, end=" ")
4 
63
for i in range(2, 21, 2):
next item taken
i = 6
74
print(i, end=" ")
6 
83
for i in range(2, 21, 2):
next item taken
i = 8
94
print(i, end=" ")
8 
103
for i in range(2, 21, 2):
next item taken
i = 10
114
print(i, end=" ")
10 
123
for i in range(2, 21, 2):
next item taken
i = 12
134
print(i, end=" ")
12 
143
for i in range(2, 21, 2):
next item taken
i = 14
154
print(i, end=" ")
14 
163
for i in range(2, 21, 2):
next item taken
i = 16
174
print(i, end=" ")
16 
183
for i in range(2, 21, 2):
next item taken
i = 18
194
print(i, end=" ")
18 
203
for i in range(2, 21, 2):
next item taken
i = 20
214
print(i, end=" ")
20 
223
for i in range(2, 21, 2):
no items left โ†’ loop ends
235
print()
Q22 PYTHON

WHILE: Write a program to print odd numbers from 1 to n.

# Program 22 : Odd numbers from 1 to n
n = int(input("Enter the value of n: "))
i = 1
print("Odd numbers from 1 to", n, ":")
while i <= n:
    print(i, end=" ")
    i = i + 2
print()
โ–ถ Sample Output
Enter the value of n: 15
Odd numbers from 1 to 15 :
1 3 5 7 9 11 13 15
๐Ÿ’ก Explanation: The while loop runs as long as i <= n. Starting at 1 and adding 2 each time gives only odd numbers. Updating i is important, otherwise the loop never ends.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses a while loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q22.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 15 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 22 : Odd numbers from 1 to n
2
n = int(input("Enter the value of n: "))
โŒจ๏ธ Input Shows "Enter the value of n: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
3
i = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable i
4
print("Odd numbers from 1 to", n, ":")
๐Ÿ–ฅ๏ธ Output Displays the text "Odd numbers from 1 to", then the value of n, then the text ":" on the screen
5
while i <= n:
๐Ÿ” Loop LOOP: repeats the indented block as long as i is less than or equal to n; checks the condition before every round
6
print(i, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of i on the screen (ends with " " instead of a new line)
7
i = i + 2
๐Ÿงฎ Store / Calculate Stores the value of i + 2 (calculated using +) in variable i
8
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
n = int(input("Enter the value of n: "))
n = 15
Enter the value of n: 15
23
i = 1
i = 1
34
print("Odd numbers from 1 to", n, ":")
Odd numbers from 1 to 15 :
45
while i <= n:
condition is TRUE โ†’ enters the block
56
print(i, end=" ")
1 
67
i = i + 2
i = 3
75
while i <= n:
condition is TRUE โ†’ enters the block
86
print(i, end=" ")
3 
97
i = i + 2
i = 5
105
while i <= n:
condition is TRUE โ†’ enters the block
116
print(i, end=" ")
5 
127
i = i + 2
i = 7
135
while i <= n:
condition is TRUE โ†’ enters the block
146
print(i, end=" ")
7 
157
i = i + 2
i = 9
165
while i <= n:
condition is TRUE โ†’ enters the block
176
print(i, end=" ")
9 
187
i = i + 2
i = 11
195
while i <= n:
condition is TRUE โ†’ enters the block
206
print(i, end=" ")
11 
217
i = i + 2
i = 13
225
while i <= n:
condition is TRUE โ†’ enters the block
236
print(i, end=" ")
13 
247
i = i + 2
i = 15
255
while i <= n:
condition is TRUE โ†’ enters the block
266
print(i, end=" ")
15 
277
i = i + 2
i = 17
285
while i <= n:
condition is FALSE โ†’ loop ends
298
print()
Q23 PYTHON

FOR: Write a program to print the sum of first 10 natural numbers.

# Program 23 : Sum of first 10 natural numbers
total = 0
for i in range(1, 11):
    total = total + i
print("Sum of first 10 natural numbers =", total)
โ–ถ Sample Output
Sum of first 10 natural numbers = 55
๐Ÿ’ก Explanation: total starts at 0 and each number is added in the loop (an accumulator). Check: n(n+1)/2 = 10 x 11 / 2 = 55.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q23.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 23 : Sum of first 10 natural numbers
2
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
3
for i in range(1, 11):
๐Ÿ” Loop LOOP: gives the numbers 1 to 10; for each number, i takes that value and the indented block runs once
4
total = total + i
๐Ÿงฎ Store / Calculate Stores the value of total + i (calculated using +) in variable total
5
print("Sum of first 10 natural numbers =", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum of first 10 natural numbers =", then the value of total on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
total = 0
total = 0
23
for i in range(1, 11):
next item taken
i = 1
34
total = total + i
total = 1
43
for i in range(1, 11):
next item taken
i = 2
54
total = total + i
total = 3
63
for i in range(1, 11):
next item taken
i = 3
74
total = total + i
total = 6
83
for i in range(1, 11):
next item taken
i = 4
94
total = total + i
total = 10
103
for i in range(1, 11):
next item taken
i = 5
114
total = total + i
total = 15
123
for i in range(1, 11):
next item taken
i = 6
134
total = total + i
total = 21
143
for i in range(1, 11):
next item taken
i = 7
154
total = total + i
total = 28
163
for i in range(1, 11):
next item taken
i = 8
174
total = total + i
total = 36
183
for i in range(1, 11):
next item taken
i = 9
194
total = total + i
total = 45
203
for i in range(1, 11):
next item taken
i = 10
214
total = total + i
total = 55
223
for i in range(1, 11):
no items left โ†’ loop ends
235
print("Sum of first 10 natural numbers =", total)
Sum of first 10 natural numbers = 55
Q24 PYTHON

LIST + FOR: Write a program to find the sum of all numbers stored in a list.

# Program 24 : Sum of numbers in a list
numbers = [12, 45, 7, 23, 56, 89, 34]
total = 0
for x in numbers:
    total = total + x
print("List :", numbers)
print("Sum using loop  =", total)
print("Sum using sum() =", sum(numbers))
โ–ถ Sample Output
List : [12, 45, 7, 23, 56, 89, 34]
Sum using loop  = 266
Sum using sum() = 266
๐Ÿ’ก Explanation: The for loop picks each item of the list one by one. Python's built-in sum() gives the same answer and is a quick way to verify.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as ix_ai_q24.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 24 : Sum of numbers in a list
2
numbers = [12, 45, 7, 23, 56, 89, 34]
๐Ÿงฎ Store / Calculate Stores a list [12, 45, 7, 23, 56, 89, 34] in variable numbers
3
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
4
for x in numbers:
๐Ÿ” Loop LOOP: takes each item of numbers one-by-one into x and runs the indented block for it
5
total = total + x
๐Ÿงฎ Store / Calculate Stores the value of total + x (calculated using +) in variable total
6
print("List :", numbers)
๐Ÿ–ฅ๏ธ Output Displays the text "List :", then the value of numbers on the screen
7
print("Sum using loop  =", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum using loop =", then the value of total on the screen
8
print("Sum using sum() =", sum(numbers))
๐Ÿ–ฅ๏ธ Output Displays the text "Sum using sum() =", then the value of sum(numbers) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
numbers = [12, 45, 7, 23, 56, 89, 34]
numbers = [12, 45, 7, 23, 56, 89, 34]
23
total = 0
total = 0
34
for x in numbers:
next item taken
x = 12
45
total = total + x
total = 12
54
for x in numbers:
next item taken
x = 45
65
total = total + x
total = 57
74
for x in numbers:
next item taken
x = 7
85
total = total + x
total = 64
94
for x in numbers:
next item taken
x = 23
105
total = total + x
total = 87
114
for x in numbers:
next item taken
x = 56
125
total = total + x
total = 143
134
for x in numbers:
next item taken
x = 89
145
total = total + x
total = 232
154
for x in numbers:
next item taken
x = 34
165
total = total + x
total = 266
174
for x in numbers:
no items left โ†’ loop ends
186
print("List :", numbers)
List : [12, 45, 7, 23, 56, 89, 34]
197
print("Sum using loop  =", total)
Sum using loop  = 266
208
print("Sum using sum() =", sum(numbers))
Sum using sum() = 266
Q25 ACTIVITY

ACTIVITY (Unit 1 - AI Reflection): Play the AI Game and record how each game uses a domain of AI - Rock Paper Scissors (Data), Semantris (NLP) and Quick Draw (Computer Vision).

STEPS
1. Game 1 - Rock, Paper, Scissors  : https://next.rockpaperscissors.ai/
   Play 20+ rounds against the AI and note how often it wins.
2. Game 2 - Semantris              : https://research.google.com/semantris/
   Type a clue word; the AI ranks words that are related in meaning.
3. Game 3 - Quick Draw             : https://quickdraw.withgoogle.com/
   Draw the given object in 20 seconds; the AI guesses the drawing.

RECORD IN YOUR FILE
+------------------+-------------------+--------------------------------------------+
| Game             | Domain of AI      | How the AI works / what it learns from     |
+------------------+-------------------+--------------------------------------------+
| Rock Paper       | DATA (Statistical | Learns the PATTERN of your previous moves  |
| Scissors         | Data)             | and predicts your next move                |
| Semantris        | NLP (Natural      | Understands the MEANING / association of   |
|                  | Language Proc.)   | words, not just exact spellings            |
| Quick Draw       | CV (Computer      | Recognises SHAPES in the drawing using a   |
|                  | Vision)           | model trained on millions of doodles       |
+------------------+-------------------+--------------------------------------------+
โ–ถ Sample Observation
Sample observation: Rock Paper Scissors AI won 11 of 20 rounds after it learnt my pattern;
Semantris correctly linked 'ocean' -> 'whale', 'wave', 'ship';
Quick Draw identified 5 of 6 drawings (bicycle, sun, house, fish, tree).
๐Ÿ’ก Explanation: Each game represents one AI domain: Data (numbers/patterns), NLP (human language) and Computer Vision (images). Write 2-3 lines on which game the AI was best at and why.
Q26 ACTIVITY

ACTIVITY (Unit 1 - Problem Scoping): Fill a 4Ws Problem Canvas for an SDG-related problem in your community and write the problem statement.

THEME : Clean Water and Sanitation (SDG 6)      TOPIC : Water wastage in school

4Ws PROBLEM CANVAS
WHO ?   Stakeholders : Students, teachers, housekeeping staff, school management
        What do we know about them? Use drinking-water taps & washrooms daily.
WHAT ?  Problem : Taps are left open / leaking; water tank overflows daily.
        Evidence : Tank overflow seen 4 days a week; 6 leaking taps found in survey.
WHERE ? Context : Drinking-water area, washrooms and garden of the school,
        mostly during lunch break and after games period.
WHY ?   Benefits : Saves water and electricity (pump), reduces bill,
        builds responsible water habits (SDG 6).

PROBLEM STATEMENT TEMPLATE
Our  [students and staff]          (Who)
have a problem that [water is wasted from open/leaking taps and tank overflow]  (What)
while  [using taps in school during breaks]   (Where)
An ideal solution would [alert us when water is wasted and track daily usage]   (Why)
โ–ถ Problem Statement
Problem Statement: Our students and staff have a problem that water is wasted from open or
leaking taps and tank overflow while using taps in school during breaks. An ideal solution
would alert us when water is wasted and track daily water usage.
๐Ÿ’ก Explanation: The 4Ws canvas (Who, What, Where, Why) is the first stage of the AI Project Cycle - Problem Scoping. It makes the goal clear before collecting any data.
Q27 ACTIVITY

ACTIVITY (Unit 1 - Data Acquisition): Identify the data features for the problem scoped and draw a System Map showing the relationship between them.

DATA FEATURES (for water wastage in school)
 1. Number of taps / leaking taps        4. Time the pump runs (minutes/day)
 2. Tank level (litres) every hour       5. Number of students present
 3. Rainfall / temperature of the day    6. Break timings

SYSTEM MAP  ( + : increases,  - : decreases )

   Students present --(+)--> Water usage --(+)--> Tank empties faster
          |                       ^                       |
         (+)                     (+)                     (+)
          v                       |                       v
   Taps left open  --(+)----------+              Pump running time --(+)--> Electricity bill
          ^
         (-)
          |
   Awareness posters / sensor alert --(-)--> Water wasted
   Hot temperature --(+)--> Drinking-water usage
โ–ถ Conclusion
Most important features chosen for the AI model: tank level, pump running time,
students present and temperature. Sources: hourly tank reading, attendance register,
weather app.
๐Ÿ’ก Explanation: A System Map shows how elements of a problem affect each other. Arrows with (+) mean 'increases' and (-) mean 'decreases'. It helps decide which data features to collect.
Q28 ACTIVITY

ACTIVITY (Unit 1/2 - Data Exploration): Collect data of daily water usage for one week, store it in a spreadsheet and draw a bar graph and a line graph to interpret the data.

STEPS (Google Sheets / MS Excel / LibreOffice Calc)
1. Enter the data in two columns:
       A          B
   1   Day        Water used (litres)
   2   Monday     1450
   3   Tuesday    1380
   4   Wednesday  1620
   5   Thursday   1500
   6   Friday     1710
   7   Saturday    900
2. In B8 type  =AVERAGE(B2:B7)   ->  average daily usage
   In B9 type  =MAX(B2:B7)       ->  maximum usage
3. Select A1:B7 -> Insert -> Chart -> choose Column (bar) chart -> add title
   "Daily Water Usage in School".
4. Insert another chart -> Line chart to see the trend.
5. Write 3 observations below the charts (interpretation).
โ–ถ Result / Interpretation
Average = 1426.67 litres/day   Maximum = 1710 litres (Friday)
Interpretation: Usage rises towards the end of the week (games day Friday);
Saturday is lowest (half day). Target: reduce Friday usage by fixing garden taps.
๐Ÿ’ก Explanation: Data visualisation turns numbers into pictures so patterns are visible at a glance. A bar chart compares days; a line chart shows the trend over time.
Q29 ACTIVITY

ACTIVITY (Unit 3 - Statistics): Car Spotting and Tabulating - record the colours of 30 cars passing the school gate, tabulate the data and answer questions on probability.

TALLY TABLE (data collected in 10 minutes)
+---------+----------------------+-----------+
| Colour  | Tally                | Frequency |
+---------+----------------------+-----------+
| White   | |||| |||| |          |    11     |
| Silver  | |||| ||              |     7     |
| Black   | ||||                 |     5     |
| Red     | ||||                 |     4     |
| Blue    | |||                  |     3     |
+---------+----------------------+-----------+
| Total   |                      |    30     |
+---------+----------------------+-----------+

QUESTIONS
1. Which colour is the MODE (most frequent)?       -> White
2. P(next car is white) = 11/30                    -> 0.37 (approx.)
3. P(next car is NOT red) = 1 - 4/30 = 26/30        -> 0.87 (approx.)
4. Is "next car is green" an impossible event?  P = 0/30 = 0 from our data,
   but it is NOT truly impossible - more data may include green cars.
โ–ถ Result
Mode colour: White | P(White) = 0.37 | P(not Red) = 0.87
๐Ÿ’ก Explanation: Probability = favourable outcomes / total outcomes. AI systems use the same idea: predictions are based on the frequency of patterns in the data they have seen.
Q30 ACTIVITY

ACTIVITY (Unit 1 - Evaluation): Understand True Positive, False Positive, True Negative and False Negative using a rain-prediction example and find the accuracy of the model.

SCENARIO : An AI model predicts every morning whether it will rain. Data for 20 days:

                         REALITY: Rain   REALITY: No Rain
   PREDICTION: Rain          TP = 6           FP = 2
   PREDICTION: No Rain       FN = 1           TN = 11

 True Positive  (TP) : predicted Rain    and it rained          -> 6
 False Positive (FP) : predicted Rain    but it did not rain     -> 2
 False Negative (FN) : predicted No Rain but it rained           -> 1
 True Negative  (TN) : predicted No Rain and it did not rain     -> 11

 Accuracy = (TP + TN) / Total = (6 + 11) / 20 = 17/20 = 0.85 = 85 %
โ–ถ Result
Accuracy of the model = 85 %
๐Ÿ’ก Explanation: The confusion matrix compares predictions with reality. In rain prediction a False Negative is costly (you get wet), so we want FN to be as low as possible.
Q31 ACTIVITY

ACTIVITY (Unit 4 - Generative AI): Guess the Real Image vs the AI-generated image, explore a Generative AI tool and list the ethical considerations of using Generative AI.

PART A - Real or AI?  (look at 6 images shown by the teacher)
  Clues of AI images: extra/merged fingers, unreadable text in background,
  too-smooth skin, odd shadows, earrings that do not match, warped lines.

PART B - Hands-on (any one): GAN Paint / Canva Magic Media / Microsoft Designer
  Prompt used: "A solar-powered school in a green village, watercolour style"
  Note what changed when the prompt was edited (style, colours, objects).

PART C - Generative AI vs Conventional AI
  Conventional AI : classifies / predicts (e.g. spam filter, face unlock)
  Generative AI   : creates NEW content - text, image, audio, video, code

PART D - Ethical considerations
  1. Deepfakes and misinformation      4. Bias in generated content
  2. Copyright of training data/art    5. Privacy - never upload personal photos
  3. Always disclose AI-generated work 6. Do not submit AI text as your own
โ–ถ Sample Observation
Score in Real vs AI: 5 / 6 identified correctly.
Learning: AI images look real, so always verify the source before sharing.
๐Ÿ’ก Explanation: Generative AI learns patterns from huge datasets and generates new content. Responsible use means checking facts, giving credit and never misusing someone's identity.

๐Ÿ“ Project Work Reference (CBSE 417)

PROJECT WORK / FIELD VISIT / STUDENT PORTFOLIO  (Part D - 15 marks, relate it to the Sustainable Development Goals)
Any ONE of the following has to be done:

1. Suggested Projects
   a) Create an AI model using Teachable Machine (https://teachablemachine.withgoogle.com/)
      or Machine Learning for Kids (https://machinelearningforkids.co.uk/).
   b) Choose an issue related to the SDGs and: create a 4Ws problem canvas; identify the data
      features and create a system map; visualise the collected data graphically in a
      spreadsheet; suggest an AI-enabled solution (prototype / research work).
2. Suggested Field Visit - visit an industry / IT company / any place creating or using AI
   applications (physical or virtual) and present a report.
3. Student Portfolio - record of all AI activities (e.g. Letter to Future Self, Smart Home Floor
   Plan, Future Job Advertisement, Research on AI for SDGs and AI in different sectors, 4Ws
   canvas, System Map). Minimum 5 activities.

The 10 Python mini-projects given in the Live Projects section can be used for idea (b) and for
practice; each comes with code, real output and a one-click project report.

๐Ÿง  Class X โ€” Artificial Intelligence (417)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 34 Practicals (31 Python programs + 3 activities) as per CBSE curriculum 2026-27

๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

๐Ÿ“‘ CBSE Practical Assessment Scheme โ€” Class X AI (417)

ComponentMarks
Practical File with minimum 15 programs15
Practical Examination - Statistical Data, Computer Vision, NLP, Advance Python15
Viva Voce5
Project Work / Field Visit / Student Portfolio (any one)10
Viva Voce (related to project work)5
TOTAL (Practical)50

Theory 50 + Practical 50 = 100. Every Python program below was run and its real output is shown; activities give the procedure and a model answer for the practical file.

Q1 PYTHON

Write a program to print your Bio-Data.

# Program 1 : Bio-Data
name = "Ananya Verma"
father_name = "Mr. Sanjay Verma"
mother_name = "Mrs. Kavita Verma"
class_name = "X - B"
school_name = "PM SHRI Kendriya Vidyalaya Shalimar Bagh"
hobbies = "Coding, Chess, Reading"

print("=" * 45)
print("                  BIO-DATA")
print("=" * 45)
print("Name          :", name)
print("Father's Name :", father_name)
print("Mother's Name :", mother_name)
print("Class         :", class_name)
print("School        :", school_name)
print("Hobbies       :", hobbies)
print("=" * 45)
โ–ถ Sample Output
=============================================
                  BIO-DATA
=============================================
Name          : Ananya Verma
Father's Name : Mr. Sanjay Verma
Mother's Name : Mrs. Kavita Verma
Class         : X - B
School        : PM SHRI Kendriya Vidyalaya Shalimar Bagh
Hobbies       : Coding, Chess, Reading
=============================================
๐Ÿ’ก Explanation: Variables store string values and print() displays them. The expression '=' * 45 repeats the '=' character 45 times (string replication).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q1.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 1 : Bio-Data
2
name = "Ananya Verma"
๐Ÿงฎ Store / Calculate Stores the text "Ananya Verma" in variable name
3
father_name = "Mr. Sanjay Verma"
๐Ÿงฎ Store / Calculate Stores the text "Mr. Sanjay Verma" in variable father_name
4
mother_name = "Mrs. Kavita Verma"
๐Ÿงฎ Store / Calculate Stores the text "Mrs. Kavita Verma" in variable mother_name
5
class_name = "X - B"
๐Ÿงฎ Store / Calculate Stores the text "X - B" in variable class_name
6
school_name = "PM SHRI Kendriya Vidyalaya Shalimar Bagh"
๐Ÿงฎ Store / Calculate Stores the text "PM SHRI Kendriya Vidyalaya Shalimar Bagh" in variable school_name
7
hobbies = "Coding, Chess, Reading"
๐Ÿงฎ Store / Calculate Stores the text "Coding, Chess, Reading" in variable hobbies
9
print("=" * 45)
๐Ÿ–ฅ๏ธ Output Displays a line of 45 "=" signs on the screen
10
print("                  BIO-DATA")
๐Ÿ–ฅ๏ธ Output Displays the text "BIO-DATA" on the screen
11
print("=" * 45)
๐Ÿ–ฅ๏ธ Output Displays a line of 45 "=" signs on the screen
12
print("Name          :", name)
๐Ÿ–ฅ๏ธ Output Displays the text "Name :", then the value of name on the screen
13
print("Father's Name :", father_name)
๐Ÿ–ฅ๏ธ Output Displays the text "Father's Name :", then the value of father_name on the screen
14
print("Mother's Name :", mother_name)
๐Ÿ–ฅ๏ธ Output Displays the text "Mother's Name :", then the value of mother_name on the screen
15
print("Class         :", class_name)
๐Ÿ–ฅ๏ธ Output Displays the text "Class :", then the value of class_name on the screen
16
print("School        :", school_name)
๐Ÿ–ฅ๏ธ Output Displays the text "School :", then the value of school_name on the screen
17
print("Hobbies       :", hobbies)
๐Ÿ–ฅ๏ธ Output Displays the text "Hobbies :", then the value of hobbies on the screen
18
print("=" * 45)
๐Ÿ–ฅ๏ธ Output Displays a line of 45 "=" signs on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
name = "Ananya Verma"
name = 'Ananya Verma'
23
father_name = "Mr. Sanjay Verma"
father_name = 'Mr. Sanjay Verma'
34
mother_name = "Mrs. Kavita Verma"
mother_name = 'Mrs. Kavita Verma'
45
class_name = "X - B"
class_name = 'X - B'
56
school_name = "PM SHRI Kendriya Vidyalaya Shalimar Bagh"
school_name = 'PM SHRI Kendriya Vidyalaya Shalimar Bagh'
67
hobbies = "Coding, Chess, Reading"
hobbies = 'Coding, Chess, Reading'
79
print("=" * 45)
=============================================
810
print("                  BIO-DATA")
                  BIO-DATA
911
print("=" * 45)
=============================================
1012
print("Name          :", name)
Name          : Ananya Verma
1113
print("Father's Name :", father_name)
Father's Name : Mr. Sanjay Verma
1214
print("Mother's Name :", mother_name)
Mother's Name : Mrs. Kavita Verma
1315
print("Class         :", class_name)
Class         : X - B
1416
print("School        :", school_name)
School        : PM SHRI Kendriya Vidyalaya Shalimar Bagh
1517
print("Hobbies       :", hobbies)
Hobbies       : Coding, Chess, Reading
1618
print("=" * 45)
=============================================
Q2 PYTHON

Write a program to convert temperature from Celsius to Fahrenheit.

# Program 2 : Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
print(celsius, "degree Celsius =", fahrenheit, "degree Fahrenheit")
โ–ถ Sample Output
Enter temperature in Celsius: 45
45.0 degree Celsius = 113.0 degree Fahrenheit
๐Ÿ’ก Explanation: Formula F = (C x 9/5) + 32. For 45 C: 45 x 1.8 + 32 = 113.0 F. (In Class XII, a neural network learns this same formula from data!)
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ celsius
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q2.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 45 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 2 : Celsius to Fahrenheit
2
celsius = float(input("Enter temperature in Celsius: "))
โŒจ๏ธ Input Shows "Enter temperature in Celsius: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable celsius
3
fahrenheit = (celsius * 9 / 5) + 32
๐Ÿงฎ Store / Calculate Stores the value of (celsius * 9 / 5) + 32 (calculated using +) in variable fahrenheit
4
print(celsius, "degree Celsius =", fahrenheit, "degree Fahrenheit")
๐Ÿ–ฅ๏ธ Output Displays the value of celsius, then the text "degree Celsius =", then the value of fahrenheit, then the text "degree Fahrenheit" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
celsius = float(input("Enter temperature in Celsius: "))
celsius = 45.0
Enter temperature in Celsius: 45
23
fahrenheit = (celsius * 9 / 5) + 32
fahrenheit = 113.0
34
print(celsius, "degree Celsius =", fahrenheit, "degree Fahrenheit")
45.0 degree Celsius = 113.0 degree Fahrenheit
Q3 PYTHON

Write a program to check if a number is even or odd.

# Program 3 : Even or odd
number = int(input("Enter a number: "))
if number % 2 == 0:
    print(number, "is an EVEN number.")
else:
    print(number, "is an ODD number.")
โ–ถ Sample Output
Enter a number: 48
48 is an EVEN number.
๐Ÿ’ก Explanation: The modulus operator % gives the remainder. A number divisible by 2 leaves remainder 0, so it is even.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ number
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 48 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 3 : Even or odd
2
number = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable number
3
if number % 2 == 0:
๐Ÿ”€ Decision CHECKS whether number % 2 is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
print(number, "is an EVEN number.")
๐Ÿ–ฅ๏ธ Output Displays the value of number, then the text "is an EVEN number." on the screen
5
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
6
print(number, "is an ODD number.")
๐Ÿ–ฅ๏ธ Output Displays the value of number, then the text "is an ODD number." on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
number = int(input("Enter a number: "))
number = 48
Enter a number: 48
23
if number % 2 == 0:
condition is TRUE โ†’ enters the block
34
print(number, "is an EVEN number.")
48 is an EVEN number.
Q4 PYTHON

Write a simple menu-driven calculator program.

# Program 4 : Menu-driven calculator
while True:
    print("\n----- MENU -----")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")
    print("5. Exit")
    choice = input("Enter your choice (1-5): ")
    if choice == '5':
        print("Exiting the program. Thank you!")
        break
    if choice not in ('1', '2', '3', '4'):
        print("Invalid choice! Please choose 1 to 5.")
        continue
    num1 = float(input("Enter first number : "))
    num2 = float(input("Enter second number: "))
    if choice == '1':
        print("Result:", num1 + num2)
    elif choice == '2':
        print("Result:", num1 - num2)
    elif choice == '3':
        print("Result:", num1 * num2)
    elif choice == '4':
        if num2 != 0:
            print("Result:", num1 / num2)
        else:
            print("Error! Division by zero is not allowed.")
โ–ถ Sample Output

----- MENU -----
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice (1-5): 1
Enter first number : 34
Enter second number: 65
Result: 99.0

----- MENU -----
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice (1-5): 4
Enter first number : 45
Enter second number: 0
Error! Division by zero is not allowed.

----- MENU -----
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice (1-5): 3
Enter first number : 12
Enter second number: 2.5
Result: 30.0

----- MENU -----
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice (1-5): 5
Exiting the program. Thank you!
๐Ÿ’ก Explanation: while True repeats the menu until the user chooses 5 (break exits the loop). continue skips back to the menu for an invalid choice. Division by zero is checked before dividing.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ choice, num1, num2
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 34, 65, 4, 45, 0, 3, 12, 2.5, 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 4 : Menu-driven calculator
2
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
3
print("\n----- MENU -----")
๐Ÿ–ฅ๏ธ Output Displays the text "----- MENU -----" on the screen
4
print("1. Addition")
๐Ÿ–ฅ๏ธ Output Displays the text "1. Addition" on the screen
5
print("2. Subtraction")
๐Ÿ–ฅ๏ธ Output Displays the text "2. Subtraction" on the screen
6
print("3. Multiplication")
๐Ÿ–ฅ๏ธ Output Displays the text "3. Multiplication" on the screen
7
print("4. Division")
๐Ÿ–ฅ๏ธ Output Displays the text "4. Division" on the screen
8
print("5. Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "5. Exit" on the screen
9
choice = input("Enter your choice (1-5): ")
โŒจ๏ธ Input Shows the message "Enter your choice (1-5): " and waits; whatever the user types comes back as TEXT (string); it is stored in variable choice
10
if choice == '5':
๐Ÿ”€ Decision CHECKS whether choice is equal to '5'. If True, the indented lines below run; otherwise they are skipped
11
print("Exiting the program. Thank you!")
๐Ÿ–ฅ๏ธ Output Displays the text "Exiting the program. Thank you!" on the screen
12
break
๐Ÿ” Loop BREAK - leaves the loop immediately
13
if choice not in ('1', '2', '3', '4'):
๐Ÿ”€ Decision CHECKS whether choice is not present in ('1', '2', '3', '4'). If True, the indented lines below run; otherwise they are skipped
14
print("Invalid choice! Please choose 1 to 5.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice! Please choose 1 tโ€ฆ" on the screen
15
continue
๐Ÿ” Loop CONTINUE - skips the rest of this round and goes to the next round of the loop
16
num1 = float(input("Enter first number : "))
โŒจ๏ธ Input Shows "Enter first number : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable num1
17
num2 = float(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable num2
18
if choice == '1':
๐Ÿ”€ Decision CHECKS whether choice is equal to '1'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
19
print("Result:", num1 + num2)
๐Ÿ–ฅ๏ธ Output Displays the text "Result:", then the value of num1 + num2 on the screen
20
elif choice == '2':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '2'
21
print("Result:", num1 - num2)
๐Ÿ–ฅ๏ธ Output Displays the text "Result:", then the value of num1 - num2 on the screen
22
elif choice == '3':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '3'
23
print("Result:", num1 * num2)
๐Ÿ–ฅ๏ธ Output Displays the text "Result:", then the value of num1 * num2 on the screen
24
elif choice == '4':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '4'
25
if num2 != 0:
๐Ÿ”€ Decision CHECKS whether num2 is not equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
26
print("Result:", num1 / num2)
๐Ÿ–ฅ๏ธ Output Displays the text "Result:", then the value of num1 / num2 on the screen
27
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
28
print("Error! Division by zero is not allowed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Error! Division by zero is not alโ€ฆ" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
while True:
condition is TRUE โ†’ enters the block
23
print("\n----- MENU -----")
----- MENU -----
34
print("1. Addition")
1. Addition
45
print("2. Subtraction")
2. Subtraction
56
print("3. Multiplication")
3. Multiplication
67
print("4. Division")
4. Division
78
print("5. Exit")
5. Exit
89
choice = input("Enter your choice (1-5): ")
choice = '1'
Enter your choice (1-5): 1
910
if choice == '5':
condition is FALSE โ†’ skips this block
1013
if choice not in ('1', '2', '3', '4'):
condition is FALSE โ†’ skips this block
1116
num1 = float(input("Enter first number : "))
num1 = 34.0
Enter first number : 34
1217
num2 = float(input("Enter second number: "))
num2 = 65.0
Enter second number: 65
1318
if choice == '1':
condition is TRUE โ†’ enters the block
1419
print("Result:", num1 + num2)
Result: 99.0
152
while True:
condition is TRUE โ†’ enters the block
163
print("\n----- MENU -----")
----- MENU -----
174
print("1. Addition")
1. Addition
185
print("2. Subtraction")
2. Subtraction
196
print("3. Multiplication")
3. Multiplication
207
print("4. Division")
4. Division
218
print("5. Exit")
5. Exit
229
choice = input("Enter your choice (1-5): ")
choice = '4'
Enter your choice (1-5): 4
2310
if choice == '5':
condition is FALSE โ†’ skips this block
2413
if choice not in ('1', '2', '3', '4'):
condition is FALSE โ†’ skips this block
2516
num1 = float(input("Enter first number : "))
num1 = 45.0
Enter first number : 45
2617
num2 = float(input("Enter second number: "))
num2 = 0.0
Enter second number: 0
2718
if choice == '1':
condition is FALSE โ†’ skips this block
2820
elif choice == '2':
condition is FALSE โ†’ skips this block
2922
elif choice == '3':
condition is FALSE โ†’ skips this block
3024
elif choice == '4':
condition is TRUE โ†’ enters the block
3125
if num2 != 0:
condition is FALSE โ†’ skips this block
3228
print("Error! Division by zero is not allowed.")
Error! Division by zero is not allowed.

โ€ฆ Python runs 27 more line-steps in the same way (loops repeat the same lines). Final values: choice = '5', num1 = 12.0, num2 = 2.5

Q5 PYTHON

Write a program to print a name 5 times.

# Program 5 : Print a name 5 times
name = input("Enter your name: ")
for i in range(5):
    print(i + 1, name)
โ–ถ Sample Output
Enter your name: Kendriya Vidyalaya
1 Kendriya Vidyalaya
2 Kendriya Vidyalaya
3 Kendriya Vidyalaya
4 Kendriya Vidyalaya
5 Kendriya Vidyalaya
๐Ÿ’ก Explanation: range(5) gives 0,1,2,3,4 - so the loop body runs exactly 5 times.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ name
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Kendriya Vidyalaya (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 5 : Print a name 5 times
2
name = input("Enter your name: ")
โŒจ๏ธ Input Shows the message "Enter your name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
3
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
4
print(i + 1, name)
๐Ÿ–ฅ๏ธ Output Displays the value of i + 1, then the value of name on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
name = input("Enter your name: ")
name = 'Kendriya Vidyalaya'
Enter your name: Kendriya Vidyalaya
23
for i in range(5):
next item taken
i = 0
34
print(i + 1, name)
1 Kendriya Vidyalaya
43
for i in range(5):
next item taken
i = 1
54
print(i + 1, name)
2 Kendriya Vidyalaya
63
for i in range(5):
next item taken
i = 2
74
print(i + 1, name)
3 Kendriya Vidyalaya
83
for i in range(5):
next item taken
i = 3
94
print(i + 1, name)
4 Kendriya Vidyalaya
103
for i in range(5):
next item taken
i = 4
114
print(i + 1, name)
5 Kendriya Vidyalaya
123
for i in range(5):
no items left โ†’ loop ends
Q6 PYTHON

Write a program to calculate the LCM and HCF of two numbers.

# Program 6 : LCM and HCF
num1 = int(input("Enter first number : "))
num2 = int(input("Enter second number: "))
small = min(num1, num2)
hcf = 1
for i in range(1, small + 1):          # include 'small' itself
    if num1 % i == 0 and num2 % i == 0:
        hcf = i
lcm = (num1 * num2) // hcf
print("HCF =", hcf)
print("LCM =", lcm)
โ–ถ Sample Output
Enter first number : 45
Enter second number: 95
HCF = 5
LCM = 855
๐Ÿ’ก Explanation: HCF is the largest number that divides both. range(1, small + 1) must include small itself (e.g. HCF of 12 and 36 is 12). LCM = (a x b) / HCF.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ num1, num2
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 45, 95 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 6 : LCM and HCF
2
num1 = int(input("Enter first number : "))
โŒจ๏ธ Input Shows "Enter first number : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable num1
3
num2 = int(input("Enter second number: "))
โŒจ๏ธ Input Shows "Enter second number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable num2
4
small = min(num1, num2)
๐Ÿงฎ Store / Calculate Finds the smallest value among num1, num2; the result is stored in variable small
5
hcf = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable hcf
6
for i in range(1, small + 1):          # include 'small' itself
๐Ÿ” Loop LOOP: gives the numbers from 1 up to small + 1 - 1; for each number, i takes that value and the indented block runs once
7
if num1 % i == 0 and num2 % i == 0:
๐Ÿ”€ Decision CHECKS whether (num1 % i is equal to 0 AND num2 % i is equal to 0). If True, the indented lines below run; otherwise they are skipped
8
hcf = i
๐Ÿงฎ Store / Calculate Stores the value of i in variable hcf
9
lcm = (num1 * num2) // hcf
๐Ÿงฎ Store / Calculate Stores the value of (num1 * num2) // hcf (calculated using // (integer division)) in variable lcm
10
print("HCF =", hcf)
๐Ÿ–ฅ๏ธ Output Displays the text "HCF =", then the value of hcf on the screen
11
print("LCM =", lcm)
๐Ÿ–ฅ๏ธ Output Displays the text "LCM =", then the value of lcm on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
num1 = int(input("Enter first number : "))
num1 = 45
Enter first number : 45
23
num2 = int(input("Enter second number: "))
num2 = 95
Enter second number: 95
34
small = min(num1, num2)
small = 45
45
hcf = 1
hcf = 1
56
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 1
67
if num1 % i == 0 and num2 % i == 0:
condition is TRUE โ†’ enters the block
78
hcf = i
86
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 2
97
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
106
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 3
117
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
126
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 4
137
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
146
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 5
157
if num1 % i == 0 and num2 % i == 0:
condition is TRUE โ†’ enters the block
168
hcf = i
hcf = 5
176
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 6
187
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
196
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 7
207
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
216
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 8
227
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
236
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 9
247
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
256
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 10
267
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
276
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 11
287
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
296
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 12
307
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block
316
for i in range(1, small + 1):          # include 'small' itself
next item taken
i = 13
327
if num1 % i == 0 and num2 % i == 0:
condition is FALSE โ†’ skips this block

โ€ฆ Python runs 68 more line-steps in the same way (loops repeat the same lines). Final values: num1 = 45, num2 = 95, small = 45, hcf = 5, i = 45, lcm = 855

Q7 PYTHON

Write a program to print a right-angled triangle pattern.

# Program 7 : Right-angled triangle pattern
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
    print('* ' * i)
โ–ถ Sample Output
Enter the number of rows: 5
* 
* * 
* * * 
* * * * 
* * * * *
๐Ÿ’ก Explanation: String replication: '* ' * i prints the star i times. Row 1 has 1 star, row 2 has 2 stars and so on.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ rows
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 5 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 7 : Right-angled triangle pattern
2
rows = int(input("Enter the number of rows: "))
โŒจ๏ธ Input Shows "Enter the number of rows: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable rows
3
for i in range(1, rows + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to rows + 1 - 1; for each number, i takes that value and the indented block runs once
4
print('* ' * i)
๐Ÿ–ฅ๏ธ Output Displays the value of '* ' * i on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
rows = int(input("Enter the number of rows: "))
rows = 5
Enter the number of rows: 5
23
for i in range(1, rows + 1):
next item taken
i = 1
34
print('* ' * i)
* 
43
for i in range(1, rows + 1):
next item taken
i = 2
54
print('* ' * i)
* * 
63
for i in range(1, rows + 1):
next item taken
i = 3
74
print('* ' * i)
* * * 
83
for i in range(1, rows + 1):
next item taken
i = 4
94
print('* ' * i)
* * * * 
103
for i in range(1, rows + 1):
next item taken
i = 5
114
print('* ' * i)
* * * * * 
123
for i in range(1, rows + 1):
no items left โ†’ loop ends
Q8 PYTHON

Write a program to count vowels and consonants in a string.

# Program 8 : Count vowels and consonants
text = input("Enter a string: ")
v = c = 0
for ch in text:
    if ch.isalpha():
        if ch in "aeiouAEIOU":
            v += 1
        else:
            c += 1
print("Total number of vowels     :", v)
print("Total number of consonants :", c)
โ–ถ Sample Output
Enter a string: pm shri kendriya vidyalaya shalimar bagh
Total number of vowels     : 12
Total number of consonants : 23
๐Ÿ’ก Explanation: isalpha() ignores spaces, digits and symbols. The membership operator 'in' checks whether the character is a vowel.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ text
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type pm shri kendriya vidyalaya shalimar bagh (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 8 : Count vowels and consonants
2
text = input("Enter a string: ")
โŒจ๏ธ Input Shows the message "Enter a string: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable text
3
v = c = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable v
4
for ch in text:
๐Ÿ” Loop LOOP: takes each item of text one-by-one into ch and runs the indented block for it
5
if ch.isalpha():
๐Ÿ”€ Decision CHECKS whether ch.isalpha() is True. If True, the indented lines below run; otherwise they are skipped
6
if ch in "aeiouAEIOU":
๐Ÿ”€ Decision CHECKS whether ch is present in "aeiouAEIOU". If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
v += 1
๐Ÿงฎ Store / Calculate Adds 1 to v (same as v = v + 1)
8
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
9
c += 1
๐Ÿงฎ Store / Calculate Adds 1 to c (same as c = c + 1)
10
print("Total number of vowels     :", v)
๐Ÿ–ฅ๏ธ Output Displays the text "Total number of vowels :", then the value of v on the screen
11
print("Total number of consonants :", c)
๐Ÿ–ฅ๏ธ Output Displays the text "Total number of consonants :", then the value of c on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
text = input("Enter a string: ")
text = 'pm shri kendriya vidyalaya shalimar bagh'
Enter a string: pm shri kendriya vidyalaya shalimar bagh
23
v = c = 0
v = 0, c = 0
34
for ch in text:
next item taken
ch = 'p'
45
if ch.isalpha():
condition is TRUE โ†’ enters the block
56
if ch in "aeiouAEIOU":
condition is FALSE โ†’ skips this block
69
c += 1
c = 1
74
for ch in text:
next item taken
ch = 'm'
85
if ch.isalpha():
condition is TRUE โ†’ enters the block
96
if ch in "aeiouAEIOU":
condition is FALSE โ†’ skips this block
109
c += 1
c = 2
114
for ch in text:
next item taken
ch = ' '
125
if ch.isalpha():
condition is FALSE โ†’ skips this block
134
for ch in text:
next item taken
ch = 's'
145
if ch.isalpha():
condition is TRUE โ†’ enters the block
156
if ch in "aeiouAEIOU":
condition is FALSE โ†’ skips this block
169
c += 1
c = 3
174
for ch in text:
next item taken
ch = 'h'
185
if ch.isalpha():
condition is TRUE โ†’ enters the block
196
if ch in "aeiouAEIOU":
condition is FALSE โ†’ skips this block
209
c += 1
c = 4
214
for ch in text:
next item taken
ch = 'r'
225
if ch.isalpha():
condition is TRUE โ†’ enters the block
236
if ch in "aeiouAEIOU":
condition is FALSE โ†’ skips this block
249
c += 1
c = 5
254
for ch in text:
next item taken
ch = 'i'
265
if ch.isalpha():
condition is TRUE โ†’ enters the block
276
if ch in "aeiouAEIOU":
condition is TRUE โ†’ enters the block
287
v += 1
v = 1
294
for ch in text:
next item taken
ch = ' '
305
if ch.isalpha():
condition is FALSE โ†’ skips this block
314
for ch in text:
next item taken
ch = 'k'
325
if ch.isalpha():
condition is TRUE โ†’ enters the block

โ€ฆ Python runs 123 more line-steps in the same way (loops repeat the same lines). Final values: text = 'pm shri kendriya vidyalaya shalimar bagh', v = 12, c = 23, ch = 'h'

Q9 PYTHON

Write a menu-driven program to insert and delete elements in a list.

# Program 9 : Insert and delete elements in a list
my_list = []
while True:
    print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
    choice = input("Enter your choice: ")
    if choice == '1':
        element = input("Enter element to insert: ")
        my_list.append(element)
        print(element, "inserted.")
    elif choice == '2':
        element = input("Enter element to delete: ")
        if element in my_list:
            my_list.remove(element)
            print(element, "deleted.")
        else:
            print(element, "is not in the list.")
    elif choice == '3':
        print("List:", my_list)
    elif choice == '4':
        break
    else:
        print("Invalid choice")
โ–ถ Sample Output

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 1
Enter element to insert: AI
AI inserted.

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 1
Enter element to insert: ML
ML inserted.

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 1
Enter element to insert: DL
DL inserted.

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 3
List: ['AI', 'ML', 'DL']

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 2
Enter element to delete: ML
ML deleted.

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 2
Enter element to delete: CV
CV is not in the list.

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 3
List: ['AI', 'DL']

1. Insert an element  2. Delete an element  3. Display  4. Exit
Enter your choice: 4
๐Ÿ’ก Explanation: append() inserts at the end and remove() deletes the first matching value. Checking 'in' before remove() avoids a ValueError.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ choice, element
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, AI, 1, ML, 1, DL, 3, 2, ML, 2 โ€ฆ (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 9 : Insert and delete elements in a list
2
my_list = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable my_list
3
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
4
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1. Insert an element 2. Delete anโ€ฆ" on the screen
5
choice = input("Enter your choice: ")
โŒจ๏ธ Input Shows the message "Enter your choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable choice
6
if choice == '1':
๐Ÿ”€ Decision CHECKS whether choice is equal to '1'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
7
element = input("Enter element to insert: ")
โŒจ๏ธ Input Shows the message "Enter element to insert: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable element
8
my_list.append(element)
๐Ÿงฎ Store / Calculate Adds element at the end of list my_list
9
print(element, "inserted.")
๐Ÿ–ฅ๏ธ Output Displays the value of element, then the text "inserted." on the screen
10
elif choice == '2':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '2'
11
element = input("Enter element to delete: ")
โŒจ๏ธ Input Shows the message "Enter element to delete: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable element
12
if element in my_list:
๐Ÿ”€ Decision CHECKS whether element is present in my_list. If True, the indented lines below run; otherwise Python jumps to the elif/else part
13
my_list.remove(element)
๐Ÿงฎ Store / Calculate Removes the first element from my_list
14
print(element, "deleted.")
๐Ÿ–ฅ๏ธ Output Displays the value of element, then the text "deleted." on the screen
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
print(element, "is not in the list.")
๐Ÿ–ฅ๏ธ Output Displays the value of element, then the text "is not in the list." on the screen
17
elif choice == '3':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '3'
18
print("List:", my_list)
๐Ÿ–ฅ๏ธ Output Displays the text "List:", then the value of my_list on the screen
19
elif choice == '4':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether choice is equal to '4'
20
break
๐Ÿ” Loop BREAK - leaves the loop immediately
21
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
22
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
my_list = []
my_list = []
23
while True:
condition is TRUE โ†’ enters the block
34
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
1. Insert an element  2. Delete an element  3. Display  4. Exit
45
choice = input("Enter your choice: ")
choice = '1'
Enter your choice: 1
56
if choice == '1':
condition is TRUE โ†’ enters the block
67
element = input("Enter element to insert: ")
element = 'AI'
Enter element to insert: AI
78
my_list.append(element)
my_list = ['AI']
89
print(element, "inserted.")
AI inserted.
93
while True:
condition is TRUE โ†’ enters the block
104
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
1. Insert an element  2. Delete an element  3. Display  4. Exit
115
choice = input("Enter your choice: ")
Enter your choice: 1
126
if choice == '1':
condition is TRUE โ†’ enters the block
137
element = input("Enter element to insert: ")
element = 'ML'
Enter element to insert: ML
148
my_list.append(element)
my_list = ['AI', 'ML']
159
print(element, "inserted.")
ML inserted.
163
while True:
condition is TRUE โ†’ enters the block
174
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
1. Insert an element  2. Delete an element  3. Display  4. Exit
185
choice = input("Enter your choice: ")
Enter your choice: 1
196
if choice == '1':
condition is TRUE โ†’ enters the block
207
element = input("Enter element to insert: ")
element = 'DL'
Enter element to insert: DL
218
my_list.append(element)
my_list = ['AI', 'ML', 'DL']
229
print(element, "inserted.")
DL inserted.
233
while True:
condition is TRUE โ†’ enters the block
244
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
1. Insert an element  2. Delete an element  3. Display  4. Exit
255
choice = input("Enter your choice: ")
choice = '3'
Enter your choice: 3
266
if choice == '1':
condition is FALSE โ†’ skips this block
2710
elif choice == '2':
condition is FALSE โ†’ skips this block
2817
elif choice == '3':
condition is TRUE โ†’ enters the block
2918
print("List:", my_list)
List: ['AI', 'ML', 'DL']
303
while True:
condition is TRUE โ†’ enters the block
314
print("\n1. Insert an element  2. Delete an element  3. Display  4. Exit")
1. Insert an element  2. Delete an element  3. Display  4. Exit
325
choice = input("Enter your choice: ")
choice = '2'
Enter your choice: 2

โ€ฆ Python runs 29 more line-steps in the same way (loops repeat the same lines). Final values: my_list = ['AI', 'DL'], choice = '4', element = 'CV'

Q10 PYTHON

Write a program to add the elements of the two lists.

# Program 10 : Add elements of two lists
list1 = [10, 20, 30, 40, 50]
list2 = [5, 15, 25, 35, 45]
result = []
for i in range(len(list1)):
    result.append(list1[i] + list2[i])
print("List 1 :", list1)
print("List 2 :", list2)
print("Sum    :", result)

# Same task using NumPy (element-wise addition)
import numpy as np
print("Using NumPy:", np.array(list1) + np.array(list2))
โ–ถ Sample Output
List 1 : [10, 20, 30, 40, 50]
List 2 : [5, 15, 25, 35, 45]
Sum    : [15, 35, 55, 75, 95]
Using NumPy: [15 35 55 75 95]
๐Ÿ’ก Explanation: Corresponding elements (same index) are added. With NumPy arrays, + automatically adds element-wise - this is why NumPy is used in AI for fast calculations.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 10 : Add elements of two lists
2
list1 = [10, 20, 30, 40, 50]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 30, 40, 50] in variable list1
3
list2 = [5, 15, 25, 35, 45]
๐Ÿงฎ Store / Calculate Stores a list [5, 15, 25, 35, 45] in variable list2
4
result = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable result
5
for i in range(len(list1)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(list1) - 1; for each number, i takes that value and the indented block runs once
6
result.append(list1[i] + list2[i])
๐Ÿงฎ Store / Calculate Adds list1[i] + list2[i] at the end of list result
7
print("List 1 :", list1)
๐Ÿ–ฅ๏ธ Output Displays the text "List 1 :", then the value of list1 on the screen
8
print("List 2 :", list2)
๐Ÿ–ฅ๏ธ Output Displays the text "List 2 :", then the value of list2 on the screen
9
print("Sum    :", result)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum :", then the value of result on the screen
๐Ÿ“Œ Same task using NumPy (element-wise addition)
12
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
13
print("Using NumPy:", np.array(list1) + np.array(list2))
๐Ÿ–ฅ๏ธ Output Displays the text "Using NumPy:", then the value of np.array(list1) + np.array(list2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
list1 = [10, 20, 30, 40, 50]
list1 = [10, 20, 30, 40, 50]
23
list2 = [5, 15, 25, 35, 45]
list2 = [5, 15, 25, 35, 45]
34
result = []
result = []
45
for i in range(len(list1)):
next item taken
i = 0
56
result.append(list1[i] + list2[i])
result = [15]
65
for i in range(len(list1)):
next item taken
i = 1
76
result.append(list1[i] + list2[i])
result = [15, 35]
85
for i in range(len(list1)):
next item taken
i = 2
96
result.append(list1[i] + list2[i])
result = [15, 35, 55]
105
for i in range(len(list1)):
next item taken
i = 3
116
result.append(list1[i] + list2[i])
result = [15, 35, 55, 75]
125
for i in range(len(list1)):
next item taken
i = 4
136
result.append(list1[i] + list2[i])
result = [15, 35, 55, 75, 95]
145
for i in range(len(list1)):
no items left โ†’ loop ends
157
print("List 1 :", list1)
List 1 : [10, 20, 30, 40, 50]
168
print("List 2 :", list2)
List 2 : [5, 15, 25, 35, 45]
179
print("Sum    :", result)
Sum    : [15, 35, 55, 75, 95]
1812
import numpy as np
1913
print("Using NumPy:", np.array(list1) + np.array(list2))
Using NumPy: [15 35 55 75 95]
Q11 PYTHON

Write a program to calculate the mean of a given list.

# Program 11 : Mean of a list
numbers = [10, 20, 30, 40, 50]
mean = sum(numbers) / len(numbers)
print("Given List:", numbers)
print("Mean:", mean)
โ–ถ Sample Output
Given List: [10, 20, 30, 40, 50]
Mean: 30.0
๐Ÿ’ก Explanation: Mean = sum of all values / number of values = 150 / 5 = 30.0
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses simple statements, one after another
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 11 : Mean of a list
2
numbers = [10, 20, 30, 40, 50]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 30, 40, 50] in variable numbers
3
mean = sum(numbers) / len(numbers)
๐Ÿงฎ Store / Calculate Stores the value of sum(numbers) / len(numbers) (calculated using รท) in variable mean
4
print("Given List:", numbers)
๐Ÿ–ฅ๏ธ Output Displays the text "Given List:", then the value of numbers on the screen
5
print("Mean:", mean)
๐Ÿ–ฅ๏ธ Output Displays the text "Mean:", then the value of mean on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
numbers = [10, 20, 30, 40, 50]
numbers = [10, 20, 30, 40, 50]
23
mean = sum(numbers) / len(numbers)
mean = 30.0
34
print("Given List:", numbers)
Given List: [10, 20, 30, 40, 50]
45
print("Mean:", mean)
Mean: 30.0
Q12 PYTHON

Write a program to create a 2D array using NumPy.

# Program 12 : 2D array using NumPy
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(array_2d)
print("Dimensions (ndim):", array_2d.ndim)
print("Shape            :", array_2d.shape)
print("Total elements   :", array_2d.size)
โ–ถ Sample Output
[[1 2 3]
 [4 5 6]]
Dimensions (ndim): 2
Shape            : (2, 3)
Total elements   : 6
๐Ÿ’ก Explanation: A 2D array has rows and columns. shape (2, 3) means 2 rows and 3 columns. Images are stored as 2D/3D arrays of pixels in exactly this way.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 12 : 2D array using NumPy
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[1, 2, 3], [4, 5, 6]]; the result is stored in variable array_2d
4
print(array_2d)
๐Ÿ–ฅ๏ธ Output Displays the value of array_2d on the screen
5
print("Dimensions (ndim):", array_2d.ndim)
๐Ÿ–ฅ๏ธ Output Displays the text "Dimensions (ndim):", then the value of array_2d.ndim on the screen
6
print("Shape            :", array_2d.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape :", then the value of array_2d.shape on the screen
7
print("Total elements   :", array_2d.size)
๐Ÿ–ฅ๏ธ Output Displays the text "Total elements :", then the value of array_2d.size on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
array_2d = array([[1, 2, 3], [4, 5, 6]])
34
print(array_2d)
[[1 2 3]
 [4 5 6]]
45
print("Dimensions (ndim):", array_2d.ndim)
Dimensions (ndim): 2
56
print("Shape            :", array_2d.shape)
Shape            : (2, 3)
67
print("Total elements   :", array_2d.size)
Total elements   : 6
Q13 PYTHON

Write a program to convert a Python list to a NumPy array.

# Program 13 : List to NumPy array
import numpy as np
my_list = [10, 20, 30, 40]
numpy_array = np.array(my_list)
print("Python list :", my_list, type(my_list))
print("NumPy array :", numpy_array, type(numpy_array))
print("Array * 2   :", numpy_array * 2)
โ–ถ Sample Output
Python list : [10, 20, 30, 40] <class 'list'>
NumPy array : [10 20 30 40] <class 'numpy.ndarray'>
Array * 2   : [20 40 60 80]
๐Ÿ’ก Explanation: np.array() converts a list into an ndarray. Notice that array * 2 doubles every element, whereas list * 2 would repeat the list.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 13 : List to NumPy array
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
my_list = [10, 20, 30, 40]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 30, 40] in variable my_list
4
numpy_array = np.array(my_list)
๐Ÿ“ฆ Library / Data Makes a NumPy array from my_list; the result is stored in variable numpy_array
5
print("Python list :", my_list, type(my_list))
๐Ÿ–ฅ๏ธ Output Displays the text "Python list :", then the value of my_list, then the value of type(my_list) on the screen
6
print("NumPy array :", numpy_array, type(numpy_array))
๐Ÿ–ฅ๏ธ Output Displays the text "NumPy array :", then the value of numpy_array, then the value of type(numpy_array) on the screen
7
print("Array * 2   :", numpy_array * 2)
๐Ÿ–ฅ๏ธ Output Displays the text "Array * 2 :", then the value of numpy_array * 2 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
my_list = [10, 20, 30, 40]
my_list = [10, 20, 30, 40]
34
numpy_array = np.array(my_list)
numpy_array = array([10, 20, 30, 40])
45
print("Python list :", my_list, type(my_list))
Python list : [10, 20, 30, 40] <class 'list'>
56
print("NumPy array :", numpy_array, type(numpy_array))
NumPy array : [10 20 30 40] <class 'numpy.ndarray'>
67
print("Array * 2   :", numpy_array * 2)
Array * 2   : [20 40 60 80]
Q14 PYTHON

Write a program to create a 3x3 matrix with values from 11 to 19.

# Program 14 : 3x3 matrix using arange() and reshape()
import numpy as np
matrix_3x3 = np.arange(11, 20).reshape(3, 3)
print(matrix_3x3)
โ–ถ Sample Output
[[11 12 13]
 [14 15 16]
 [17 18 19]]
๐Ÿ’ก Explanation: np.arange(11, 20) gives 9 numbers 11 to 19 (20 is excluded) and reshape(3, 3) arranges them into 3 rows x 3 columns.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q14.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 14 : 3x3 matrix using arange() and reshape()
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
matrix_3x3 = np.arange(11, 20).reshape(3, 3)
๐Ÿ“ฆ Library / Data Changes the shape of np.arange(11, 20) to (3, 3); the result is stored in variable matrix_3x3
4
print(matrix_3x3)
๐Ÿ–ฅ๏ธ Output Displays the value of matrix_3x3 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
matrix_3x3 = np.arange(11, 20).reshape(3, 3)
matrix_3x3 = array of shape (3, 3)
34
print(matrix_3x3)
[[11 12 13]
 [14 15 16]
 [17 18 19]]
Q15 PYTHON

Write a program to calculate mean, median and mode using NumPy.

# Program 15 : Mean, median and mode using NumPy
import numpy as np
marks = np.array([45, 67, 89, 67, 90, 56, 67, 78, 89, 72])
mean = np.mean(marks)
median = np.median(marks)
values, counts = np.unique(marks, return_counts=True)
mode = values[np.argmax(counts)]
print("Marks  :", marks)
print("Mean   :", mean)
print("Median :", median)
print("Mode   :", mode, "(occurs", counts.max(), "times)")
โ–ถ Sample Output
Marks  : [45 67 89 67 90 56 67 78 89 72]
Mean   : 72.0
Median : 69.5
Mode   : 67 (occurs 3 times)
๐Ÿ’ก Explanation: np.mean() and np.median() are built in. NumPy has no mode() function, so np.unique(..., return_counts=True) counts each value and argmax() picks the most frequent one.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 15 : Mean, median and mode using NumPy
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
marks = np.array([45, 67, 89, 67, 90, 56, 67, 78, 89, 72])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [45, 67, 89, 67, 90, 56, 67, 78, 89, 72]; the result is stored in variable marks
4
mean = np.mean(marks)
๐Ÿ“ฆ Library / Data Finds the average (mean) of np; the result is stored in variable mean
5
median = np.median(marks)
๐Ÿ“ฆ Library / Data Finds the middle value of np; the result is stored in variable median
6
values, counts = np.unique(marks, return_counts=True)
๐Ÿ“ฆ Library / Data Gives the unique values of np; the result is stored in variables values, counts
7
mode = values[np.argmax(counts)]
๐Ÿ“ฆ Library / Data Stores the item values[np.argmax(counts)] in variable mode
8
print("Marks  :", marks)
๐Ÿ–ฅ๏ธ Output Displays the text "Marks :", then the value of marks on the screen
9
print("Mean   :", mean)
๐Ÿ–ฅ๏ธ Output Displays the text "Mean :", then the value of mean on the screen
10
print("Median :", median)
๐Ÿ–ฅ๏ธ Output Displays the text "Median :", then the value of median on the screen
11
print("Mode   :", mode, "(occurs", counts.max(), "times)")
๐Ÿ–ฅ๏ธ Output Displays the text "Mode :", then the value of mode, then the text "(occurs", then the value of counts.max(), then the text "times)" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
marks = np.array([45, 67, 89, 67, 90, 56, 67, 78, 89, 72])
marks = array of shape (10,)
34
mean = np.mean(marks)
mean = np.float64(72.0)
45
median = np.median(marks)
median = np.float64(69.5)
56
values, counts = np.unique(marks, return_counts=True)
values = array([45, 56, 67, 72, 78, 89, 90]), counts = array([1, 1, 3, 1, 1, 2, 1])
67
mode = values[np.argmax(counts)]
mode = np.int64(67)
78
print("Marks  :", marks)
Marks  : [45 67 89 67 90 56 67 78 89 72]
89
print("Mean   :", mean)
Mean   : 72.0
910
print("Median :", median)
Median : 69.5
1011
print("Mode   :", mode, "(occurs", counts.max(), "times)")
Mode   : 67 (occurs 3 times)
Q16 PYTHON

Write a menu-driven program to calculate mean, mode and median using the statistics module.

# Program 16 : Menu-driven mean / median / mode
import statistics
data = [1, 2, 2, 3, 4, 5]
print("Data:", data)
while True:
    print("\n1. Mean  2. Median  3. Mode  4. Exit")
    ch = input("Enter choice: ")
    if ch == '1':
        print("Mean   =", round(statistics.mean(data), 2))
    elif ch == '2':
        print("Median =", statistics.median(data))
    elif ch == '3':
        print("Mode   =", statistics.mode(data))
    elif ch == '4':
        print("Bye!")
        break
    else:
        print("Invalid choice")
โ–ถ Sample Output
Data: [1, 2, 2, 3, 4, 5]

1. Mean  2. Median  3. Mode  4. Exit
Enter choice: 1
Mean   = 2.83

1. Mean  2. Median  3. Mode  4. Exit
Enter choice: 2
Median = 2.5

1. Mean  2. Median  3. Mode  4. Exit
Enter choice: 3
Mode   = 2

1. Mean  2. Median  3. Mode  4. Exit
Enter choice: 4
Bye!
๐Ÿ’ก Explanation: statistics.median() of an even-sized list is the average of the two middle values: (2 + 3) / 2 = 2.5.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ ch
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else; module statistics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 1, 2, 3, 4 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 16 : Menu-driven mean / median / mode
2
import statistics
๐Ÿ“ฆ Library / Data Loads the module statistics - mean, median, mode functions
3
data = [1, 2, 2, 3, 4, 5]
๐Ÿงฎ Store / Calculate Stores a list [1, 2, 2, 3, 4, 5] in variable data
4
print("Data:", data)
๐Ÿ–ฅ๏ธ Output Displays the text "Data:", then the value of data on the screen
5
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
6
print("\n1. Mean  2. Median  3. Mode  4. Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1. Mean 2. Median 3. Mode 4. Exit" on the screen
7
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
8
if ch == '1':
๐Ÿ”€ Decision CHECKS whether ch is equal to '1'. If True, the indented lines below run; otherwise Python jumps to the elif/else part
9
print("Mean   =", round(statistics.mean(data), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Mean =", then the value of round(statistics.mean(data), 2) on the screen
10
elif ch == '2':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to '2'
11
print("Median =", statistics.median(data))
๐Ÿ–ฅ๏ธ Output Displays the text "Median =", then the value of statistics.median(data) on the screen
12
elif ch == '3':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to '3'
13
print("Mode   =", statistics.mode(data))
๐Ÿ–ฅ๏ธ Output Displays the text "Mode =", then the value of statistics.mode(data) on the screen
14
elif ch == '4':
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to '4'
15
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
16
break
๐Ÿ” Loop BREAK - leaves the loop immediately
17
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
18
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import statistics
23
data = [1, 2, 2, 3, 4, 5]
data = [1, 2, 2, 3, 4, 5]
34
print("Data:", data)
Data: [1, 2, 2, 3, 4, 5]
45
while True:
condition is TRUE โ†’ enters the block
56
print("\n1. Mean  2. Median  3. Mode  4. Exit")
1. Mean  2. Median  3. Mode  4. Exit
67
ch = input("Enter choice: ")
ch = '1'
Enter choice: 1
78
if ch == '1':
condition is TRUE โ†’ enters the block
89
print("Mean   =", round(statistics.mean(data), 2))
Mean   = 2.83
95
while True:
condition is TRUE โ†’ enters the block
106
print("\n1. Mean  2. Median  3. Mode  4. Exit")
1. Mean  2. Median  3. Mode  4. Exit
117
ch = input("Enter choice: ")
ch = '2'
Enter choice: 2
128
if ch == '1':
condition is FALSE โ†’ skips this block
1310
elif ch == '2':
condition is TRUE โ†’ enters the block
1411
print("Median =", statistics.median(data))
Median = 2.5
155
while True:
condition is TRUE โ†’ enters the block
166
print("\n1. Mean  2. Median  3. Mode  4. Exit")
1. Mean  2. Median  3. Mode  4. Exit
177
ch = input("Enter choice: ")
ch = '3'
Enter choice: 3
188
if ch == '1':
condition is FALSE โ†’ skips this block
1910
elif ch == '2':
condition is FALSE โ†’ skips this block
2012
elif ch == '3':
condition is TRUE โ†’ enters the block
2113
print("Mode   =", statistics.mode(data))
Mode   = 2
225
while True:
condition is TRUE โ†’ enters the block
236
print("\n1. Mean  2. Median  3. Mode  4. Exit")
1. Mean  2. Median  3. Mode  4. Exit
247
ch = input("Enter choice: ")
ch = '4'
Enter choice: 4
258
if ch == '1':
condition is FALSE โ†’ skips this block
2610
elif ch == '2':
condition is FALSE โ†’ skips this block
2712
elif ch == '3':
condition is FALSE โ†’ skips this block
2814
elif ch == '4':
condition is TRUE โ†’ enters the block
2915
print("Bye!")
Bye!
3016
break
Q17 PYTHON

Write a program to calculate variance and standard deviation.

# Program 17 : Variance and standard deviation
import statistics
data = [10, 20, 30, 40, 50]
variance = statistics.variance(data)      # sample variance
std_dev = statistics.stdev(data)          # sample standard deviation
print("Data               :", data)
print("Variance           :", variance)
print("Standard deviation :", round(std_dev, 4))
โ–ถ Sample Output
Data               : [10, 20, 30, 40, 50]
Variance           : 250
Standard deviation : 15.8114
๐Ÿ’ก Explanation: Variance measures how far values spread from the mean; standard deviation is its square root (same unit as the data). statistics.variance() divides by n-1 (sample variance).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module statistics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 17 : Variance and standard deviation
2
import statistics
๐Ÿ“ฆ Library / Data Loads the module statistics - mean, median, mode functions
3
data = [10, 20, 30, 40, 50]
๐Ÿงฎ Store / Calculate Stores a list [10, 20, 30, 40, 50] in variable data
4
variance = statistics.variance(data)      # sample variance
๐Ÿงฎ Store / Calculate Finds the variance of data; the result is stored in variable variance
5
std_dev = statistics.stdev(data)          # sample standard deviation
๐Ÿงฎ Store / Calculate Finds the sample standard deviation of data; the result is stored in variable std_dev
6
print("Data               :", data)
๐Ÿ–ฅ๏ธ Output Displays the text "Data :", then the value of data on the screen
7
print("Variance           :", variance)
๐Ÿ–ฅ๏ธ Output Displays the text "Variance :", then the value of variance on the screen
8
print("Standard deviation :", round(std_dev, 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Standard deviation :", then the value of round(std_dev, 4) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import statistics
23
data = [10, 20, 30, 40, 50]
data = [10, 20, 30, 40, 50]
34
variance = statistics.variance(data)      # sample variance
variance = 250
45
std_dev = statistics.stdev(data)          # sample standard deviation
std_dev = 15.811388300841896
56
print("Data               :", data)
Data               : [10, 20, 30, 40, 50]
67
print("Variance           :", variance)
Variance           : 250
78
print("Standard deviation :", round(std_dev, 4))
Standard deviation : 15.8114
Q18 PYTHON

Write a program to create a DataFrame to store data of candidates who appeared in interviews.

# Program 18 : DataFrame of interview candidates
import pandas as pd
data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'],
        'Age': [25, 30, 22, 27, 24],
        'Interview_Score': [85, 90, 88, 76, 93]}
df = pd.DataFrame(data)
print(df)
print("\nHighest score:", df['Interview_Score'].max())
โ–ถ Sample Output
     Name  Age  Interview_Score
0    Aman   25               85
1  Babita   30               90
2   Karan   22               88
3   Divya   27               76
4    Esha   24               93

Highest score: 93
๐Ÿ’ก Explanation: A DataFrame is a 2D table with labelled columns, created here from a dictionary. Each key becomes a column name.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 18 : DataFrame of interview candidates
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'],
        'Age': [25, 30, 22, 27, 24],
        'Interview_Score': [85, 90, 88, 76, 93]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Name': ['Aman', 'Babita', 'Karan', 'Divya',โ€ฆ in variable data
6
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
7
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
8
print("\nHighest score:", df['Interview_Score'].max())
๐Ÿ–ฅ๏ธ Output Displays the text "Highest score:", then the value of df['Interview_Score'].max() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'],
34
'Age': [25, 30, 22, 27, 24],
45
'Interview_Score': [85, 90, 88, 76, 93]}
53
data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'],
data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'], 'Age': [25, โ€ฆ
66
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 3 columns)
77
print(df)
     Name  Age  Interview_Score
0    Aman   25               85
1  Babita   30               90
2   Karan   22               88
3   Divya   27               76
4    Esha   24               93
88
print("\nHighest score:", df['Interview_Score'].max())
Highest score: 93
Q19 PYTHON

Write a program to create a DataFrame of players and filter the players who scored more than 1000 runs.

# Program 19 : Filter a DataFrame
import pandas as pd
data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'],
        'Runs': [1450, 1820, 990, 560, 1105]}
df = pd.DataFrame(data)
print("All players:\n", df)
filtered_df = df[df['Runs'] > 1000]
print("\nPlayers with Runs > 1000:\n", filtered_df)
โ–ถ Sample Output
All players:
     Player  Runs
0    Rohit  1450
1    Virat  1820
2  Shubman   990
3    Rinku   560
4   Hardik  1105

Players with Runs > 1000:
    Player  Runs
0   Rohit  1450
1   Virat  1820
4  Hardik  1105
๐Ÿ’ก Explanation: df['Runs'] > 1000 creates a True/False mask; df[mask] keeps only the rows where the condition is True (boolean indexing).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 19 : Filter a DataFrame
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'],
        'Runs': [1450, 1820, 990, 560, 1105]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinโ€ฆ in variable data
5
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
6
print("All players:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "All players:", then the value of df on the screen
7
filtered_df = df[df['Runs'] > 1000]
๐Ÿงฎ Store / Calculate Stores the item df[df['Runs'] > 1000] in variable filtered_df
8
print("\nPlayers with Runs > 1000:\n", filtered_df)
๐Ÿ–ฅ๏ธ Output Displays the text "Players with Runs > 1000:", then the value of filtered_df on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'],
34
'Runs': [1450, 1820, 990, 560, 1105]}
43
data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'],
data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'], 'Runs'โ€ฆ
55
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 2 columns)
66
print("All players:\n", df)
All players:
     Player  Runs
0    Rohit  1450
1    Virat  1820
2  Shubman   990
3    Rinku   560
4   Hardik  1105
77
filtered_df = df[df['Runs'] > 1000]
filtered_df = DataFrame (3 rows ร— 2 columns)
88
print("\nPlayers with Runs > 1000:\n", filtered_df)
Players with Runs > 1000:
    Player  Runs
0   Rohit  1450
1   Virat  1820
4  Hardik  1105
Q20 PYTHON

Write a program to display a line chart from (2,5) to (9,10).

# Program 20 : Line chart from (2,5) to (9,10)
import matplotlib.pyplot as plt
x = [2, 9]
y = [5, 10]
plt.plot(x, y, color='blue', marker='o')
plt.title("Line chart from (2,5) to (9,10)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: plt.plot() joins the given points with a straight line. The x-values and y-values are given as two separate lists.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 20 : Line chart from (2,5) to (9,10)
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
x = [2, 9]
๐Ÿงฎ Store / Calculate Stores a list [2, 9] in variable x
4
y = [5, 10]
๐Ÿงฎ Store / Calculate Stores a list [5, 10] in variable y
5
plt.plot(x, y, color='blue', marker='o')
๐Ÿ–ฅ๏ธ Output Draws a line chart of x, y
6
plt.title("Line chart from (2,5) to (9,10)")
๐Ÿ–ฅ๏ธ Output Writes "Line chart from (2,5) to (9,10)" as the title of the chart
7
plt.xlabel("X-axis")
๐Ÿ–ฅ๏ธ Output Writes "X-axis" as the label of the X-axis
8
plt.ylabel("Y-axis")
๐Ÿ–ฅ๏ธ Output Writes "Y-axis" as the label of the Y-axis
9
plt.grid(True)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
10
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
x = [2, 9]
x = [2, 9]
34
y = [5, 10]
y = [5, 10]
45
plt.plot(x, y, color='blue', marker='o')
56
plt.title("Line chart from (2,5) to (9,10)")
67
plt.xlabel("X-axis")
78
plt.ylabel("Y-axis")
89
plt.grid(True)
910
plt.show()
Q21 PYTHON

Write a program to display a scatter chart for the points (2,5), (9,10), (8,3), (5,7), (6,18).

# Program 21 : Scatter chart
import matplotlib.pyplot as plt
x = [2, 9, 8, 5, 6]
y = [5, 10, 3, 7, 18]
plt.scatter(x, y, color='red', s=60)
plt.title("Scatter Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A scatter chart shows each point separately without joining them. It is used in AI to see the relationship (correlation) between two features.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q21.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 21 : Scatter chart
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
x = [2, 9, 8, 5, 6]
๐Ÿงฎ Store / Calculate Stores a list [2, 9, 8, 5, 6] in variable x
4
y = [5, 10, 3, 7, 18]
๐Ÿงฎ Store / Calculate Stores a list [5, 10, 3, 7, 18] in variable y
5
plt.scatter(x, y, color='red', s=60)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of x, y
6
plt.title("Scatter Chart")
๐Ÿ–ฅ๏ธ Output Writes "Scatter Chart" as the title of the chart
7
plt.xlabel("X-axis")
๐Ÿ–ฅ๏ธ Output Writes "X-axis" as the label of the X-axis
8
plt.ylabel("Y-axis")
๐Ÿ–ฅ๏ธ Output Writes "Y-axis" as the label of the Y-axis
9
plt.grid(True)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
10
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
x = [2, 9, 8, 5, 6]
x = [2, 9, 8, 5, 6]
34
y = [5, 10, 3, 7, 18]
y = [5, 10, 3, 7, 18]
45
plt.scatter(x, y, color='red', s=60)
56
plt.title("Scatter Chart")
67
plt.xlabel("X-axis")
78
plt.ylabel("Y-axis")
89
plt.grid(True)
910
plt.show()
Q22 PYTHON

Write a program to represent mobile game ratings on a bar chart.

# Program 22 : Bar chart of mobile game ratings
import matplotlib.pyplot as plt
games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing']
ratings = [4.5, 4.0, 3.8, 4.2, 3.5]
plt.bar(games, ratings, color=['teal', 'orange', 'green', 'purple', 'red'])
plt.xlabel('Games')
plt.ylabel('Ratings (out of 5)')
plt.title('Mobile Game Ratings')
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: plt.bar() compares values of different categories. Each bar's height equals the rating.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q22.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 22 : Bar chart of mobile game ratings
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing']
๐Ÿงฎ Store / Calculate Stores a list ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racinโ€ฆ in variable games
4
ratings = [4.5, 4.0, 3.8, 4.2, 3.5]
๐Ÿงฎ Store / Calculate Stores a list [4.5, 4.0, 3.8, 4.2, 3.5] in variable ratings
5
plt.bar(games, ratings, color=['teal', 'orange', 'green', 'purple', 'red'])
๐Ÿ–ฅ๏ธ Output Draws a bar chart of games, ratings
6
plt.xlabel('Games')
๐Ÿ–ฅ๏ธ Output Writes 'Games' as the label of the X-axis
7
plt.ylabel('Ratings (out of 5)')
๐Ÿ–ฅ๏ธ Output Writes 'Ratings (out of 5)' as the label of the Y-axis
8
plt.title('Mobile Game Ratings')
๐Ÿ–ฅ๏ธ Output Writes 'Mobile Game Ratings' as the title of the chart
9
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing']
games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing']
34
ratings = [4.5, 4.0, 3.8, 4.2, 3.5]
ratings = [4.5, 4.0, 3.8, 4.2, 3.5]
45
plt.bar(games, ratings, color=['teal', 'orange', 'green', 'purple', 'red'])
56
plt.xlabel('Games')
67
plt.ylabel('Ratings (out of 5)')
78
plt.title('Mobile Game Ratings')
89
plt.show()
Q23 PYTHON

Plot monthly sales data for garments on a line chart.

# Program 23 : Line chart of monthly garment sales
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [5000, 6000, 5500, 7000, 8000, 7600]
plt.plot(months, sales, marker='o', color='green', linewidth=2)
plt.xlabel('Months')
plt.ylabel('Sales (Rs.)')
plt.title('Monthly Sales Data for Garments')
plt.grid(True)
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A line chart is best for showing a trend over time. Markers highlight the actual monthly values.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q23.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 23 : Line chart of monthly garment sales
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
๐Ÿงฎ Store / Calculate Stores a list ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] in variable months
4
sales = [5000, 6000, 5500, 7000, 8000, 7600]
๐Ÿงฎ Store / Calculate Stores a list [5000, 6000, 5500, 7000, 8000, 7600] in variable sales
5
plt.plot(months, sales, marker='o', color='green', linewidth=2)
๐Ÿ–ฅ๏ธ Output Draws a line chart of months, sales
6
plt.xlabel('Months')
๐Ÿ–ฅ๏ธ Output Writes 'Months' as the label of the X-axis
7
plt.ylabel('Sales (Rs.)')
๐Ÿ–ฅ๏ธ Output Writes 'Sales (Rs.)' as the label of the Y-axis
8
plt.title('Monthly Sales Data for Garments')
๐Ÿ–ฅ๏ธ Output Writes 'Monthly Sales Data for Garments' as the title of the chart
9
plt.grid(True)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
10
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
34
sales = [5000, 6000, 5500, 7000, 8000, 7600]
sales = [5000, 6000, 5500, 7000, 8000, 7600]
45
plt.plot(months, sales, marker='o', color='green', linewidth=2)
56
plt.xlabel('Months')
67
plt.ylabel('Sales (Rs.)')
78
plt.title('Monthly Sales Data for Garments')
89
plt.grid(True)
910
plt.show()
Q24 PYTHON

Read the CSV file saved in your system and display 10 rows.

# Program 24 : Read a CSV file and display 10 rows
# (student_data.csv is saved in the same folder as this program)
import pandas as pd
df = pd.read_csv("student_data.csv")
print(df.head(10))
โ–ถ Sample Output
   RollNo     Name Gender  Maths  Science  AI
0       1    Aarav      M     78       82  91
1       2   Bhavya      F     88       79  95
2       3   Chetan      M     65       70  72
3       4     Diya      F     92       94  98
4       5  Eklavya      M     55       61  68
5       6    Farah      F     81       85  89
6       7    Gagan      M     73       69  80
7       8     Hina      F     95       90  97
8       9    Ishan      M     60       58  66
9      10     Jiya      F     84       88  90
๐Ÿ’ก Explanation: pd.read_csv() loads a CSV file into a DataFrame. head(10) shows the first 10 rows (default is 5). Create student_data.csv in Excel/Notepad with columns RollNo, Name, Gender, Maths, Science, AI and save it as CSV.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q24.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 24 : Read a CSV file and display 10 rows
๐Ÿ“Œ (student_data.csv is saved in the same folder as this program)
3
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
4
df = pd.read_csv("student_data.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "student_data.csv" into a DataFrame (table); the result is stored in variable df
5
print(df.head(10))
๐Ÿ–ฅ๏ธ Output Displays the value of df.head(10) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
13
import pandas as pd
24
df = pd.read_csv("student_data.csv")
df = DataFrame (15 rows ร— 6 columns)
35
print(df.head(10))
   RollNo     Name Gender  Maths  Science  AI
0       1    Aarav      M     78       82  91
1       2   Bhavya      F     88       79  95
2       3   Chetan      M     65       70  72
3       4     Diya      F     92       94  98
4       5  Eklavya      M     55       61  68
5       6    Farah   โ€ฆ
Q25 PYTHON

Read the CSV file saved in your system and display its information.

# Program 25 : Information about a CSV file
import pandas as pd
df = pd.read_csv("student_data.csv")
print("Shape (rows, columns):", df.shape)
print()
df.info()
print()
print(df.describe())
โ–ถ Sample Output
Shape (rows, columns): (15, 6)

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 15 entries, 0 to 14
Data columns (total 6 columns):
 #   Column   Non-Null Count  Dtype 
---  ------   --------------  ----- 
 0   RollNo   15 non-null     int64 
 1   Name     15 non-null     object
 2   Gender   15 non-null     object
 3   Maths    15 non-null     int64 
 4   Science  15 non-null     int64 
 5   AI       15 non-null     int64 
dtypes: int64(4), object(2)
memory usage: 852.0+ bytes

          RollNo      Maths    Science         AI
count  15.000000  15.000000  15.000000  15.000000
mean    8.000000  76.400000  77.466667  84.066667
std     4.472136  12.659271  11.457167  10.924852
min     1.000000  55.000000  58.000000  66.000000
25%     4.500000  67.500000  69.500000  74.500000
50%     8.000000  78.000000  79.000000  88.000000
75%    11.500000  86.000000  86.500000  92.500000
max    15.000000  95.000000  94.000000  98.000000
๐Ÿ’ก Explanation: info() shows column names, data types and non-null counts (useful to find missing data). describe() gives count, mean, std, min, quartiles and max of numeric columns.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q25.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 25 : Information about a CSV file
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
df = pd.read_csv("student_data.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "student_data.csv" into a DataFrame (table); the result is stored in variable df
4
print("Shape (rows, columns):", df.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape (rows, columns):", then the value of df.shape on the screen
5
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
6
df.info()
๐Ÿ“ฆ Library / Data Shows columns, data types and non-null counts of df
7
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
8
print(df.describe())
๐Ÿ–ฅ๏ธ Output Displays the value of df.describe() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
df = pd.read_csv("student_data.csv")
df = DataFrame (15 rows ร— 6 columns)
34
print("Shape (rows, columns):", df.shape)
Shape (rows, columns): (15, 6)
45
print()
56
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 15 entries, 0 to 14
Data columns (total 6 columns):
 #   Column   Non-Null Count  Dtype 
---  ------   --------------  ----- 
 0   RollNo   15 non-null     int64 
 1   Name     15 non-null     object
 2   Gender   15 non-null     object
 3   Mathsโ€ฆ
67
print()
78
print(df.describe())
          RollNo      Maths    Science         AI
count  15.000000  15.000000  15.000000  15.000000
mean    8.000000  76.400000  77.466667  84.066667
std     4.472136  12.659271  11.457167  10.924852
min     1.000000  55.000000  58.000000  66.000000
25%     4.500000  67.500000  69.500000  74.5000โ€ฆ
Q26 PYTHON

Write a program to read an image and display it using Python.

# Program 26 : Read and display an image
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("flower.jpg")                  # OpenCV reads in BGR order
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # convert to RGB for display
plt.imshow(img_rgb)
plt.title("Flower Image")
plt.axis('off')
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: cv2.imread() loads an image as a NumPy array. OpenCV stores colours as BGR, so it is converted to RGB before displaying with matplotlib. (Install with: pip install opencv-python)
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules cv2, matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q26.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 26 : Read and display an image
2
import cv2
๐Ÿ“ฆ Library / Data Loads the module cv2 - OpenCV image processing
3
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
img = cv2.imread("flower.jpg")                  # OpenCV reads in BGR order
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable img
5
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # convert to RGB for display
๐Ÿ“ฆ Library / Data Converts the colour format of the image; the result is stored in variable img_rgb
6
plt.imshow(img_rgb)
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
7
plt.title("Flower Image")
๐Ÿ–ฅ๏ธ Output Writes "Flower Image" as the title of the chart
8
plt.axis('off')
๐Ÿ–ฅ๏ธ Output Sets axis options
9
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
Q27 PYTHON

Write a program to read an image and identify its shape using Python.

# Program 27 : Shape (dimensions) of an image
import cv2
img = cv2.imread("flower.jpg")
print("Shape of the image:", img.shape)
height, width, channels = img.shape
print("Height   :", height, "pixels")
print("Width    :", width, "pixels")
print("Channels :", channels, "(B, G, R)")
print("Total pixels:", height * width)
โ–ถ Sample Output
Shape of the image: (300, 400, 3)
Height   : 300 pixels
Width    : 400 pixels
Channels : 3 (B, G, R)
Total pixels: 120000
๐Ÿ’ก Explanation: img.shape returns (height, width, channels). A colour image has 3 channels (Blue, Green, Red); a grayscale image has only (height, width).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module cv2
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q27.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 27 : Shape (dimensions) of an image
2
import cv2
๐Ÿ“ฆ Library / Data Loads the module cv2 - OpenCV image processing
3
img = cv2.imread("flower.jpg")
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable img
4
print("Shape of the image:", img.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape of the image:", then the value of img.shape on the screen
5
height, width, channels = img.shape
๐Ÿงฎ Store / Calculate Stores img.shape in variables height, width, channels
6
print("Height   :", height, "pixels")
๐Ÿ–ฅ๏ธ Output Displays the text "Height :", then the value of height, then the text "pixels" on the screen
7
print("Width    :", width, "pixels")
๐Ÿ–ฅ๏ธ Output Displays the text "Width :", then the value of width, then the text "pixels" on the screen
8
print("Channels :", channels, "(B, G, R)")
๐Ÿ–ฅ๏ธ Output Displays the text "Channels :", then the value of channels, then the text "(B, G, R)" on the screen
9
print("Total pixels:", height * width)
๐Ÿ–ฅ๏ธ Output Displays the text "Total pixels:", then the value of height * width on the screen
Q28 PYTHON

Perform various tasks using OpenCV: load an image and give it a title, open it in grey scale, print its shape, display the maximum and minimum pixel values, crop a part of the image and save the image.

# Program 28 : Image tasks with OpenCV
import cv2
img = cv2.imread("flower.jpg")                          # 1. load the image
cv2.imshow("Original Image", img)                       #    window title

gray = cv2.imread("flower.jpg", cv2.IMREAD_GRAYSCALE)   # 2. grey scale
cv2.imshow("Grayscale Image", gray)

print("Image Shape:", gray.shape)                       # 3. shape
print("Minimum Pixel Value:", gray.min())               # 4. min / max
print("Maximum Pixel Value:", gray.max())

cropped = img[50:180, 120:280]                          # 5. crop rows, cols
cv2.imshow("Cropped Image", cropped)

cv2.imwrite("flower_gray.jpg", gray)                    # 6. save
print("Grayscale image saved as flower_gray.jpg")
cv2.waitKey(0)
cv2.destroyAllWindows()
โ–ถ Sample Output
Image Shape: (300, 400)
Minimum Pixel Value: 79
Maximum Pixel Value: 221
Grayscale image saved as flower_gray.jpg
Window: Original Image
Window: Original Image
Window: Grayscale Image
Window: Grayscale Image
Window: Cropped Image
Window: Cropped Image
๐Ÿ’ก Explanation: Grayscale pixels range from 0 (black) to 255 (white). Cropping uses array slicing img[row_start:row_end, col_start:col_end]. cv2.waitKey(0) keeps the windows open until a key is pressed.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module cv2
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q28.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 28 : Image tasks with OpenCV
2
import cv2
๐Ÿ“ฆ Library / Data Loads the module cv2 - OpenCV image processing
3
img = cv2.imread("flower.jpg")                          # 1. load the image
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable img
4
cv2.imshow("Original Image", img)                       #    window title
๐Ÿ–ฅ๏ธ Output Shows the image in a window
6
gray = cv2.imread("flower.jpg", cv2.IMREAD_GRAYSCALE)   # 2. grey scale
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable gray
7
cv2.imshow("Grayscale Image", gray)
๐Ÿ–ฅ๏ธ Output Shows the image in a window
9
print("Image Shape:", gray.shape)                       # 3. shape
๐Ÿ–ฅ๏ธ Output Displays the text "Image Shape:", then the value of gray.shape on the screen
10
print("Minimum Pixel Value:", gray.min())               # 4. min / max
๐Ÿ–ฅ๏ธ Output Displays the text "Minimum Pixel Value:", then the value of gray.min() on the screen
11
print("Maximum Pixel Value:", gray.max())
๐Ÿ–ฅ๏ธ Output Displays the text "Maximum Pixel Value:", then the value of gray.max() on the screen
13
cropped = img[50:180, 120:280]                          # 5. crop rows, cols
๐Ÿงฎ Store / Calculate Stores a slice img[50:180, 120:280] (part of img) in variable cropped
14
cv2.imshow("Cropped Image", cropped)
๐Ÿ–ฅ๏ธ Output Shows the image in a window
16
cv2.imwrite("flower_gray.jpg", gray)                    # 6. save
๐Ÿ“ฆ Library / Data Saves the image to file "flower_gray.jpg"
17
print("Grayscale image saved as flower_gray.jpg")
๐Ÿ–ฅ๏ธ Output Displays the text "Grayscale image saved as flower_gโ€ฆ" on the screen
18
cv2.waitKey(0)
๐Ÿ“ฆ Library / Data Waits for a key press
19
cv2.destroyAllWindows()
๐Ÿ“ฆ Library / Data Closes all image windows
Q29 PYTHON

Unit 3 - Evaluating Models: Write a program to build a confusion matrix from actual and predicted values and calculate Accuracy, Precision, Recall and F1 Score.

# Program 29 : Confusion matrix and evaluation metrics
actual    = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0]   # 1 = Yes (positive)
predicted = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]
TP = FP = TN = FN = 0
for a, p in zip(actual, predicted):
    if a == 1 and p == 1: TP += 1
    elif a == 0 and p == 1: FP += 1
    elif a == 0 and p == 0: TN += 1
    else: FN += 1
print("Confusion Matrix")
print("                 Actual Yes  Actual No")
print("Predicted Yes   ", TP, "         ", FP)
print("Predicted No    ", FN, "         ", TN)
accuracy = (TP + TN) / (TP + TN + FP + FN)
precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * precision * recall / (precision + recall)
print("Accuracy  =", round(accuracy, 3))
print("Precision =", round(precision, 3))
print("Recall    =", round(recall, 3))
print("F1 Score  =", round(f1, 3))
โ–ถ Sample Output
Confusion Matrix
                 Actual Yes  Actual No
Predicted Yes    6           2
Predicted No     2           5
Accuracy  = 0.733
Precision = 0.75
Recall    = 0.75
F1 Score  = 0.75
๐Ÿ’ก Explanation: Accuracy = (TP+TN)/Total, Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = 2PR/(P+R). F1 balances precision and recall and is preferred when classes are unequal or both errors are costly.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q29.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 29 : Confusion matrix and evaluation metrics
2
actual    = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0]   # 1 = Yes (positive)
๐Ÿงฎ Store / Calculate Stores a list [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0] in variable actual
3
predicted = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]
๐Ÿงฎ Store / Calculate Stores a list [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1] in variable predicted
4
TP = FP = TN = FN = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable TP
5
for a, p in zip(actual, predicted):
๐Ÿ” Loop LOOP that walks through actual, predicted together; a, p get one item from each
6
if a == 1 and p == 1: TP += 1
๐Ÿ”€ Decision CHECKS whether (a is equal to 1 AND p is equal to 1). If True, the indented lines below run; otherwise Python jumps to the elif/else part โ†’ here: adds 1 to TP (same as TP = TP + 1)
7
elif a == 0 and p == 1: FP += 1
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (a is equal to 0 AND p is equal to 1) โ†’ here: adds 1 to FP (same as FP = FP + 1)
8
elif a == 0 and p == 0: TN += 1
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (a is equal to 0 AND p is equal to 0) โ†’ here: adds 1 to TN (same as TN = TN + 1)
9
else: FN += 1
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False โ†’ here: adds 1 to FN (same as FN = FN + 1)
10
print("Confusion Matrix")
๐Ÿ–ฅ๏ธ Output Displays the text "Confusion Matrix" on the screen
11
print("                 Actual Yes  Actual No")
๐Ÿ–ฅ๏ธ Output Displays the text "Actual Yes Actual No" on the screen
12
print("Predicted Yes   ", TP, "         ", FP)
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted Yes", then the value of TP, then a blank, then the value of FP on the screen
13
print("Predicted No    ", FN, "         ", TN)
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted No", then the value of FN, then a blank, then the value of TN on the screen
14
accuracy = (TP + TN) / (TP + TN + FP + FN)
๐Ÿงฎ Store / Calculate Stores the value of (TP + TN) / (TP + TN + FP + FN) (calculated using รท) in variable accuracy
15
precision = TP / (TP + FP)
๐Ÿงฎ Store / Calculate Stores the value of TP / (TP + FP) (calculated using รท) in variable precision
16
recall = TP / (TP + FN)
๐Ÿงฎ Store / Calculate Stores the value of TP / (TP + FN) (calculated using รท) in variable recall
17
f1 = 2 * precision * recall / (precision + recall)
๐Ÿงฎ Store / Calculate Stores the value of 2 * precision * recall / (precision + recall) (calculated using รท) in variable f1
18
print("Accuracy  =", round(accuracy, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Accuracy =", then the value of round(accuracy, 3) on the screen
19
print("Precision =", round(precision, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Precision =", then the value of round(precision, 3) on the screen
20
print("Recall    =", round(recall, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Recall =", then the value of round(recall, 3) on the screen
21
print("F1 Score  =", round(f1, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "F1 Score =", then the value of round(f1, 3) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
actual    = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0]   # 1 = Yes (positive)
actual = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0]
23
predicted = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]
predicted = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]
34
TP = FP = TN = FN = 0
TP = 0, FP = 0, TN = 0, FN = 0
45
for a, p in zip(actual, predicted):
next item taken
a = 1, p = 1
56
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
TP = 1
65
for a, p in zip(actual, predicted):
next item taken
a = 0, p = 0
76
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
87
elif a == 0 and p == 1: FP += 1
condition is FALSE โ†’ skips this block
98
elif a == 0 and p == 0: TN += 1
condition is FALSE โ†’ skips this block
TN = 1
105
for a, p in zip(actual, predicted):
next item taken
a = 1, p = 1
116
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
TP = 2
125
for a, p in zip(actual, predicted):
next item taken
p = 0
136
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
147
elif a == 0 and p == 1: FP += 1
condition is FALSE โ†’ skips this block
158
elif a == 0 and p == 0: TN += 1
condition is FALSE โ†’ skips this block
169
else: FN += 1
FN = 1
175
for a, p in zip(actual, predicted):
next item taken
a = 0
186
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
197
elif a == 0 and p == 1: FP += 1
condition is FALSE โ†’ skips this block
208
elif a == 0 and p == 0: TN += 1
condition is FALSE โ†’ skips this block
TN = 2
215
for a, p in zip(actual, predicted):
next item taken
a = 1, p = 1
226
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
TP = 3
235
for a, p in zip(actual, predicted):
next item taken
a = 0
246
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
257
elif a == 0 and p == 1: FP += 1
condition is FALSE โ†’ skips this block
FP = 1
265
for a, p in zip(actual, predicted):
next item taken
p = 0
276
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
287
elif a == 0 and p == 1: FP += 1
condition is FALSE โ†’ skips this block
298
elif a == 0 and p == 0: TN += 1
condition is FALSE โ†’ skips this block
TN = 3
305
for a, p in zip(actual, predicted):
next item taken
a = 1, p = 1
316
if a == 1 and p == 1: TP += 1
condition is FALSE โ†’ skips this block
TP = 4
325
for a, p in zip(actual, predicted):
next item taken

โ€ฆ Python runs 32 more line-steps in the same way (loops repeat the same lines). Final values: actual = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0], predicted = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1], TP = 6, FP = 2, TN = 5, FN = 2, a = 0, p = 1, accuracy = 0.7333333333333333, precision = 0.75, recall = 0.75, f1 = 0.75

Q30 PYTHON

Unit 5 - Computer Vision: Apply the convolution operator (kernel) on an image matrix using NumPy.

# Program 30 : Convolution of an image matrix with a kernel
import numpy as np
image = np.array([[10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80]])
kernel = np.array([[-1, 0, 1],          # vertical edge detector
                   [-1, 0, 1],
                   [-1, 0, 1]])
out = np.zeros((3, 3), dtype=int)       # (5-3+1) x (5-3+1)
for i in range(3):
    for j in range(3):
        region = image[i:i+3, j:j+3]
        out[i, j] = np.sum(region * kernel)
print("Image matrix:\n", image)
print("Kernel:\n", kernel)
print("Convolved output (feature map):\n", out)
โ–ถ Sample Output
Image matrix:
 [[10 10 10 80 80]
 [10 10 10 80 80]
 [10 10 10 80 80]
 [10 10 10 80 80]
 [10 10 10 80 80]]
Kernel:
 [[-1  0  1]
 [-1  0  1]
 [-1  0  1]]
Convolved output (feature map):
 [[  0 210 210]
 [  0 210 210]
 [  0 210 210]]
๐Ÿ’ก Explanation: The kernel slides over the image; at each position the overlapping values are multiplied and added. Large values appear only where pixel values change sharply - that is the vertical EDGE. CNNs learn such kernels automatically.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q30.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 30 : Convolution of an image matrix with a kernel
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
image = np.array([[10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80],
                  [10, 10, 10, 80, 80โ€ฆ
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[10, 10, 10, 80, 80], [10, 10, 10, 80, 80], โ€ฆ; the result is stored in variable image
8
kernel = np.array([[-1, 0, 1],          # vertical edge detector
                   [-1, 0, 1],
                   [-1, 0, 1]])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[-1, 0, 1], # vertical edge detector [-1, 0,โ€ฆ; the result is stored in variable kernel
11
out = np.zeros((3, 3), dtype=int)       # (5-3+1) x (5-3+1)
๐Ÿ“ฆ Library / Data Makes a NumPy array filled with 0s; the result is stored in variable out
12
for i in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, i takes that value and the indented block runs once
13
for j in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, j takes that value and the indented block runs once
14
region = image[i:i+3, j:j+3]
๐Ÿงฎ Store / Calculate Stores a slice image[i:i+3, j:j+3] (part of image) in variable region
15
out[i, j] = np.sum(region * kernel)
๐Ÿ“ฆ Library / Data Adds up the values of np (along axis region * kernel); the result is put into out[i, j] (item i, j of out)
16
print("Image matrix:\n", image)
๐Ÿ–ฅ๏ธ Output Displays the text "Image matrix:", then the value of image on the screen
17
print("Kernel:\n", kernel)
๐Ÿ–ฅ๏ธ Output Displays the text "Kernel:", then the value of kernel on the screen
18
print("Convolved output (feature map):\n", out)
๐Ÿ–ฅ๏ธ Output Displays the text "Convolved output (feature map):", then the value of out on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
image = np.array([[10, 10, 10, 80, 80],
34
[10, 10, 10, 80, 80],
45
[10, 10, 10, 80, 80],
56
[10, 10, 10, 80, 80],
67
[10, 10, 10, 80, 80]])
73
image = np.array([[10, 10, 10, 80, 80],
image = array of shape (5, 5)
88
kernel = np.array([[-1, 0, 1],          # vertical edge detector
99
[-1, 0, 1],
1010
[-1, 0, 1]])
118
kernel = np.array([[-1, 0, 1],          # vertical edge detector
kernel = array of shape (3, 3)
1211
out = np.zeros((3, 3), dtype=int)       # (5-3+1) x (5-3+1)
out = array of shape (3, 3)
1312
for i in range(3):
next item taken
i = 0
1413
for j in range(3):
next item taken
j = 0
1514
region = image[i:i+3, j:j+3]
region = array of shape (3, 3)
1615
out[i, j] = np.sum(region * kernel)
1713
for j in range(3):
next item taken
j = 1
1814
region = image[i:i+3, j:j+3]
1915
out[i, j] = np.sum(region * kernel)
2013
for j in range(3):
next item taken
j = 2
2114
region = image[i:i+3, j:j+3]
2215
out[i, j] = np.sum(region * kernel)
2313
for j in range(3):
no items left โ†’ loop ends
2412
for i in range(3):
next item taken
i = 1
2513
for j in range(3):
next item taken
j = 0
2614
region = image[i:i+3, j:j+3]
2715
out[i, j] = np.sum(region * kernel)
2813
for j in range(3):
next item taken
j = 1
2914
region = image[i:i+3, j:j+3]
3015
out[i, j] = np.sum(region * kernel)
3113
for j in range(3):
next item taken
j = 2
3214
region = image[i:i+3, j:j+3]

โ€ฆ Python runs 17 more line-steps in the same way (loops repeat the same lines). Final values: image = array of shape (5, 5), kernel = array of shape (3, 3), out = array of shape (3, 3), i = 2, j = 2, region = array of shape (3, 3)

Q31 PYTHON

Unit 6 - NLP: Perform text normalisation (tokenisation, lowercase, stop-word removal) and create a Bag of Words and TF-IDF for three documents.

# Program 31 : Text normalisation, Bag of Words and TF-IDF
import math
docs = ["Aman and Anil are stressed",
        "Aman went to a therapist",
        "Anil went to download a health chatbot"]
stop_words = {"and", "are", "to", "a"}

# Text normalisation
tokens = []
for d in docs:
    words = [w.lower() for w in d.split() if w.lower() not in stop_words]
    tokens.append(words)
    print("Tokens:", words)

# Dictionary (unique words)
vocab = sorted(set(w for t in tokens for w in t))
print("\nDictionary:", vocab)

# Bag of Words (document vectors)
print("\nBag of Words")
for i, t in enumerate(tokens):
    print("Doc", i + 1, [t.count(w) for w in vocab])

# TF-IDF = TF x log10(N / DF)
N = len(tokens)
print("\nTF-IDF of Doc 1")
for w in vocab:
    df = sum(1 for t in tokens if w in t)
    tfidf = tokens[0].count(w) * math.log10(N / df)
    if tokens[0].count(w):
        print(f"{w:<10} {tfidf:.3f}")
โ–ถ Sample Output
Tokens: ['aman', 'anil', 'stressed']
Tokens: ['aman', 'went', 'therapist']
Tokens: ['anil', 'went', 'download', 'health', 'chatbot']

Dictionary: ['aman', 'anil', 'chatbot', 'download', 'health', 'stressed', 'therapist', 'went']

Bag of Words
Doc 1 [1, 1, 0, 0, 0, 1, 0, 0]
Doc 2 [1, 0, 0, 0, 0, 0, 1, 1]
Doc 3 [0, 1, 1, 1, 1, 0, 0, 1]

TF-IDF of Doc 1
aman       0.176
anil       0.176
stressed   0.477
๐Ÿ’ก Explanation: Bag of Words counts how often each dictionary word occurs in each document. TF-IDF lowers the weight of words found in many documents (like 'aman', 'anil') and raises rare, meaningful words (like 'stressed').
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else; module math
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as x_ai_q31.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Program 31 : Text normalisation, Bag of Words and TF-IDF
2
import math
๐Ÿ“ฆ Library / Data Loads the module math - mathematical functions (sqrt, pi, factorial โ€ฆ)
3
docs = ["Aman and Anil are stressed",
        "Aman went to a therapist",
        "Anil went to download a health chatbot"]
๐Ÿงฎ Store / Calculate Stores a list ["Aman and Anil are stressed", "Aman went to โ€ฆ in variable docs
6
stop_words = {"and", "are", "to", "a"}
๐Ÿงฎ Store / Calculate Stores the set {"and", "are", "to", "a"} in variable stop_words
๐Ÿ“Œ Text normalisation
9
tokens = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable tokens
10
for d in docs:
๐Ÿ” Loop LOOP: takes each item of docs one-by-one into d and runs the indented block for it
11
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [w.lower() for w in d.split() if w.lower() noโ€ฆ in variable words
12
tokens.append(words)
๐Ÿงฎ Store / Calculate Adds words at the end of list tokens
13
print("Tokens:", words)
๐Ÿ–ฅ๏ธ Output Displays the text "Tokens:", then the value of words on the screen
๐Ÿ“Œ Dictionary (unique words)
16
vocab = sorted(set(w for t in tokens for w in t))
๐Ÿงฎ Store / Calculate Makes a new sorted list from set(w for t in tokens for w in t); the result is stored in variable vocab
17
print("\nDictionary:", vocab)
๐Ÿ–ฅ๏ธ Output Displays the text "Dictionary:", then the value of vocab on the screen
๐Ÿ“Œ Bag of Words (document vectors)
20
print("\nBag of Words")
๐Ÿ–ฅ๏ธ Output Displays the text "Bag of Words" on the screen
21
for i, t in enumerate(tokens):
๐Ÿ” Loop LOOP over tokens with position: in each round i, t get (position, item)
22
print("Doc", i + 1, [t.count(w) for w in vocab])
๐Ÿ–ฅ๏ธ Output Displays the text "Doc", then the value of i + 1, then the value of [t.count(w) for w in vocab] on the screen
๐Ÿ“Œ TF-IDF = TF x log10(N / DF)
25
N = len(tokens)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in tokens; the result is stored in variable N
26
print("\nTF-IDF of Doc 1")
๐Ÿ–ฅ๏ธ Output Displays the text "TF-IDF of Doc 1" on the screen
27
for w in vocab:
๐Ÿ” Loop LOOP: takes each item of vocab one-by-one into w and runs the indented block for it
28
df = sum(1 for t in tokens if w in t)
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for t in tokens if w in t); the result is stored in variable df
29
tfidf = tokens[0].count(w) * math.log10(N / df)
๐Ÿงฎ Store / Calculate Stores the value of tokens[0].count(w) * math.log10(N / df) (calculated using ร—) in variable tfidf
30
if tokens[0].count(w):
๐Ÿ”€ Decision CHECKS whether tokens[0].count(w) is True. If True, the indented lines below run; otherwise they are skipped
31
print(f"{w:<10} {tfidf:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{w:<10} {tfidf:.3f}" with the values filled into { } on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import math
23
docs = ["Aman and Anil are stressed",
docs = ['Aman and Anil are stressed', 'Aman went to a therapist', 'Anil weโ€ฆ
36
stop_words = {"and", "are", "to", "a"}
stop_words = {'and', 'a', 'to', 'are'}
49
tokens = []
tokens = []
510
for d in docs:
next item taken
d = 'Aman and Anil are stressed'
611
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
711
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
811
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
911
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1011
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1111
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
words = ['aman', 'anil', 'stressed']
1212
tokens.append(words)
tokens = [['aman', 'anil', 'stressed']]
1313
print("Tokens:", words)
Tokens: ['aman', 'anil', 'stressed']
1410
for d in docs:
next item taken
d = 'Aman went to a therapist'
1511
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1611
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1711
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1811
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
1911
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2011
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
words = ['aman', 'went', 'therapist']
2112
tokens.append(words)
tokens = [['aman', 'anil', 'stressed'], ['aman', 'went', 'therapist']]
2213
print("Tokens:", words)
Tokens: ['aman', 'went', 'therapist']
2310
for d in docs:
next item taken
d = 'Anil went to download a health chatbot'
2411
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2511
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2611
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2711
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2811
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
2911
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
3011
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
3111
words = [w.lower() for w in d.split() if w.lower() not in stop_words]
words = ['anil', 'went', 'download', 'health', 'chatbot']
3212
tokens.append(words)
tokens = [['aman', 'anil', 'stressed'], ['aman', 'went', 'therapist'], ['aniโ€ฆ

โ€ฆ Python runs 121 more line-steps in the same way (loops repeat the same lines). Final values: docs = ['Aman and Anil are stressed', 'Aman went to a therapist', 'Anil weโ€ฆ, stop_words = {'and', 'a', 'to', 'are'}, tokens = [['aman', 'anil', 'stressed'], ['aman', 'went', 'therapist'], ['aniโ€ฆ, d = 'Anil went to download a health chatbot', words = ['anil', 'went', 'download', 'health', 'chatbot'], vocab = ['aman', 'anil', 'chatbot', 'download', 'health', 'stressed', 'therโ€ฆ, t = ['anil', 'went', 'download', 'health', 'chatbot'], w = 'went', i = 2, N = 3, df = 2, tfidf = 0.0

Q32 ACTIVITY

ACTIVITY (Unit 5): Visit an RGB colour tool (https://www.w3schools.com/colors/colors_rgb.asp) and answer the colour-mixing questions.

QUESTION                                            ANSWER
1. Output colour when R = G = B = 255 ?            White
2. Output colour when R = G = 255, B = 0 ?          Yellow
3. Output colour when R = 255, G = 0, B = 255 ?     Magenta (pink-purple)
4. Output colour when R = 0, G = 255, B = 255 ?     Cyan
5. Output colour when R = G = B = 0 ?               Black
6. Output colour when R = 0, G = 0, B = 255 ?       Blue
7. Output colour when R = 255, G = 0, B = 0 ?       Red
8. Output colour when R = 0, G = 255, B = 0 ?       Green
9. Output colour when R = G = B = 128 ?             Grey
โ–ถ Conclusion
Learning: a colour image is three 2D matrices (R, G, B) stacked together;
0 means no light and 255 means full intensity of that colour.
๐Ÿ’ก Explanation: Every pixel of a colour image has 3 values (Red, Green, Blue), each from 0 to 255. Equal values of R, G and B give shades of grey. This is how computers 'see' colour.
Q33 ACTIVITY

ACTIVITY (Unit 5): Create your own pixel art / animated GIF using Piskel (www.piskelapp.com).

STEPS
1. Open https://www.piskelapp.com and click "Create Sprite".
2. Set canvas size (Resize) to 32 x 32 pixels.
3. Use the Pen, Fill and Eraser tools to draw the first frame
   (e.g. a smiling face / a walking stick-man).
4. Click "+ Add new frame" (or duplicate the frame) and change a few pixels
   to show movement.
5. Repeat for 4-6 frames; set FPS (speed) using the preview slider.
6. Preview the animation in the top-right window.
7. Export -> GIF -> Download.  Paste a screenshot / print in the file.
โ–ถ Result
Output: an animated GIF (32 x 32 pixels, 6 frames) of a waving stick-man.
๐Ÿ’ก Explanation: Pixel art shows that an image is a grid of small squares (pixels), each with its own colour value. Resolution = number of pixels in width x height.
Q34 ACTIVITY

ACTIVITY (Unit 4/5/6 - No-Code AI): Build a classification model with Teachable Machine / Orange Data Mining (e.g. Smart Sorter - recyclable vs non-recyclable) and record the steps.

TEACHABLE MACHINE  (https://teachablemachine.withgoogle.com)
1. Get Started -> Image Project -> Standard image model.
2. Rename Class 1 = "Recyclable" and Class 2 = "Non-Recyclable".
3. Add 40-60 webcam/uploaded images per class (bottles, paper, cans /
   food waste, wrappers, thermocol) from different angles and lighting.
4. Click "Train Model" (keep default epochs = 50).
5. Test with new objects in the Preview panel and note the confidence %.
6. Export Model -> Upload (shareable link) or Download.

ORANGE DATA MINING (statistical data)
File (penguins / iris) -> Data Table -> Scatter Plot -> Test & Score
(Tree, kNN, Logistic Regression) -> Confusion Matrix.
โ–ถ Sample Observation
Model accuracy on 10 new test items: 9 correct (90 %).
Mistake: a crushed plastic cup was classified as Non-Recyclable - add more such images.
๐Ÿ’ก Explanation: No-code tools let us follow the full AI project cycle (data acquisition, modeling, evaluation, deployment) without writing code. More varied images give a more accurate model.

๐Ÿ“ Project Work Reference (CBSE 417)

PROJECT WORK / FIELD VISIT / STUDENT PORTFOLIO  (10 marks + 5 marks viva, relate it to SDGs)
Any ONE activity to be done.

Sample Projects - AI project development using:
  1. Statistical Data for AI : Prediction of Palmer Penguin species
  2. Computer Vision          : Early detection of coral bleaching
  3. Natural Language Proc.   : Sentiment analysis
  (All three are given as complete Python projects in the Live Projects section; CBSE also
   walks through them in the no-code Orange Data Mining tool.)

Field Work - participation in: AI for Youth Bootcamp, AI Fests / Exhibitions, any AI training
sessions, virtual tours of companies using AI.

Student Portfolio (continued from Class IX) - record of all AI activities, hackathons,
competitions (CBSE / inter-school). Minimum 5 activities.

๐Ÿ“Š Class XI โ€” Artificial Intelligence (843)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 34 Practicals (21 Python programs + 13 activities) as per CBSE curriculum 2026-27

๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

๐Ÿ“‘ CBSE Practical Assessment Scheme โ€” Class XI AI (843)

ComponentMarks
IBM SkillsBuild Certification / any other industry certification5
Capstone Project12
Bootcamps / Internship / other startups7
Practical File10
Lab Test / Written Exam (based on practical file)10
Viva Voce (based on practical file and project)6
TOTAL (Practical)50

Theory 50 + Practical 50 = 100. Every Python program below was run and its real output is shown; activities give the procedure and a model answer for the practical file.

Q1 THEORY / VIVA

Unit 1: Categorize the given applications into the three domains of AI - Data Statistics, Computer Vision and Natural Language Processing.

+----+-------------------------------------------+---------------------------+
| No | Application                               | Domain of AI              |
+----+-------------------------------------------+---------------------------+
|  1 | Face Lock / Face unlock in smartphones    | Computer Vision (CV)      |
|  2 | Google Translate / Bhashini               | Natural Language Proc.    |
|  3 | Netflix / YouTube recommendations         | Data Statistics (Data)    |
|  4 | Self-driving car detecting pedestrians    | Computer Vision (CV)      |
|  5 | Alexa / Siri / Google Assistant           | NLP (speech + language)   |
|  6 | Weather / rainfall forecasting            | Data Statistics (Data)    |
|  7 | Email spam filter                         | NLP                       |
|  8 | Medical X-ray / MRI analysis              | Computer Vision (CV)      |
|  9 | Online fraud detection in UPI payments    | Data Statistics (Data)    |
| 10 | Chatbots on websites (e.g. IRCTC AskDisha)| NLP                       |
| 11 | Google Lens - search by image             | Computer Vision (CV)      |
| 12 | Price prediction of flight tickets        | Data Statistics (Data)    |
+----+-------------------------------------------+---------------------------+

Machine Learning example      : Spam filter learns from labelled emails.
Reinforcement Learning example: A robot / game agent learns by reward and penalty
                                (e.g. AlphaGo, self-learning chess engines).
โ–ถ Result
Domain-wise count: Computer Vision = 4, NLP = 4, Data Statistics = 4
๐Ÿ’ก Explanation: Data domain works with numbers and tables, CV with images and videos, and NLP with human language (text and speech). Some applications use more than one domain (e.g. a voice assistant uses speech recognition + NLP).
Q2 THEORY / VIVA

Unit 2: Identify ten companies currently hiring employees for specific AI positions.

HOW TO DO IT : Search job portals (LinkedIn, Naukri, Indeed, company career pages,
               NCS portal) with keywords "AI Engineer", "Data Scientist", "ML Engineer".
               Record the company, job role and city. (Sample record below -
               update it with the openings you actually find on the date of search.)

+----+---------------------------+--------------------------------+-------------+
| No | Company                   | AI Position                    | Location    |
+----+---------------------------+--------------------------------+-------------+
|  1 | Tata Consultancy Services | AI/ML Engineer                 | Pune        |
|  2 | Infosys                   | Data Scientist                 | Bengaluru   |
|  3 | Wipro                     | Generative AI Developer        | Hyderabad   |
|  4 | IBM India                 | AI Solutions Consultant        | Bengaluru   |
|  5 | Google India              | Machine Learning Engineer      | Bengaluru   |
|  6 | Microsoft India (IDC)     | Applied Scientist              | Hyderabad   |
|  7 | Amazon India              | Computer Vision Scientist      | Chennai     |
|  8 | Flipkart                  | Data Analyst - ML              | Bengaluru   |
|  9 | Accenture                 | NLP Engineer                   | Gurugram    |
| 10 | HCLTech                   | AI Ethics & Governance Analyst | Noida       |
+----+---------------------------+--------------------------------+-------------+
โ–ถ Observation
Observation: Most openings ask for Python, statistics and ML basics; Bengaluru and
Hyderabad have the maximum AI openings.
๐Ÿ’ก Explanation: AI jobs exist in IT services, product companies, e-commerce, healthcare, banking and government. Common roles: Data Scientist, ML Engineer, AI Research Scientist, Data Analyst, Computer Vision Engineer, NLP Engineer, Prompt Engineer, AI Ethicist.
Q3 THEORY / VIVA

Unit 2: Note down the technical skills and soft skills listed by any two companies for a specific AI position.

POSITION : Machine Learning / AI Engineer   (sample from two job descriptions)

                    COMPANY A (IT Services)          COMPANY B (Product / E-commerce)
TECHNICAL SKILLS    - Python, NumPy, Pandas            - Python, SQL
                    - Scikit-learn, TensorFlow         - Deep learning (PyTorch/TensorFlow)
                    - Statistics & Linear Algebra      - NLP / Computer Vision models
                    - Cloud (AWS / Azure / GCP)        - Data visualisation (Power BI)
                    - Git, REST APIs                   - MLOps, model deployment

SOFT SKILLS         - Communication & presentation     - Problem solving
                    - Team work                        - Critical thinking
                    - Time management                  - Curiosity / continuous learning
                    - Client handling                  - Ethical judgement

COMMON SKILLS : Python, Machine Learning, Statistics, Problem solving, Communication
โ–ถ Conclusion
My skill-gap plan: learn Pandas & Scikit-learn this year, complete an IBM SkillsBuild
course, and practise presenting projects to improve communication.
๐Ÿ’ก Explanation: Employers look for a mix of technical skills (programming, maths, ML tools) and soft skills (communication, teamwork, ethics). This activity helps students plan a learning path for an AI career.
Q4 PYTHON

Python Level 1: Write a program to input a number and check whether it is positive, negative or zero, and also whether it is even or odd (operators and if-elif-else).

# Level 1 - Program 1 : operators and conditional statements
n = int(input("Enter an integer: "))
if n > 0:
    sign = "Positive"
elif n < 0:
    sign = "Negative"
else:
    sign = "Zero"
parity = "Even" if n % 2 == 0 else "Odd"
print("Number      :", n)
print("Sign        :", sign)
print("Even / Odd  :", parity)
print("Square      :", n ** 2)
print("n // 3, n % 3 :", n // 3, ",", n % 3)
โ–ถ Sample Output
Enter an integer: -14
Number      : -14
Sign        : Negative
Even / Odd  : Even
Square      : 196
n // 3, n % 3 : -5 , 1
๐Ÿ’ก Explanation: Uses relational operators (>, <), arithmetic operators (**, //, %) and a conditional (ternary) expression. // gives the quotient and % gives the remainder.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type -14 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 1 - Program 1 : operators and conditional statements
2
n = int(input("Enter an integer: "))
โŒจ๏ธ Input Shows "Enter an integer: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
3
if n > 0:
๐Ÿ”€ Decision CHECKS whether n is greater than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
4
sign = "Positive"
๐Ÿงฎ Store / Calculate Stores the text "Positive" in variable sign
5
elif n < 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether n is less than 0
6
sign = "Negative"
๐Ÿงฎ Store / Calculate Stores the text "Negative" in variable sign
7
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
8
sign = "Zero"
๐Ÿงฎ Store / Calculate Stores the text "Zero" in variable sign
9
parity = "Even" if n % 2 == 0 else "Odd"
๐Ÿงฎ Store / Calculate Stores either "Even" or "Odd" depending on n % 2 == 0 in variable parity
10
print("Number      :", n)
๐Ÿ–ฅ๏ธ Output Displays the text "Number :", then the value of n on the screen
11
print("Sign        :", sign)
๐Ÿ–ฅ๏ธ Output Displays the text "Sign :", then the value of sign on the screen
12
print("Even / Odd  :", parity)
๐Ÿ–ฅ๏ธ Output Displays the text "Even / Odd :", then the value of parity on the screen
13
print("Square      :", n ** 2)
๐Ÿ–ฅ๏ธ Output Displays the text "Square :", then the value of n ** 2 on the screen
14
print("n // 3, n % 3 :", n // 3, ",", n % 3)
๐Ÿ–ฅ๏ธ Output Displays the text "n // 3, n % 3 :", then the value of n // 3, then the text ",", then the value of n % 3 on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
n = int(input("Enter an integer: "))
n = -14
Enter an integer: -14
23
if n > 0:
condition is FALSE โ†’ skips this block
35
elif n < 0:
condition is TRUE โ†’ enters the block
46
sign = "Negative"
sign = 'Negative'
59
parity = "Even" if n % 2 == 0 else "Odd"
parity = 'Even'
610
print("Number      :", n)
Number      : -14
711
print("Sign        :", sign)
Sign        : Negative
812
print("Even / Odd  :", parity)
Even / Odd  : Even
913
print("Square      :", n ** 2)
Square      : 196
1014
print("n // 3, n % 3 :", n // 3, ",", n % 3)
n // 3, n % 3 : -5 , 1
Q5 PYTHON

Python Level 1: Write a program to input marks of 5 subjects and display total, percentage and grade.

# Level 1 - Program 2 : data types, input and if-elif ladder
name = input("Enter student name: ")
total = 0
for i in range(1, 6):
    m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
    total += m
percent = total / 5
if percent >= 90:   grade = 'A'
elif percent >= 75: grade = 'B'
elif percent >= 60: grade = 'C'
elif percent >= 33: grade = 'D'
else:               grade = 'E'
print("\nName       :", name)
print("Total      :", total, "/ 500")
print("Percentage :", round(percent, 2), "%")
print("Grade      :", grade)
โ–ถ Sample Output
Enter student name: Ishaan
Enter marks of subject 1 (out of 100): 88
Enter marks of subject 2 (out of 100): 92
Enter marks of subject 3 (out of 100): 79
Enter marks of subject 4 (out of 100): 95
Enter marks of subject 5 (out of 100): 84

Name       : Ishaan
Total      : 438.0 / 500
Percentage : 87.6 %
Grade      : B
๐Ÿ’ก Explanation: str(i) converts the integer to a string so it can be joined with '+'. The if-elif ladder tests the percentage against grade boundaries from highest to lowest.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 2 values from the keyboard โ†’ name, m
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type Ishaan, 88, 92, 79, 95, 84 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 1 - Program 2 : data types, input and if-elif ladder
2
name = input("Enter student name: ")
โŒจ๏ธ Input Shows the message "Enter student name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
3
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
4
for i in range(1, 6):
๐Ÿ” Loop LOOP: gives the numbers 1 to 5; for each number, i takes that value and the indented block runs once
5
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
โŒจ๏ธ Input Shows "Enter marks of subject " + str(i) + " (out of 100): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable m
6
total += m
๐Ÿงฎ Store / Calculate Adds m to total (same as total = total + m)
7
percent = total / 5
๐Ÿงฎ Store / Calculate Stores the value of total / 5 (calculated using รท) in variable percent
8
if percent >= 90:   grade = 'A'
๐Ÿ”€ Decision CHECKS whether percent is greater than or equal to 90. If True, the indented lines below run; otherwise Python jumps to the elif/else part โ†’ here: stores the text 'A' in variable grade
9
elif percent >= 75: grade = 'B'
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether percent is greater than or equal to 75 โ†’ here: stores the text 'B' in variable grade
10
elif percent >= 60: grade = 'C'
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether percent is greater than or equal to 60 โ†’ here: stores the text 'C' in variable grade
11
elif percent >= 33: grade = 'D'
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether percent is greater than or equal to 33 โ†’ here: stores the text 'D' in variable grade
12
else:               grade = 'E'
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False โ†’ here: stores the text 'E' in variable grade
13
print("\nName       :", name)
๐Ÿ–ฅ๏ธ Output Displays the text "Name :", then the value of name on the screen
14
print("Total      :", total, "/ 500")
๐Ÿ–ฅ๏ธ Output Displays the text "Total :", then the value of total, then the text "/ 500" on the screen
15
print("Percentage :", round(percent, 2), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Percentage :", then the value of round(percent, 2), then the text "%" on the screen
16
print("Grade      :", grade)
๐Ÿ–ฅ๏ธ Output Displays the text "Grade :", then the value of grade on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
name = input("Enter student name: ")
name = 'Ishaan'
Enter student name: Ishaan
23
total = 0
total = 0
34
for i in range(1, 6):
next item taken
i = 1
45
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
m = 88.0
Enter marks of subject 1 (out of 100): 88
56
total += m
total = 88.0
64
for i in range(1, 6):
next item taken
i = 2
75
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
m = 92.0
Enter marks of subject 2 (out of 100): 92
86
total += m
total = 180.0
94
for i in range(1, 6):
next item taken
i = 3
105
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
m = 79.0
Enter marks of subject 3 (out of 100): 79
116
total += m
total = 259.0
124
for i in range(1, 6):
next item taken
i = 4
135
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
m = 95.0
Enter marks of subject 4 (out of 100): 95
146
total += m
total = 354.0
154
for i in range(1, 6):
next item taken
i = 5
165
m = float(input("Enter marks of subject " + str(i) + " (out of 100): "))
m = 84.0
Enter marks of subject 5 (out of 100): 84
176
total += m
total = 438.0
184
for i in range(1, 6):
no items left โ†’ loop ends
197
percent = total / 5
percent = 87.6
208
if percent >= 90:   grade = 'A'
condition is FALSE โ†’ skips this block
219
elif percent >= 75: grade = 'B'
condition is FALSE โ†’ skips this block
grade = 'B'
2213
print("\nName       :", name)
Name       : Ishaan
2314
print("Total      :", total, "/ 500")
Total      : 438.0 / 500
2415
print("Percentage :", round(percent, 2), "%")
Percentage : 87.6 %
2516
print("Grade      :", grade)
Grade      : B
Q6 PYTHON

Python Level 1: Write a program to find the sum of digits and the reverse of a number and check whether it is a palindrome (while loop).

# Level 1 - Program 3 : while loop
num = int(input("Enter a number: "))
temp = num
total = 0
rev = 0
while temp > 0:
    digit = temp % 10
    total += digit
    rev = rev * 10 + digit
    temp //= 10
print("Sum of digits :", total)
print("Reverse       :", rev)
if rev == num:
    print(num, "is a Palindrome")
else:
    print(num, "is not a Palindrome")
โ–ถ Sample Output
Enter a number: 12321
Sum of digits : 9
Reverse       : 12321
12321 is a Palindrome
๐Ÿ’ก Explanation: % 10 extracts the last digit and // 10 removes it. The loop continues until no digits are left.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ num
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 12321 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 1 - Program 3 : while loop
2
num = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable num
3
temp = num
๐Ÿงฎ Store / Calculate Stores the value of num in variable temp
4
total = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable total
5
rev = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable rev
6
while temp > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as temp is greater than 0; checks the condition before every round
7
digit = temp % 10
๐Ÿงฎ Store / Calculate Stores the value of temp % 10 (calculated using % (remainder)) in variable digit
8
total += digit
๐Ÿงฎ Store / Calculate Adds digit to total (same as total = total + digit)
9
rev = rev * 10 + digit
๐Ÿงฎ Store / Calculate Stores the value of rev * 10 + digit (calculated using +) in variable rev
10
temp //= 10
๐Ÿงฎ Store / Calculate Updates temp using temp //= 10
11
print("Sum of digits :", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum of digits :", then the value of total on the screen
12
print("Reverse       :", rev)
๐Ÿ–ฅ๏ธ Output Displays the text "Reverse :", then the value of rev on the screen
13
if rev == num:
๐Ÿ”€ Decision CHECKS whether rev is equal to num. If True, the indented lines below run; otherwise Python jumps to the elif/else part
14
print(num, "is a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of num, then the text "is a Palindrome" on the screen
15
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
16
print(num, "is not a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the value of num, then the text "is not a Palindrome" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
num = int(input("Enter a number: "))
num = 12321
Enter a number: 12321
23
temp = num
temp = 12321
34
total = 0
total = 0
45
rev = 0
rev = 0
56
while temp > 0:
condition is TRUE โ†’ enters the block
67
digit = temp % 10
digit = 1
78
total += digit
total = 1
89
rev = rev * 10 + digit
rev = 1
910
temp //= 10
temp = 1232
106
while temp > 0:
condition is TRUE โ†’ enters the block
117
digit = temp % 10
digit = 2
128
total += digit
total = 3
139
rev = rev * 10 + digit
rev = 12
1410
temp //= 10
temp = 123
156
while temp > 0:
condition is TRUE โ†’ enters the block
167
digit = temp % 10
digit = 3
178
total += digit
total = 6
189
rev = rev * 10 + digit
rev = 123
1910
temp //= 10
temp = 12
206
while temp > 0:
condition is TRUE โ†’ enters the block
217
digit = temp % 10
digit = 2
228
total += digit
total = 8
239
rev = rev * 10 + digit
rev = 1232
2410
temp //= 10
temp = 1
256
while temp > 0:
condition is TRUE โ†’ enters the block
267
digit = temp % 10
digit = 1
278
total += digit
total = 9
289
rev = rev * 10 + digit
rev = 12321
2910
temp //= 10
temp = 0
306
while temp > 0:
condition is FALSE โ†’ loop ends
3111
print("Sum of digits :", total)
Sum of digits : 9
3212
print("Reverse       :", rev)
Reverse       : 12321

โ€ฆ Python runs 2 more line-steps in the same way (loops repeat the same lines). Final values: num = 12321, temp = 0, total = 9, rev = 12321, digit = 1

Q7 PYTHON

Python Level 1: Write a program to print the multiplication table of a number and find its factorial (for loop).

# Level 1 - Program 4 : for loop with range()
n = int(input("Enter a number: "))
print("Multiplication table of", n)
for i in range(1, 11):
    print(f"{n} x {i:2} = {n * i}")
fact = 1
for i in range(1, n + 1):
    fact *= i
print("Factorial of", n, "=", fact)
โ–ถ Sample Output
Enter a number: 6
Multiplication table of 6
6 x  1 = 6
6 x  2 = 12
6 x  3 = 18
6 x  4 = 24
6 x  5 = 30
6 x  6 = 36
6 x  7 = 42
6 x  8 = 48
6 x  9 = 54
6 x 10 = 60
Factorial of 6 = 720
๐Ÿ’ก Explanation: f-strings format output neatly ({i:2} reserves 2 places). Factorial n! = 1 x 2 x ... x n, found using an accumulator that starts at 1.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ n
โžœ
โ‘ก PROCESSuses a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 6 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 1 - Program 4 : for loop with range()
2
n = int(input("Enter a number: "))
โŒจ๏ธ Input Shows "Enter a number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
3
print("Multiplication table of", n)
๐Ÿ–ฅ๏ธ Output Displays the text "Multiplication table of", then the value of n on the screen
4
for i in range(1, 11):
๐Ÿ” Loop LOOP: gives the numbers 1 to 10; for each number, i takes that value and the indented block runs once
5
print(f"{n} x {i:2} = {n * i}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} x {i:2} = {n * i}" with the values filled into { } on the screen
6
fact = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable fact
7
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
8
fact *= i
๐Ÿงฎ Store / Calculate Multiplies fact by i (same as fact = fact ร— i)
9
print("Factorial of", n, "=", fact)
๐Ÿ–ฅ๏ธ Output Displays the text "Factorial of", then the value of n, then the text "=", then the value of fact on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
n = int(input("Enter a number: "))
n = 6
Enter a number: 6
23
print("Multiplication table of", n)
Multiplication table of 6
34
for i in range(1, 11):
next item taken
i = 1
45
print(f"{n} x {i:2} = {n * i}")
6 x  1 = 6
54
for i in range(1, 11):
next item taken
i = 2
65
print(f"{n} x {i:2} = {n * i}")
6 x  2 = 12
74
for i in range(1, 11):
next item taken
i = 3
85
print(f"{n} x {i:2} = {n * i}")
6 x  3 = 18
94
for i in range(1, 11):
next item taken
i = 4
105
print(f"{n} x {i:2} = {n * i}")
6 x  4 = 24
114
for i in range(1, 11):
next item taken
i = 5
125
print(f"{n} x {i:2} = {n * i}")
6 x  5 = 30
134
for i in range(1, 11):
next item taken
i = 6
145
print(f"{n} x {i:2} = {n * i}")
6 x  6 = 36
154
for i in range(1, 11):
next item taken
i = 7
165
print(f"{n} x {i:2} = {n * i}")
6 x  7 = 42
174
for i in range(1, 11):
next item taken
i = 8
185
print(f"{n} x {i:2} = {n * i}")
6 x  8 = 48
194
for i in range(1, 11):
next item taken
i = 9
205
print(f"{n} x {i:2} = {n * i}")
6 x  9 = 54
214
for i in range(1, 11):
next item taken
i = 10
225
print(f"{n} x {i:2} = {n * i}")
6 x 10 = 60
234
for i in range(1, 11):
no items left โ†’ loop ends
246
fact = 1
fact = 1
257
for i in range(1, n + 1):
next item taken
i = 1
268
fact *= i
277
for i in range(1, n + 1):
next item taken
i = 2
288
fact *= i
fact = 2
297
for i in range(1, n + 1):
next item taken
i = 3
308
fact *= i
fact = 6
317
for i in range(1, n + 1):
next item taken
i = 4
328
fact *= i
fact = 24

โ€ฆ Python runs 6 more line-steps in the same way (loops repeat the same lines). Final values: n = 6, i = 6, fact = 720

Q8 PYTHON

Python Level 1: Write a program to print all prime numbers between two numbers and the first n terms of the Fibonacci series (nested loops).

# Level 1 - Program 5 : nested loops, break
low = int(input("Enter lower limit: "))
high = int(input("Enter upper limit: "))
print("Prime numbers:", end=" ")
for num in range(max(2, low), high + 1):
    for d in range(2, int(num ** 0.5) + 1):
        if num % d == 0:
            break
    else:
        print(num, end=" ")
print()
n = int(input("How many Fibonacci terms? "))
a, b = 0, 1
print("Fibonacci:", end=" ")
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
print()
โ–ถ Sample Output
Enter lower limit: 10
Enter upper limit: 50
Prime numbers: 11 13 17 19 23 29 31 37 41 43 47 
How many Fibonacci terms? 10
Fibonacci: 0 1 1 2 3 5 8 13 21 34
๐Ÿ’ก Explanation: The else attached to a for loop runs only when the loop ends without break - i.e. no divisor was found, so the number is prime. Checking divisors up to the square root is enough.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 3 values from the keyboard โ†’ low, high, n
โžœ
โ‘ก PROCESSuses a for loop; decisions with if / elif / else
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type 10, 50, 10 (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 1 - Program 5 : nested loops, break
2
low = int(input("Enter lower limit: "))
โŒจ๏ธ Input Shows "Enter lower limit: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable low
3
high = int(input("Enter upper limit: "))
โŒจ๏ธ Input Shows "Enter upper limit: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable high
4
print("Prime numbers:", end=" ")
๐Ÿ–ฅ๏ธ Output Displays the text "Prime numbers:" on the screen (ends with " " instead of a new line)
5
for num in range(max(2, low), high + 1):
๐Ÿ” Loop LOOP: gives the numbers from max(2, low) up to high + 1 - 1; for each number, num takes that value and the indented block runs once
6
for d in range(2, int(num ** 0.5) + 1):
๐Ÿ” Loop LOOP: gives the numbers from 2 up to int(num ** 0.5) + 1 - 1; for each number, d takes that value and the indented block runs once
7
if num % d == 0:
๐Ÿ”€ Decision CHECKS whether num % d is equal to 0. If True, the indented lines below run; otherwise they are skipped
8
break
๐Ÿ” Loop BREAK - leaves the loop immediately
9
else:
๐Ÿ” Loop ELSE of the loop: runs when the loop finishes WITHOUT a break
10
print(num, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of num on the screen (ends with " " instead of a new line)
11
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
12
n = int(input("How many Fibonacci terms? "))
โŒจ๏ธ Input Shows "How many Fibonacci terms? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
13
a, b = 0, 1
๐Ÿงฎ Store / Calculate Stores 0, 1 into a, b respectively
14
print("Fibonacci:", end=" ")
๐Ÿ–ฅ๏ธ Output Displays the text "Fibonacci:" on the screen (ends with " " instead of a new line)
15
for _ in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, _ takes that value and the indented block runs once
16
print(a, end=" ")
๐Ÿ–ฅ๏ธ Output Displays the value of a on the screen (ends with " " instead of a new line)
17
a, b = b, a + b
๐Ÿงฎ Store / Calculate Stores b, a + b into a, b respectively
18
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
low = int(input("Enter lower limit: "))
low = 10
Enter lower limit: 10
23
high = int(input("Enter upper limit: "))
high = 50
Enter upper limit: 50
34
print("Prime numbers:", end=" ")
Prime numbers: 
45
for num in range(max(2, low), high + 1):
next item taken
num = 10
56
for d in range(2, int(num ** 0.5) + 1):
next item taken
d = 2
67
if num % d == 0:
condition is TRUE โ†’ enters the block
78
break
85
for num in range(max(2, low), high + 1):
next item taken
num = 11
96
for d in range(2, int(num ** 0.5) + 1):
next item taken
107
if num % d == 0:
condition is FALSE โ†’ skips this block
116
for d in range(2, int(num ** 0.5) + 1):
next item taken
d = 3
127
if num % d == 0:
condition is FALSE โ†’ skips this block
136
for d in range(2, int(num ** 0.5) + 1):
no items left โ†’ loop ends
1410
print(num, end=" ")
11 
155
for num in range(max(2, low), high + 1):
next item taken
num = 12
166
for d in range(2, int(num ** 0.5) + 1):
next item taken
d = 2
177
if num % d == 0:
condition is TRUE โ†’ enters the block
188
break
195
for num in range(max(2, low), high + 1):
next item taken
num = 13
206
for d in range(2, int(num ** 0.5) + 1):
next item taken
217
if num % d == 0:
condition is FALSE โ†’ skips this block
226
for d in range(2, int(num ** 0.5) + 1):
next item taken
d = 3
237
if num % d == 0:
condition is FALSE โ†’ skips this block
246
for d in range(2, int(num ** 0.5) + 1):
no items left โ†’ loop ends
2510
print(num, end=" ")
13 
265
for num in range(max(2, low), high + 1):
next item taken
num = 14
276
for d in range(2, int(num ** 0.5) + 1):
next item taken
d = 2
287
if num % d == 0:
condition is TRUE โ†’ enters the block
298
break
305
for num in range(max(2, low), high + 1):
next item taken
num = 15
316
for d in range(2, int(num ** 0.5) + 1):
next item taken
327
if num % d == 0:
condition is FALSE โ†’ skips this block

โ€ฆ Python runs 277 more line-steps in the same way (loops repeat the same lines). Final values: low = 10, high = 50, num = 50, d = 2, n = 10, a = 55, b = 89, _ = 9

Q9 PYTHON

Python Level 2 (NumPy): Create NumPy arrays and perform arithmetic, statistical and indexing operations.

# Level 2 - Program 1 : NumPy basics
import numpy as np
marks = np.array([78, 85, 62, 90, 71, 88])
print("Array        :", marks)
print("Type / dtype :", type(marks), marks.dtype)
print("Add 5 grace  :", marks + 5)
print("Sum / Mean   :", marks.sum(), "/", round(marks.mean(), 2))
print("Max / Min    :", marks.max(), "/", marks.min())
print("Std deviation:", round(marks.std(), 3))
print("Marks > 80   :", marks[marks > 80])
print("zeros(3)     :", np.zeros(3))
print("arange(0,10,3):", np.arange(0, 10, 3))
print("linspace(0,1,5):", np.linspace(0, 1, 5))
โ–ถ Sample Output
Array        : [78 85 62 90 71 88]
Type / dtype : <class 'numpy.ndarray'> int64
Add 5 grace  : [83 90 67 95 76 93]
Sum / Mean   : 474 / 79.0
Max / Min    : 90 / 62
Std deviation: 9.933
Marks > 80   : [85 90 88]
zeros(3)     : [0. 0. 0.]
arange(0,10,3): [0 3 6 9]
linspace(0,1,5): [0.   0.25 0.5  0.75 1.  ]
๐Ÿ’ก Explanation: NumPy performs vectorised operations - one statement works on all elements without a loop. marks[marks > 80] is boolean indexing (filtering).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 2 - Program 1 : NumPy basics
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
marks = np.array([78, 85, 62, 90, 71, 88])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [78, 85, 62, 90, 71, 88]; the result is stored in variable marks
4
print("Array        :", marks)
๐Ÿ–ฅ๏ธ Output Displays the text "Array :", then the value of marks on the screen
5
print("Type / dtype :", type(marks), marks.dtype)
๐Ÿ–ฅ๏ธ Output Displays the text "Type / dtype :", then the value of type(marks), then the value of marks.dtype on the screen
6
print("Add 5 grace  :", marks + 5)
๐Ÿ–ฅ๏ธ Output Displays the text "Add 5 grace :", then the value of marks + 5 on the screen
7
print("Sum / Mean   :", marks.sum(), "/", round(marks.mean(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Sum / Mean :", then the value of marks.sum(), then the text "/", then the value of round(marks.mean(), 2) on the screen
8
print("Max / Min    :", marks.max(), "/", marks.min())
๐Ÿ–ฅ๏ธ Output Displays the text "Max / Min :", then the value of marks.max(), then the text "/", then the value of marks.min() on the screen
9
print("Std deviation:", round(marks.std(), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Std deviation:", then the value of round(marks.std(), 3) on the screen
10
print("Marks > 80   :", marks[marks > 80])
๐Ÿ–ฅ๏ธ Output Displays the text "Marks > 80 :", then the value of marks[marks > 80] on the screen
11
print("zeros(3)     :", np.zeros(3))
๐Ÿ–ฅ๏ธ Output Displays the text "zeros(3) :", then the value of np.zeros(3) on the screen
12
print("arange(0,10,3):", np.arange(0, 10, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "arange(0,10,3):", then the value of np.arange(0, 10, 3) on the screen
13
print("linspace(0,1,5):", np.linspace(0, 1, 5))
๐Ÿ–ฅ๏ธ Output Displays the text "linspace(0,1,5):", then the value of np.linspace(0, 1, 5) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
marks = np.array([78, 85, 62, 90, 71, 88])
marks = array([78, 85, 62, 90, 71, 88])
34
print("Array        :", marks)
Array        : [78 85 62 90 71 88]
45
print("Type / dtype :", type(marks), marks.dtype)
Type / dtype : <class 'numpy.ndarray'> int64
56
print("Add 5 grace  :", marks + 5)
Add 5 grace  : [83 90 67 95 76 93]
67
print("Sum / Mean   :", marks.sum(), "/", round(marks.mean(), 2))
Sum / Mean   : 474 / 79.0
78
print("Max / Min    :", marks.max(), "/", marks.min())
Max / Min    : 90 / 62
89
print("Std deviation:", round(marks.std(), 3))
Std deviation: 9.933
910
print("Marks > 80   :", marks[marks > 80])
Marks > 80   : [85 90 88]
1011
print("zeros(3)     :", np.zeros(3))
zeros(3)     : [0. 0. 0.]
1112
print("arange(0,10,3):", np.arange(0, 10, 3))
arange(0,10,3): [0 3 6 9]
1213
print("linspace(0,1,5):", np.linspace(0, 1, 5))
linspace(0,1,5): [0.   0.25 0.5  0.75 1.  ]
Q10 PYTHON

Python Level 2 (NumPy - Matrices): Create two 3x3 matrices and find their sum, product, transpose and determinant.

# Level 2 - Program 2 : matrix operations
import numpy as np
A = np.array([[2, 1, 3], [0, 4, 5], [1, 2, 1]])
B = np.arange(1, 10).reshape(3, 3)
print("Matrix A:\n", A)
print("Matrix B:\n", B)
print("A + B:\n", A + B)
print("A x B (matrix product):\n", A @ B)
print("Transpose of A:\n", A.T)
print("Determinant of A:", round(np.linalg.det(A), 2))
print("Element-wise A * B:\n", A * B)
โ–ถ Sample Output
Matrix A:
 [[2 1 3]
 [0 4 5]
 [1 2 1]]
Matrix B:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
A + B:
 [[ 3  3  6]
 [ 4  9 11]
 [ 8 10 10]]
A x B (matrix product):
 [[27 33 39]
 [51 60 69]
 [16 20 24]]
Transpose of A:
 [[2 0 1]
 [1 4 2]
 [3 5 1]]
Determinant of A: -19.0
Element-wise A * B:
 [[ 2  2  9]
 [ 0 20 30]
 [ 7 16  9]]
๐Ÿ’ก Explanation: @ (or np.dot) gives the matrix product (row x column), while * multiplies element-wise. Matrices are used in AI to store data, images and neural-network weights.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 2 - Program 2 : matrix operations
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
A = np.array([[2, 1, 3], [0, 4, 5], [1, 2, 1]])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[2, 1, 3], [0, 4, 5], [1, 2, 1]]; the result is stored in variable A
4
B = np.arange(1, 10).reshape(3, 3)
๐Ÿ“ฆ Library / Data Changes the shape of np.arange(1, 10) to (3, 3); the result is stored in variable B
5
print("Matrix A:\n", A)
๐Ÿ–ฅ๏ธ Output Displays the text "Matrix A:", then the value of A on the screen
6
print("Matrix B:\n", B)
๐Ÿ–ฅ๏ธ Output Displays the text "Matrix B:", then the value of B on the screen
7
print("A + B:\n", A + B)
๐Ÿ–ฅ๏ธ Output Displays the text "A + B:", then the value of A + B on the screen
8
print("A x B (matrix product):\n", A @ B)
๐Ÿ–ฅ๏ธ Output Displays the text "A x B (matrix product):", then the value of A @ B on the screen
9
print("Transpose of A:\n", A.T)
๐Ÿ–ฅ๏ธ Output Displays the text "Transpose of A:", then the value of A.T on the screen
10
print("Determinant of A:", round(np.linalg.det(A), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Determinant of A:", then the value of round(np.linalg.det(A), 2) on the screen
11
print("Element-wise A * B:\n", A * B)
๐Ÿ–ฅ๏ธ Output Displays the text "Element-wise A * B:", then the value of A * B on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
A = np.array([[2, 1, 3], [0, 4, 5], [1, 2, 1]])
A = array of shape (3, 3)
34
B = np.arange(1, 10).reshape(3, 3)
B = array of shape (3, 3)
45
print("Matrix A:\n", A)
Matrix A:
 [[2 1 3]
 [0 4 5]
 [1 2 1]]
56
print("Matrix B:\n", B)
Matrix B:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
67
print("A + B:\n", A + B)
A + B:
 [[ 3  3  6]
 [ 4  9 11]
 [ 8 10 10]]
78
print("A x B (matrix product):\n", A @ B)
A x B (matrix product):
 [[27 33 39]
 [51 60 69]
 [16 20 24]]
89
print("Transpose of A:\n", A.T)
Transpose of A:
 [[2 0 1]
 [1 4 2]
 [3 5 1]]
910
print("Determinant of A:", round(np.linalg.det(A), 2))
Determinant of A: -19.0
1011
print("Element-wise A * B:\n", A * B)
Element-wise A * B:
 [[ 2  2  9]
 [ 0 20 30]
 [ 7 16  9]]
Q11 PYTHON

Python Level 2 (Pandas): Create a DataFrame of students, add a new column and display statistics.

# Level 2 - Program 3 : Pandas DataFrame
import pandas as pd
data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'],
        'Maths': [88, 92, 67, 75, 95],
        'Science': [79, 85, 72, 91, 89]}
df = pd.DataFrame(data)
df['Total'] = df['Maths'] + df['Science']
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
print(df)
print("\nStatistics:\n", df[['Maths', 'Science', 'Total']].describe().round(2))
print("\nTopper:", df.loc[df['Total'].idxmax(), 'Name'])
โ–ถ Sample Output
    Name  Maths  Science  Total      Result
0   Ravi     88       79    167        Pass
1   Sana     92       85    177        Pass
2    Tom     67       72    139  Needs Help
3    Uma     75       91    166        Pass
4  Vikas     95       89    184        Pass

Statistics:
        Maths  Science   Total
count   5.00     5.00    5.00
mean   83.40    83.20  166.60
std    11.93     7.76   17.13
min    67.00    72.00  139.00
25%    75.00    79.00  166.00
50%    88.00    85.00  167.00
75%    92.00    89.00  177.00
max    95.00    91.00  184.00

Topper: Vikas
๐Ÿ’ก Explanation: New columns can be calculated from existing columns. describe() summarises numeric columns and idxmax() returns the index of the largest value.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 2 - Program 3 : Pandas DataFrame
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'],
        'Maths': [88, 92, 67, 75, 95],
        'Science': [79, 85, 72, 91, 89]}
๐Ÿงฎ Store / Calculate Stores a dictionary {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikaโ€ฆ in variable data
6
df = pd.DataFrame(data)
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
7
df['Total'] = df['Maths'] + df['Science']
๐Ÿงฎ Store / Calculate Puts the value of df['Maths'] + df['Science'] (calculated using +) into df['Total'] (item 'Total' of df)
8
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
๐Ÿงฎ Store / Calculate Puts a new list made by a list comprehension ['Pass' if t >= 150 else 'Needs Help' for t iโ€ฆ into df['Result'] (item 'Result' of df)
9
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
10
print("\nStatistics:\n", df[['Maths', 'Science', 'Total']].describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays the text "Statistics:", then the value of df[['Maths', 'Science', 'Total']].describe().โ€ฆ on the screen
11
print("\nTopper:", df.loc[df['Total'].idxmax(), 'Name'])
๐Ÿ–ฅ๏ธ Output Displays the text "Topper:", then the value of df.loc[df['Total'].idxmax(), 'Name'] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'],
34
'Maths': [88, 92, 67, 75, 95],
45
'Science': [79, 85, 72, 91, 89]}
53
data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'],
data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'], 'Maths': [88, 92,โ€ฆ
66
df = pd.DataFrame(data)
df = DataFrame (5 rows ร— 3 columns)
77
df['Total'] = df['Maths'] + df['Science']
df = DataFrame (5 rows ร— 4 columns)
88
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
98
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
108
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
118
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
128
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
138
df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']]
df = DataFrame (5 rows ร— 5 columns)
149
print(df)
    Name  Maths  Science  Total      Result
0   Ravi     88       79    167        Pass
1   Sana     92       85    177        Pass
2    Tom     67       72    139  Needs Help
3    Uma     75       91    166        Pass
4  Vikas     95       89    184        Pass
1510
print("\nStatistics:\n", df[['Maths', 'Science', 'Total']].describe().round(2))
Statistics:
        Maths  Science   Total
count   5.00     5.00    5.00
mean   83.40    83.20  166.60
std    11.93     7.76   17.13
min    67.00    72.00  139.00
25%    75.00    79.00  166.00
50%    88.00    85.00  167.00
75%    92.00    89.00  177.00
max    95.00    91.00  184.00
1611
print("\nTopper:", df.loc[df['Total'].idxmax(), 'Name'])
Topper: Vikas
Q12 PYTHON

Python Level 2 (Pandas + CSV): Read rainfall.csv into a DataFrame and analyse it (head, shape, mean, maximum and minimum rainfall month).

# Level 2 - Program 4 : read a CSV file
import pandas as pd
df = pd.read_csv("rainfall.csv")
print(df.head())
print("Shape:", df.shape)
print("Average annual rainfall (mm):", round(df['Rainfall_mm'].mean(), 2))
wet = df.loc[df['Rainfall_mm'].idxmax()]
dry = df.loc[df['Rainfall_mm'].idxmin()]
print("Wettest month:", wet['Month'], "-", wet['Rainfall_mm'], "mm")
print("Driest month :", dry['Month'], "-", dry['Rainfall_mm'], "mm")
print("Monsoon (Jun-Sep) total:", df.loc[5:8, 'Rainfall_mm'].sum(), "mm")
โ–ถ Sample Output
  Month  Rainfall_mm  Avg_Temp_C
0   Jan           19          14
1   Feb           20          17
2   Mar           15          23
3   Apr           10          29
4   May           25          33
Shape: (12, 3)
Average annual rainfall (mm): 63.0
Wettest month: Aug - 233 mm
Driest month : Nov - 6 mm
Monsoon (Jun-Sep) total: 637 mm
๐Ÿ’ก Explanation: rainfall.csv contains Month, Rainfall_mm and Avg_Temp_C for 12 months. loc[5:8] selects rows with index 5 to 8 (June to September) - with loc the end label is included.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q12.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 2 - Program 4 : read a CSV file
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
df = pd.read_csv("rainfall.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "rainfall.csv" into a DataFrame (table); the result is stored in variable df
4
print(df.head())
๐Ÿ–ฅ๏ธ Output Displays the value of df.head() on the screen
5
print("Shape:", df.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape:", then the value of df.shape on the screen
6
print("Average annual rainfall (mm):", round(df['Rainfall_mm'].mean(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Average annual rainfall (mm):", then the value of round(df['Rainfall_mm'].mean(), 2) on the screen
7
wet = df.loc[df['Rainfall_mm'].idxmax()]
๐Ÿ“ฆ Library / Data Stores the item df.loc[df['Rainfall_mm'].idxmax()] in variable wet
8
dry = df.loc[df['Rainfall_mm'].idxmin()]
๐Ÿ“ฆ Library / Data Stores the item df.loc[df['Rainfall_mm'].idxmin()] in variable dry
9
print("Wettest month:", wet['Month'], "-", wet['Rainfall_mm'], "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Wettest month:", then the value of wet['Month'], then the text "-", then the value of wet['Rainfall_mm'], then the text "mm" on the screen
10
print("Driest month :", dry['Month'], "-", dry['Rainfall_mm'], "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Driest month :", then the value of dry['Month'], then the text "-", then the value of dry['Rainfall_mm'], then the text "mm" on the screen
11
print("Monsoon (Jun-Sep) total:", df.loc[5:8, 'Rainfall_mm'].sum(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Monsoon (Jun-Sep) total:", then the value of df.loc[5:8, 'Rainfall_mm'].sum(), then the text "mm" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
df = pd.read_csv("rainfall.csv")
df = DataFrame (12 rows ร— 3 columns)
34
print(df.head())
  Month  Rainfall_mm  Avg_Temp_C
0   Jan           19          14
1   Feb           20          17
2   Mar           15          23
3   Apr           10          29
4   May           25          33
45
print("Shape:", df.shape)
Shape: (12, 3)
56
print("Average annual rainfall (mm):", round(df['Rainfall_mm'].mean(), 2))
Average annual rainfall (mm): 63.0
67
wet = df.loc[df['Rainfall_mm'].idxmax()]
wet = Series (3 values)
78
dry = df.loc[df['Rainfall_mm'].idxmin()]
dry = Series (3 values)
89
print("Wettest month:", wet['Month'], "-", wet['Rainfall_mm'], "mm")
Wettest month: Aug - 233 mm
910
print("Driest month :", dry['Month'], "-", dry['Rainfall_mm'], "mm")
Driest month : Nov - 6 mm
1011
print("Monsoon (Jun-Sep) total:", df.loc[5:8, 'Rainfall_mm'].sum(), "mm")
Monsoon (Jun-Sep) total: 637 mm
Q13 PYTHON

Python Level 2 (Scikit-learn): Load the Iris dataset, split it into training and testing sets, train a classifier and find its accuracy.

# Level 2 - Program 5 : first ML model with scikit-learn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
iris = load_iris()
X, y = iris.data, iris.target
print("Features:", iris.feature_names)
print("Classes :", iris.target_names.tolist())
print("Dataset shape:", X.shape)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("Training samples:", len(X_train), " Testing samples:", len(X_test))
print("Accuracy:", round(accuracy_score(y_test, pred) * 100, 2), "%")
sample = [[5.1, 3.5, 1.4, 0.2]]
print("Prediction for", sample, "->", iris.target_names[model.predict(sample)[0]])
โ–ถ Sample Output
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Classes : ['setosa', 'versicolor', 'virginica']
Dataset shape: (150, 4)
Training samples: 120  Testing samples: 30
Accuracy: 100.0 %
Prediction for [[5.1, 3.5, 1.4, 0.2]] -> setosa
๐Ÿ’ก Explanation: Scikit-learn follows the same steps for every model: load data -> train_test_split -> fit() -> predict() -> evaluate. random_state fixes the random split so the result can be repeated.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules sklearn.datasets, sklearn.model_selection, sklearn.tree, sklearn.metrics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q13.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Level 2 - Program 5 : first ML model with scikit-learn
2
from sklearn.datasets import load_iris
๐Ÿ“ฆ Library / Data Loads load_iris from the sklearn.datasets module
3
from sklearn.model_selection import train_test_split
๐Ÿ“ฆ Library / Data Loads train_test_split from the sklearn.model_selection module
4
from sklearn.tree import DecisionTreeClassifier
๐Ÿ“ฆ Library / Data Loads DecisionTreeClassifier from the sklearn.tree module
5
from sklearn.metrics import accuracy_score
๐Ÿ“ฆ Library / Data Loads accuracy_score from the sklearn.metrics module
6
iris = load_iris()
๐Ÿงฎ Store / Calculate Loads the built-in Iris flower dataset; the result is stored in variable iris
7
X, y = iris.data, iris.target
๐Ÿงฎ Store / Calculate Stores iris.data, iris.target into X, y respectively
8
print("Features:", iris.feature_names)
๐Ÿ–ฅ๏ธ Output Displays the text "Features:", then the value of iris.feature_names on the screen
9
print("Classes :", iris.target_names.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Classes :", then the value of iris.target_names.tolist() on the screen
10
print("Dataset shape:", X.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Dataset shape:", then the value of X.shape on the screen
11
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (20% for testing) and stores them in X_train, X_test, y_train, y_test
12
model = DecisionTreeClassifier(random_state=42)
๐Ÿงฎ Store / Calculate Creates a Decision Tree model; the result is stored in variable model
13
model.fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model model on the given data
14
pred = model.predict(X_test)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for X_test; the result is stored in variable pred
15
print("Training samples:", len(X_train), " Testing samples:", len(X_test))
๐Ÿ–ฅ๏ธ Output Displays the text "Training samples:", then the value of len(X_train), then the text "Testing samples:", then the value of len(X_test) on the screen
16
print("Accuracy:", round(accuracy_score(y_test, pred) * 100, 2), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Accuracy:", then the value of round(accuracy_score(y_test, pred) * 100, 2), then the text "%" on the screen
17
sample = [[5.1, 3.5, 1.4, 0.2]]
๐Ÿงฎ Store / Calculate Stores a list [[5.1, 3.5, 1.4, 0.2]] in variable sample
18
print("Prediction for", sample, "->", iris.target_names[model.predict(sample)[0]])
๐Ÿ–ฅ๏ธ Output Displays the text "Prediction for", then the value of sample, then the text "->", then the value of iris.target_names[model.predict(sample)[0]] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
from sklearn.datasets import load_iris
23
from sklearn.model_selection import train_test_split
34
from sklearn.tree import DecisionTreeClassifier
45
from sklearn.metrics import accuracy_score
56
iris = load_iris()
iris = Bunch model
67
X, y = iris.data, iris.target
X = array of shape (150, 4), y = array of shape (150,)
78
print("Features:", iris.feature_names)
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
89
print("Classes :", iris.target_names.tolist())
Classes : ['setosa', 'versicolor', 'virginica']
910
print("Dataset shape:", X.shape)
Dataset shape: (150, 4)
1011
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train = array of shape (120, 4), X_test = array of shape (30, 4), y_train = array of shape (120,), y_test = array of shape (30,)
1112
model = DecisionTreeClassifier(random_state=42)
model = DecisionTreeClassifier model
1213
model.fit(X_train, y_train)
1314
pred = model.predict(X_test)
pred = array of shape (30,)
1415
print("Training samples:", len(X_train), " Testing samples:", len(X_test))
Training samples: 120  Testing samples: 30
1516
print("Accuracy:", round(accuracy_score(y_test, pred) * 100, 2), "%")
Accuracy: 100.0 %
1617
sample = [[5.1, 3.5, 1.4, 0.2]]
sample = [[5.1, 3.5, 1.4, 0.2]]
1718
print("Prediction for", sample, "->", iris.target_names[model.predict(sample)[0]])
Prediction for [[5.1, 3.5, 1.4, 0.2]] -> setosa
Q14 THEORY / VIVA

Unit 5: Identification of the level of measurement (Nominal, Ordinal, Interval, Ratio) of given data.

LEVELS OF MEASUREMENT
 Nominal  - names/labels, no order               (gender, blood group, city)
 Ordinal  - categories WITH order, gaps unequal  (rank, grade A/B/C, rating)
 Interval - ordered, equal gaps, NO true zero    (temperature in C, year)
 Ratio    - equal gaps AND a true zero           (height, weight, marks, income)

+----+--------------------------------------+-----------+
| No | Data                                 | Level     |
+----+--------------------------------------+-----------+
|  1 | Blood group of students              | Nominal   |
|  2 | Customer rating (Poor/Good/Excellent)| Ordinal   |
|  3 | Temperature of Delhi in Celsius      | Interval  |
|  4 | Height of students in cm             | Ratio     |
|  5 | Position in a race (1st, 2nd, 3rd)   | Ordinal   |
|  6 | Mobile number                        | Nominal   |
|  7 | Monthly electricity units consumed   | Ratio     |
|  8 | IQ score / calendar year             | Interval  |
|  9 | T-shirt size (S, M, L, XL)           | Ordinal   |
| 10 | Time taken to finish a test (min)    | Ratio     |
+----+--------------------------------------+-----------+
โ–ถ Result
Nominal = 2, Ordinal = 3, Interval = 2, Ratio = 3
๐Ÿ’ก Explanation: The level of measurement decides which statistics are allowed: mode for nominal, median for ordinal, mean for interval and ratio. Ratio data allows statements like 'twice as much'.
Q15 PYTHON

Unit 5: Python program to demonstrate the use of mean, median, mode, standard deviation and variance.

# Statistical analysis of data
import statistics as st
import numpy as np
heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
print("Data (heights in cm):", heights)
print("Mean     :", st.mean(heights))
print("Median   :", st.median(heights))
print("Mode     :", st.mode(heights))
print("Range    :", max(heights) - min(heights))
print("Population variance (pvariance):", round(st.pvariance(heights), 2))
print("Population std deviation (pstdev):", round(st.pstdev(heights), 2))
print("Sample variance (variance):", round(st.variance(heights), 2))
print("Sample std deviation (stdev):", round(st.stdev(heights), 2))
print("NumPy check -> var:", round(np.var(heights), 2), " std:", round(np.std(heights), 2))
โ–ถ Sample Output
Data (heights in cm): [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
Mean     : 158.2
Median   : 156.5
Mode     : 155
Range    : 20
Population variance (pvariance): 33.96
Population std deviation (pstdev): 5.83
Sample variance (variance): 37.73
Sample std deviation (stdev): 6.14
NumPy check -> var: 33.96  std: 5.83
๐Ÿ’ก Explanation: Mean is the average, median the middle value and mode the most frequent value. Variance/standard deviation measure spread. pvariance divides by n (population); variance divides by n-1 (sample). np.var() uses n by default.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules statistics, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q15.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Statistical analysis of data
2
import statistics as st
๐Ÿ“ฆ Library / Data Loads the module statistics (nick-name st) - mean, median, mode functions
3
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
4
heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
๐Ÿงฎ Store / Calculate Stores a list [150, 152, 155, 155, 158, 160, 155, 162, 165,โ€ฆ in variable heights
5
print("Data (heights in cm):", heights)
๐Ÿ–ฅ๏ธ Output Displays the text "Data (heights in cm):", then the value of heights on the screen
6
print("Mean     :", st.mean(heights))
๐Ÿ–ฅ๏ธ Output Displays the text "Mean :", then the value of st.mean(heights) on the screen
7
print("Median   :", st.median(heights))
๐Ÿ–ฅ๏ธ Output Displays the text "Median :", then the value of st.median(heights) on the screen
8
print("Mode     :", st.mode(heights))
๐Ÿ–ฅ๏ธ Output Displays the text "Mode :", then the value of st.mode(heights) on the screen
9
print("Range    :", max(heights) - min(heights))
๐Ÿ–ฅ๏ธ Output Displays the text "Range :", then the value of max(heights) - min(heights) on the screen
10
print("Population variance (pvariance):", round(st.pvariance(heights), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Population variance (pvariance):", then the value of round(st.pvariance(heights), 2) on the screen
11
print("Population std deviation (pstdev):", round(st.pstdev(heights), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Population std deviation (pstdev):", then the value of round(st.pstdev(heights), 2) on the screen
12
print("Sample variance (variance):", round(st.variance(heights), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Sample variance (variance):", then the value of round(st.variance(heights), 2) on the screen
13
print("Sample std deviation (stdev):", round(st.stdev(heights), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Sample std deviation (stdev):", then the value of round(st.stdev(heights), 2) on the screen
14
print("NumPy check -> var:", round(np.var(heights), 2), " std:", round(np.std(heights), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "NumPy check -> var:", then the value of round(np.var(heights), 2), then the text "std:", then the value of round(np.std(heights), 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import statistics as st
23
import numpy as np
34
heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
45
print("Data (heights in cm):", heights)
Data (heights in cm): [150, 152, 155, 155, 158, 160, 155, 162, 165, 170]
56
print("Mean     :", st.mean(heights))
Mean     : 158.2
67
print("Median   :", st.median(heights))
Median   : 156.5
78
print("Mode     :", st.mode(heights))
Mode     : 155
89
print("Range    :", max(heights) - min(heights))
Range    : 20
910
print("Population variance (pvariance):", round(st.pvariance(heights), 2))
Population variance (pvariance): 33.96
1011
print("Population std deviation (pstdev):", round(st.pstdev(heights), 2))
Population std deviation (pstdev): 5.83
1112
print("Sample variance (variance):", round(st.variance(heights), 2))
Sample variance (variance): 37.73
1213
print("Sample std deviation (stdev):", round(st.stdev(heights), 2))
Sample std deviation (stdev): 6.14
1314
print("NumPy check -> var:", round(np.var(heights), 2), " std:", round(np.std(heights), 2)
NumPy check -> var: 33.96  std: 5.83
Q16 PYTHON

Unit 5: Python program to visualise data using a LINE graph (monthly rainfall from rainfall.csv).

# Line graph
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("rainfall.csv")
plt.plot(df['Month'], df['Rainfall_mm'], marker='o', color='navy', label='Rainfall (mm)')
plt.title("Monthly Rainfall - Delhi")
plt.xlabel("Month")
plt.ylabel("Rainfall (mm)")
plt.legend()
plt.grid(True, linestyle='--', alpha=0.5)
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A line graph shows the trend of continuous data over time. The monsoon peak in July-August is clearly visible.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q16.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Line graph
2
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
3
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
df = pd.read_csv("rainfall.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "rainfall.csv" into a DataFrame (table); the result is stored in variable df
5
plt.plot(df['Month'], df['Rainfall_mm'], marker='o', color='navy', label='Rainfall (mm)')
๐Ÿ–ฅ๏ธ Output Draws a line chart of df['Month'], df['Rainfall_mm']
6
plt.title("Monthly Rainfall - Delhi")
๐Ÿ–ฅ๏ธ Output Writes "Monthly Rainfall - Delhi" as the title of the chart
7
plt.xlabel("Month")
๐Ÿ–ฅ๏ธ Output Writes "Month" as the label of the X-axis
8
plt.ylabel("Rainfall (mm)")
๐Ÿ–ฅ๏ธ Output Writes "Rainfall (mm)" as the label of the Y-axis
9
plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
10
plt.grid(True, linestyle='--', alpha=0.5)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
11
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import pandas as pd
23
import matplotlib.pyplot as plt
34
df = pd.read_csv("rainfall.csv")
df = DataFrame (12 rows ร— 3 columns)
45
plt.plot(df['Month'], df['Rainfall_mm'], marker='o', color='navy', label='Rainfall (mm)')
56
plt.title("Monthly Rainfall - Delhi")
67
plt.xlabel("Month")
78
plt.ylabel("Rainfall (mm)")
89
plt.legend()
910
plt.grid(True, linestyle='--', alpha=0.5)
1011
plt.show()
Q17 PYTHON

Unit 5: Python program to visualise data using a BAR graph.

# Bar graph
import matplotlib.pyplot as plt
domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI']
students = [34, 22, 18, 12, 40]
plt.bar(domains, students, color=['#0A2472', '#FF6B00', '#2B8A3E', '#9C36B5', '#1971C2'])
plt.title("Favourite AI Domain of Class XI Students")
plt.xlabel("AI Domain")
plt.ylabel("Number of students")
for i, v in enumerate(students):
    plt.text(i, v + 0.5, str(v), ha='center')
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: Bar graphs compare discrete categories. plt.text() writes the value on top of each bar.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q17.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Bar graph
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI']
๐Ÿงฎ Store / Calculate Stores a list ['Data Science', 'Computer Vision', 'NLP', 'Rโ€ฆ in variable domains
4
students = [34, 22, 18, 12, 40]
๐Ÿงฎ Store / Calculate Stores a list [34, 22, 18, 12, 40] in variable students
5
plt.bar(domains, students, color=['#0A2472', '#FF6B00', '#2B8A3E', '#9C36B5', '#1971C2'])
๐Ÿ–ฅ๏ธ Output Draws a bar chart of domains, students
6
plt.title("Favourite AI Domain of Class XI Students")
๐Ÿ–ฅ๏ธ Output Writes "Favourite AI Domain of Class XI Students" as the title of the chart
7
plt.xlabel("AI Domain")
๐Ÿ–ฅ๏ธ Output Writes "AI Domain" as the label of the X-axis
8
plt.ylabel("Number of students")
๐Ÿ–ฅ๏ธ Output Writes "Number of students" as the label of the Y-axis
9
for i, v in enumerate(students):
๐Ÿ” Loop LOOP over students with position: in each round i, v get (position, item)
10
plt.text(i, v + 0.5, str(v), ha='center')
๐Ÿ–ฅ๏ธ Output Writes text on the chart
11
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI']
domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI']
34
students = [34, 22, 18, 12, 40]
students = [34, 22, 18, 12, 40]
45
plt.bar(domains, students, color=['#0A2472', '#FF6B00', '#2B8A3E', '#9C36B5', '#1971C2'])
56
plt.title("Favourite AI Domain of Class XI Students")
67
plt.xlabel("AI Domain")
78
plt.ylabel("Number of students")
89
for i, v in enumerate(students):
next item taken
i = 0, v = 34
910
plt.text(i, v + 0.5, str(v), ha='center')
109
for i, v in enumerate(students):
next item taken
i = 1, v = 22
1110
plt.text(i, v + 0.5, str(v), ha='center')
129
for i, v in enumerate(students):
next item taken
i = 2, v = 18
1310
plt.text(i, v + 0.5, str(v), ha='center')
149
for i, v in enumerate(students):
next item taken
i = 3, v = 12
1510
plt.text(i, v + 0.5, str(v), ha='center')
169
for i, v in enumerate(students):
next item taken
i = 4, v = 40
1710
plt.text(i, v + 0.5, str(v), ha='center')
189
for i, v in enumerate(students):
no items left โ†’ loop ends
1911
plt.show()
Q18 PYTHON

Unit 5: Python program to visualise data using a HISTOGRAM.

# Histogram
import matplotlib.pyplot as plt
marks = [35, 42, 48, 51, 55, 58, 60, 61, 63, 65, 66, 68, 70, 71, 72, 74, 75,
         76, 78, 79, 80, 82, 84, 85, 88, 90, 92, 95]
plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], color='orange', edgecolor='black')
plt.title("Distribution of AI Marks")
plt.xlabel("Marks range")
plt.ylabel("Number of students")
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A histogram groups continuous data into ranges (bins) and shows how many values fall in each range - i.e. the distribution of the data.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q18.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Histogram
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
marks = [35, 42, 48, 51, 55, 58, 60, 61, 63, 65, 66, 68, 70, 71, 72, 74, 75,
         76, 78, 79, 80, 82, 84, 85, 88, 90, 92, 95]
๐Ÿงฎ Store / Calculate Stores a list [35, 42, 48, 51, 55, 58, 60, 61, 63, 65, 66, โ€ฆ in variable marks
5
plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], color='orange', edgecolor='black')
๐Ÿ–ฅ๏ธ Output Draws a histogram of marks
6
plt.title("Distribution of AI Marks")
๐Ÿ–ฅ๏ธ Output Writes "Distribution of AI Marks" as the title of the chart
7
plt.xlabel("Marks range")
๐Ÿ–ฅ๏ธ Output Writes "Marks range" as the label of the X-axis
8
plt.ylabel("Number of students")
๐Ÿ–ฅ๏ธ Output Writes "Number of students" as the label of the Y-axis
9
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
marks = [35, 42, 48, 51, 55, 58, 60, 61, 63, 65, 66, 68, 70, 71, 72, 74, 75,
marks = [35, 42, 48, 51, 55, 58, 60, 61, 63, 65, 66, 68, 70, 71, 72, 74, 75โ€ฆ
35
plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], color='orange', edgecolor='black')
46
plt.title("Distribution of AI Marks")
57
plt.xlabel("Marks range")
68
plt.ylabel("Number of students")
79
plt.show()
Q19 PYTHON

Unit 5: Python program to visualise data using a SCATTER graph.

# Scatter graph
import matplotlib.pyplot as plt
study_hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8]
marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88]
plt.scatter(study_hours, marks, color='green', s=60)
plt.title("Study Hours vs Marks")
plt.xlabel("Study hours per day")
plt.ylabel("Marks")
plt.grid(True, alpha=0.4)
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A scatter graph shows the relationship between two variables. Points rising from left to right indicate a positive correlation.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q19.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Scatter graph
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
study_hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8]
๐Ÿงฎ Store / Calculate Stores a list [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8] in variable study_hours
4
marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88]
๐Ÿงฎ Store / Calculate Stores a list [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88] in variable marks
5
plt.scatter(study_hours, marks, color='green', s=60)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of study_hours, marks
6
plt.title("Study Hours vs Marks")
๐Ÿ–ฅ๏ธ Output Writes "Study Hours vs Marks" as the title of the chart
7
plt.xlabel("Study hours per day")
๐Ÿ–ฅ๏ธ Output Writes "Study hours per day" as the label of the X-axis
8
plt.ylabel("Marks")
๐Ÿ–ฅ๏ธ Output Writes "Marks" as the label of the Y-axis
9
plt.grid(True, alpha=0.4)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
10
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
study_hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8]
study_hours = [1, 2, 2.5, 3, 4, 4.5, 5, 6, 6.5, 7, 8]
34
marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88]
marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88]
45
plt.scatter(study_hours, marks, color='green', s=60)
56
plt.title("Study Hours vs Marks")
67
plt.xlabel("Study hours per day")
78
plt.ylabel("Marks")
89
plt.grid(True, alpha=0.4)
910
plt.show()
Q20 PYTHON

Unit 5: Python program to visualise data using a PIE chart.

# Pie chart
import matplotlib.pyplot as plt
sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others']
share = [48, 18, 11, 10, 2, 11]
plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90,
        explode=[0, 0.1, 0, 0, 0, 0])
plt.title("Energy Mix (sample data)")
plt.axis('equal')
plt.show()
โ–ถ Sample Output
(The program opens a chart / image window - see the output figure below.)
Figure 1
Figure 1
๐Ÿ’ก Explanation: A pie chart shows each part as a percentage of the whole. autopct prints percentages and explode pulls one slice out for emphasis.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module matplotlib.pyplot
โžœ
โ‘ข OUTPUTdraws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q20.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Pie chart
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others']
๐Ÿงฎ Store / Calculate Stores a list ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear',โ€ฆ in variable sources
4
share = [48, 18, 11, 10, 2, 11]
๐Ÿงฎ Store / Calculate Stores a list [48, 18, 11, 10, 2, 11] in variable share
5
plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90,
        explode=[0, 0.1, 0, 0, 0, 0])
๐Ÿ–ฅ๏ธ Output Draws a pie chart of share
7
plt.title("Energy Mix (sample data)")
๐Ÿ–ฅ๏ธ Output Writes "Energy Mix (sample data)" as the title of the chart
8
plt.axis('equal')
๐Ÿ–ฅ๏ธ Output Sets axis options
9
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import matplotlib.pyplot as plt
23
sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others']
sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others']
34
share = [48, 18, 11, 10, 2, 11]
share = [48, 18, 11, 10, 2, 11]
45
plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90,
56
explode=[0, 0.1, 0, 0, 0, 0])
65
plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90,
77
plt.title("Energy Mix (sample data)")
88
plt.axis('equal')
99
plt.show()
Q21 THEORY / VIVA

Unit 4: Create an Empathy Map for a given scenario - 'Elderly people in the colony find it difficult to use digital payment apps'.

USER : Mrs. Kamla Devi, 68 years, retired teacher, lives alone
+-----------------------------+------------------------------+
| SAYS                        | THINKS                       |
| "The screen is too crowded" | "What if I send money to the |
| "I always need my grandson" |  wrong person?"              |
| "OTP comes and goes away"   | "I am too old to learn this" |
+-----------------------------+------------------------------+
| DOES                        | FEELS                        |
| Goes to bank for small work | Anxious, dependent           |
| Writes PIN on paper         | Afraid of fraud calls        |
| Pays only in cash           | Proud when she succeeds      |
+-----------------------------+------------------------------+
PAINS : small text, English-only menus, fear of fraud, fast OTP timeout
GAINS : independence, safety, voice help in Hindi, large buttons

INSIGHT / HMW question : How might we help senior citizens make safe digital
payments independently using voice-based guidance in their own language?
โ–ถ Insight
Problem identified: senior citizens need a simple, voice-guided and fraud-safe payment
interface in Indian languages (SDG 10 - Reduced Inequalities).
๐Ÿ’ก Explanation: An empathy map (Says, Thinks, Does, Feels) is used in the EMPATHISE stage of Design Thinking to understand the user's real needs before designing a solution.
Q22 THEORY / VIVA

Unit 4: Project Abstract Creation using the Design Thinking Framework (5W1H and SDG alignment).

PROJECT TITLE : "Saathi" - Voice-Guided Safe Payment Assistant for Senior Citizens
SDG ALIGNED   : SDG 10 Reduced Inequalities, SDG 9 Industry, Innovation & Infrastructure

5W1H
 WHO   : Senior citizens (60+) in urban colonies and their families
 WHAT  : Difficulty and fear in using UPI / digital payment apps
 WHEN  : While paying bills, shopping, receiving pension
 WHERE : Homes, local shops, banks
 WHY   : Small text, English menus, fraud calls -> loss of independence
 HOW   : AI voice assistant (speech-to-text + NLP) that reads options aloud in
         Hindi, confirms the receiver's name and warns about suspicious requests

DESIGN THINKING STAGES
 1. Empathise : interviewed 12 senior citizens (empathy map)
 2. Define    : "Seniors need a safe, voice-guided payment flow in their language"
 3. Ideate    : large-button UI, voice commands, fraud-alert rules, family alert
 4. Prototype : paper prototype + chatbot flow in Dialogflow
 5. Test      : 8 of 10 users completed a mock payment without help

ABSTRACT (about 100 words)
Many senior citizens avoid digital payments because apps are complex and fraud is
common. "Saathi" is an AI-based voice assistant that guides users step by step in
their own language, reads out the receiver's name before payment and flags
suspicious requests using simple rules learnt from common fraud patterns. Built
using design thinking, the prototype was tested with 10 seniors and improved their
confidence. The project supports SDG 10 by reducing the digital divide.
โ–ถ Result
Abstract prepared (approx. 100 words) with problem, users, AI approach, SDG and test result.
๐Ÿ’ก Explanation: A project abstract is a short summary of the problem, the users, the AI solution and the impact. Design Thinking has 5 stages: Empathise, Define, Ideate, Prototype and Test.
Q23 ACTIVITY

Unit 6: Calculation of Pearson's correlation coefficient in MS Excel.

DATA (enter in Excel)          A               B
                         1   Study_Hours     Marks
                         2       1             35
                         3       2             42
                         4       3             50
                         5       4             58
                         6       5             66
                         7       6             72
                         8       7             80
                         9       8             88

STEPS
1. In D2 type :  =CORREL(A2:A9, B2:B9)      (or =PEARSON(A2:A9, B2:B9))
2. Press Enter -> Pearson's r is displayed.
3. Select A1:B9 -> Insert -> Scatter chart to see the relationship.
4. Interpretation:  r close to +1 strong positive, close to -1 strong negative,
   close to 0 no linear relationship.

FORMULA  r = sum((x - x_mean)(y - y_mean)) / sqrt( sum((x - x_mean)^2) * sum((y - y_mean)^2) )
โ–ถ Result in Excel
r = 0.9993  ->  very strong positive correlation between study hours and marks.
๐Ÿ’ก Explanation: Pearson's r measures the strength and direction of a LINEAR relationship between two variables (range -1 to +1). Correlation does not prove causation.
Q24 ACTIVITY

Unit 6: Demonstration of Linear Regression in MS Excel.

DATA : same as previous activity (A2:A9 = Study_Hours = x, B2:B9 = Marks = y)

STEPS
1. Slope (m)        :  =SLOPE(B2:B9, A2:A9)
2. Intercept (c)    :  =INTERCEPT(B2:B9, A2:A9)
3. Equation         :  Marks = m x Hours + c
4. Predict marks for 9 hours :  =FORECAST.LINEAR(9, B2:B9, A2:A9)
                                (older Excel: =FORECAST(9, B2:B9, A2:A9))
5. Chart method : Insert -> Scatter -> right-click a point -> Add Trendline ->
   Linear -> tick "Display Equation on chart" and "Display R-squared value".
6. R-squared    :  =RSQ(B2:B9, A2:A9)
โ–ถ Result in Excel
Slope m = 7.452   Intercept c = 27.536
Equation: Marks = 7.452 x Hours + 27.536
Predicted marks for 9 hours = 94.6     R-squared = 0.9986
๐Ÿ’ก Explanation: Linear regression finds the best-fit straight line y = mx + c that minimises the squared error. The slope tells how much marks increase for every extra hour of study.
Q25 PYTHON

Unit 6 (Advanced learners): Demonstration of Linear Regression using a Python program.

# Linear regression with scikit-learn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1)
marks = np.array([35, 42, 50, 58, 66, 72, 80, 88])
model = LinearRegression()
model.fit(hours, marks)
print("Slope (m)     :", round(model.coef_[0], 3))
print("Intercept (c) :", round(model.intercept_, 3))
print("R-squared     :", round(model.score(hours, marks), 4))
print("Predicted marks for 9 hours:", round(model.predict([[9]])[0], 2))
plt.scatter(hours, marks, color='blue', label='Actual data')
plt.plot(hours, model.predict(hours), color='red', label='Best-fit line')
plt.title("Linear Regression: Study Hours vs Marks")
plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend()
plt.show()
โ–ถ Sample Output
Slope (m)     : 7.56
Intercept (c) : 27.357
R-squared     : 0.9993
Predicted marks for 9 hours: 95.39
Figure 1
Figure 1
๐Ÿ’ก Explanation: fit() learns the slope and intercept from data; predict() uses the line for new inputs. The values match the Excel SLOPE/INTERCEPT results. scikit-learn needs X as a 2D array, hence reshape(-1, 1).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules numpy, matplotlib.pyplot, sklearn.linear_model
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q25.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Linear regression with scikit-learn
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
from sklearn.linear_model import LinearRegression
๐Ÿ“ฆ Library / Data Loads LinearRegression from the sklearn.linear_model module
5
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1)
๐Ÿ“ฆ Library / Data Changes the shape of np.array([1, 2, 3, 4, 5, 6, 7, 8]) to (-1, 1); the result is stored in variable hours
6
marks = np.array([35, 42, 50, 58, 66, 72, 80, 88])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [35, 42, 50, 58, 66, 72, 80, 88]; the result is stored in variable marks
7
model = LinearRegression()
๐Ÿงฎ Store / Calculate Creates a Linear Regression model; the result is stored in variable model
8
model.fit(hours, marks)
๐Ÿ“ฆ Library / Data Trains (fits) the model model on the given data
9
print("Slope (m)     :", round(model.coef_[0], 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Slope (m) :", then the value of round(model.coef_[0], 3) on the screen
10
print("Intercept (c) :", round(model.intercept_, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Intercept (c) :", then the value of round(model.intercept_, 3) on the screen
11
print("R-squared     :", round(model.score(hours, marks), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "R-squared :", then the value of round(model.score(hours, marks), 4) on the screen
12
print("Predicted marks for 9 hours:", round(model.predict([[9]])[0], 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted marks for 9 hours:", then the value of round(model.predict([[9]])[0], 2) on the screen
13
plt.scatter(hours, marks, color='blue', label='Actual data')
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of hours, marks
14
plt.plot(hours, model.predict(hours), color='red', label='Best-fit line')
๐Ÿ–ฅ๏ธ Output Draws a line chart of hours, model.predict(hours)
15
plt.title("Linear Regression: Study Hours vs Marks")
๐Ÿ–ฅ๏ธ Output Writes "Linear Regression: Study Hours vs Marks" as the title of the chart
16
plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Hours" as the label of the X-axis
16
plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Marks" as the label of the Y-axis
16
plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
17
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
import matplotlib.pyplot as plt
34
from sklearn.linear_model import LinearRegression
45
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1)
hours = array([[1], [2], [3], [4], [5], [6], [7], [8]])
56
marks = np.array([35, 42, 50, 58, 66, 72, 80, 88])
marks = array([35, 42, 50, 58, 66, 72, 80, 88])
67
model = LinearRegression()
model = LinearRegression model
78
model.fit(hours, marks)
89
print("Slope (m)     :", round(model.coef_[0], 3))
Slope (m)     : 7.56
910
print("Intercept (c) :", round(model.intercept_, 3))
Intercept (c) : 27.357
1011
print("R-squared     :", round(model.score(hours, marks), 4))
R-squared     : 0.9993
1112
print("Predicted marks for 9 hours:", round(model.predict([[9]])[0], 2))
Predicted marks for 9 hours: 95.39
1213
plt.scatter(hours, marks, color='blue', label='Actual data')
1314
plt.plot(hours, model.predict(hours), color='red', label='Best-fit line')
1415
plt.title("Linear Regression: Study Hours vs Marks")
1516
plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend()
1617
plt.show()
Q26 PYTHON

Unit 6 (Advanced learners): Demonstration of k-Nearest Neighbour (KNN) classification using a Python program.

# KNN classification - fruit classifier
from sklearn.neighbors import KNeighborsClassifier
# features: [weight in grams, texture (0 = smooth, 1 = bumpy)]
X = [[140, 0], [130, 0], [150, 0], [170, 1], [160, 1], [180, 1], [135, 0], [175, 1]]
y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', 'Orange']
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X, y)
tests = [[145, 0], [165, 1], [158, 0]]
for t in tests:
    dist, idx = knn.kneighbors([t])
    print("Fruit", t, "-> predicted:", knn.predict([t])[0],
          "| 3 nearest:", [y[i] for i in idx[0]])
โ–ถ Sample Output
Fruit [145, 0] -> predicted: Apple | 3 nearest: ['Apple', 'Apple', 'Apple']
Fruit [165, 1] -> predicted: Orange | 3 nearest: ['Orange', 'Orange', 'Orange']
Fruit [158, 0] -> predicted: Orange | 3 nearest: ['Orange', 'Apple', 'Orange']
๐Ÿ’ก Explanation: KNN stores the training data and classifies a new point by a majority vote of its k nearest neighbours (Euclidean distance). k should be odd to avoid ties.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module sklearn.neighbors
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q26.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ KNN classification - fruit classifier
2
from sklearn.neighbors import KNeighborsClassifier
๐Ÿ“ฆ Library / Data Loads KNeighborsClassifier from the sklearn.neighbors module
๐Ÿ“Œ features: [weight in grams, texture (0 = smooth, 1 = bumpy)]
4
X = [[140, 0], [130, 0], [150, 0], [170, 1], [160, 1], [180, 1], [135, 0], [175, 1]]
๐Ÿงฎ Store / Calculate Stores a list [[140, 0], [130, 0], [150, 0], [170, 1], [160โ€ฆ in variable X
5
y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', 'Orange']
๐Ÿงฎ Store / Calculate Stores a list ['Apple', 'Apple', 'Apple', 'Orange', 'Orangeโ€ฆ in variable y
6
knn = KNeighborsClassifier(n_neighbors=3)
๐Ÿงฎ Store / Calculate Creates a K-Nearest-Neighbours model; the result is stored in variable knn
7
knn.fit(X, y)
๐Ÿ“ฆ Library / Data Trains (fits) the model knn on the given data
8
tests = [[145, 0], [165, 1], [158, 0]]
๐Ÿงฎ Store / Calculate Stores a list [[145, 0], [165, 1], [158, 0]] in variable tests
9
for t in tests:
๐Ÿ” Loop LOOP: takes each item of tests one-by-one into t and runs the indented block for it
10
dist, idx = knn.kneighbors([t])
๐Ÿงฎ Store / Calculate Finds the nearest neighbours; the result is stored in variables dist, idx
11
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
      "| 3 nearest:", [y[i] for i in idx[0]])
๐Ÿ–ฅ๏ธ Output Displays the text "Fruit", then the value of t, then the text "-> predicted:", then the value of knn.predict([t])[0], then the text "| 3 nearest:", then the value of [y[i] for i in idx[0]] on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
from sklearn.neighbors import KNeighborsClassifier
24
X = [[140, 0], [130, 0], [150, 0], [170, 1], [160, 1], [180, 1], [135, 0], [175, 1]]
X = [[140, 0], [130, 0], [150, 0], [170, 1], [160, 1], [180, 1], [135, โ€ฆ
35
y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', 'Orange']
y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', โ€ฆ
46
knn = KNeighborsClassifier(n_neighbors=3)
knn = KNeighborsClassifier model
57
knn.fit(X, y)
68
tests = [[145, 0], [165, 1], [158, 0]]
tests = [[145, 0], [165, 1], [158, 0]]
79
for t in tests:
next item taken
t = [145, 0]
810
dist, idx = knn.kneighbors([t])
dist = array([[5.0, 5.0, 10.0]]), idx = array([[0, 2, 6]])
911
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
1012
"| 3 nearest:", [y[i] for i in idx[0]])
1112
"| 3 nearest:", [y[i] for i in idx[0]])
1212
"| 3 nearest:", [y[i] for i in idx[0]])
1312
"| 3 nearest:", [y[i] for i in idx[0]])
1411
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
Fruit [145, 0] -> predicted: Apple | 3 nearest: ['Apple', 'Apple', 'Apple']
159
for t in tests:
next item taken
t = [165, 1]
1610
dist, idx = knn.kneighbors([t])
idx = array([[3, 4, 7]])
1711
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
1812
"| 3 nearest:", [y[i] for i in idx[0]])
1912
"| 3 nearest:", [y[i] for i in idx[0]])
2012
"| 3 nearest:", [y[i] for i in idx[0]])
2112
"| 3 nearest:", [y[i] for i in idx[0]])
2211
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
Fruit [165, 1] -> predicted: Orange | 3 nearest: ['Orange', 'Orange', 'Orange']
239
for t in tests:
next item taken
t = [158, 0]
2410
dist, idx = knn.kneighbors([t])
dist = array([[2.23606797749979, 8.0, 12.041594578792296]]), idx = array([[4, 2, 3]])
2511
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
2612
"| 3 nearest:", [y[i] for i in idx[0]])
2712
"| 3 nearest:", [y[i] for i in idx[0]])
2812
"| 3 nearest:", [y[i] for i in idx[0]])
2912
"| 3 nearest:", [y[i] for i in idx[0]])
3011
print("Fruit", t, "-> predicted:", knn.predict([t])[0],
Fruit [158, 0] -> predicted: Orange | 3 nearest: ['Orange', 'Apple', 'Orange']
319
for t in tests:
no items left โ†’ loop ends
Q27 PYTHON

Unit 6 (Advanced learners): Demonstration of k-Means clustering using a Python program.

# K-Means clustering - grouping customers
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# [annual spend (thousand Rs), visits per month]
X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10],
              [35, 5], [38, 6], [33, 5], [62, 9], [17, 3], [36, 6]])
km = KMeans(n_clusters=3, n_init=10, random_state=0)
labels = km.fit_predict(X)
print("Cluster labels :", labels)
print("Cluster centres:\n", km.cluster_centers_.round(2))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=70)
plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='red', marker='X', s=200, label='Centroids')
plt.title("K-Means Customer Segments"); plt.xlabel("Annual spend (thousand Rs)")
plt.ylabel("Visits / month"); plt.legend(); plt.show()
โ–ถ Sample Output
Cluster labels : [2 2 2 1 1 1 0 0 0 1 2 0]
Cluster centres:
 [[35.5   5.5 ]
 [58.75  9.  ]
 [16.5   2.5 ]]
Figure 1
Figure 1
๐Ÿ’ก Explanation: K-Means is unsupervised: no labels are given. It repeatedly assigns points to the nearest centroid and moves each centroid to the mean of its points until the groups stop changing.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules numpy, matplotlib.pyplot, sklearn.cluster
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q27.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ K-Means clustering - grouping customers
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
4
from sklearn.cluster import KMeans
๐Ÿ“ฆ Library / Data Loads KMeans from the sklearn.cluster module
๐Ÿ“Œ [annual spend (thousand Rs), visits per month]
6
X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10],
              [35, 5], [38, 6], [33, 5], [62, 9], [17, 3], [36, 6]])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [[15, 2], [18, 3], [16, 2], [55, 8], [60, 9],โ€ฆ; the result is stored in variable X
8
km = KMeans(n_clusters=3, n_init=10, random_state=0)
๐Ÿงฎ Store / Calculate Creates a K-Means clustering model; the result is stored in variable km
9
labels = km.fit_predict(X)
๐Ÿงฎ Store / Calculate Calls km.fit_predict(X); the result is stored in variable labels
10
print("Cluster labels :", labels)
๐Ÿ–ฅ๏ธ Output Displays the text "Cluster labels :", then the value of labels on the screen
11
print("Cluster centres:\n", km.cluster_centers_.round(2))
๐Ÿ–ฅ๏ธ Output Displays the text "Cluster centres:", then the value of km.cluster_centers_.round(2) on the screen
12
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=70)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of X[:, 0], X[:, 1]
13
plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='red', marker='X', s=200, label='Centroids')
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of km.cluster_centers_[:, 0], km.cluster_centers_[:, 1]
14
plt.title("K-Means Customer Segments"); plt.xlabel("Annual spend (thousand Rs)")
๐Ÿ–ฅ๏ธ Output Writes "K-Means Customer Segments" as the title of the chart
14
plt.title("K-Means Customer Segments"); plt.xlabel("Annual spend (thousand Rs)")
๐Ÿ–ฅ๏ธ Output Writes "Annual spend (thousand Rs)" as the label of the X-axis
15
plt.ylabel("Visits / month"); plt.legend(); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Visits / month" as the label of the Y-axis
15
plt.ylabel("Visits / month"); plt.legend(); plt.show()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
15
plt.ylabel("Visits / month"); plt.legend(); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
import numpy as np
23
import matplotlib.pyplot as plt
34
from sklearn.cluster import KMeans
46
X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10],
57
[35, 5], [38, 6], [33, 5], [62, 9], [17, 3], [36, 6]])
66
X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10],
X = array of shape (12, 2)
78
km = KMeans(n_clusters=3, n_init=10, random_state=0)
km = KMeans model
89
labels = km.fit_predict(X)
labels = array of shape (12,)
910
print("Cluster labels :", labels)
Cluster labels : [2 2 2 1 1 1 0 0 0 1 2 0]
1011
print("Cluster centres:\n", km.cluster_centers_.round(2))
Cluster centres:
 [[35.5   5.5 ]
 [58.75  9.  ]
 [16.5   2.5 ]]
1112
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=70)
1213
plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='red', marker='X', s=2
1314
plt.title("K-Means Customer Segments"); plt.xlabel("Annual spend (thousand Rs)")
1415
plt.ylabel("Visits / month"); plt.legend(); plt.show()
Q28 ACTIVITY

Unit 7: Create a chatbot for ordering ice-creams using Google Dialogflow (or Botsify / Botpress).

GOOGLE DIALOGFLOW ES  (https://dialogflow.cloud.google.com)
1. Sign in with a Google account -> Create Agent "IceCreamBot" (language English,
   time zone Asia/Kolkata) -> Create.
2. ENTITIES -> Create entity @flavour : chocolate, vanilla, butterscotch, mango
            -> Create entity @size    : small, medium, large
            -> Create entity @serving : cup, cone
3. INTENTS
   a) Default Welcome Intent - Response: "Hi! Welcome to Cool Scoops. What
      flavour would you like?"
   b) order.icecream - Training phrases: "I want a chocolate ice cream",
      "one large mango cone please", "order vanilla"
      Parameters: flavour (@flavour, REQUIRED, prompt "Which flavour?"),
                  size (@size, REQUIRED, prompt "Small, medium or large?"),
                  serving (@serving, REQUIRED, prompt "Cup or cone?")
      Response: "Your $size $flavour ice cream in a $serving is confirmed!"
   c) order.cancel - "cancel my order" -> "Your order has been cancelled."
4. Test in the right-hand "Try it now" panel.
5. Integrations -> Web Demo -> enable and copy the link (snapshot in file).
โ–ถ Sample conversation (Dialogflow test console)
User : hi
Bot  : Hi! Welcome to Cool Scoops. What flavour would you like?
User : I want a mango ice cream
Bot  : Small, medium or large?
User : large
Bot  : Cup or cone?
User : cone
Bot  : Your large mango ice cream in a cone is confirmed!
๐Ÿ’ก Explanation: Intents capture what the user wants, entities pick out important values (flavour, size) and slot-filling prompts ask for missing values. This is a rule + ML based (smart) chatbot built without code.
Q29 PYTHON

Unit 7 (Advanced learners): Creating a simple rule-based chatbot using Python.

# Rule-based ice-cream chatbot
menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65}
order = []
print("Bot: Hi! I am ScoopBot. Type 'menu', a flavour name, 'bill' or 'bye'.")
while True:
    msg = input("You: ").lower().strip()
    if msg in ('hi', 'hello', 'hey'):
        print("Bot: Hello! What would you like today?")
    elif 'menu' in msg:
        for f, p in menu.items():
            print(f"Bot:  {f.title():<13} Rs.{p}")
    elif any(f in msg for f in menu):
        flavour = [f for f in menu if f in msg][0]
        order.append(flavour)
        print(f"Bot: Added one {flavour} scoop. Anything else?")
    elif 'bill' in msg:
        total = sum(menu[f] for f in order)
        print("Bot: You ordered", ", ".join(order), "- Total Rs.", total)
    elif msg in ('bye', 'exit', 'quit'):
        print("Bot: Thank you! Enjoy your ice cream.")
        break
    else:
        print("Bot: Sorry, I did not understand. Try 'menu'.")
โ–ถ Sample Output
Bot: Hi! I am ScoopBot. Type 'menu', a flavour name, 'bill' or 'bye'.
You: hello
Bot: Hello! What would you like today?
You: menu
Bot:  Chocolate     Rs.60
Bot:  Vanilla       Rs.50
Bot:  Mango         Rs.55
Bot:  Butterscotch  Rs.65
You: I want mango
Bot: Added one mango scoop. Anything else?
You: one chocolate please
Bot: Added one chocolate scoop. Anything else?
You: strawberry?
Bot: Sorry, I did not understand. Try 'menu'.
You: bill
Bot: You ordered mango, chocolate - Total Rs. 115
You: bye
Bot: Thank you! Enjoy your ice cream.
๐Ÿ’ก Explanation: A rule-based (script) bot matches keywords with if-elif rules. It cannot understand new sentences it was not programmed for - unlike an ML-based smart bot.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ msg
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else; a for loop
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q29.py.
  3. Press F5 (Run โ†’ Run Module).
  4. When the program asks, type hello, menu, I want mango, one chocolate please, strawberry?, bill, bye (the same values as the Sample Output) and press Enter after each.
  5. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Rule-based ice-cream chatbot
2
menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65}
๐Ÿงฎ Store / Calculate Stores a dictionary {'chocolate': 60, 'vanilla': 50, 'mango': 55,โ€ฆ in variable menu
3
order = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable order
4
print("Bot: Hi! I am ScoopBot. Type 'menu', a flavour name, 'bill' or 'bye'.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Hi! I am ScoopBot. Type 'menโ€ฆ" on the screen
5
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
6
msg = input("You: ").lower().strip()
โŒจ๏ธ Input Removes extra spaces from both ends of input("You: ").lower(); the result is stored in variable msg
7
if msg in ('hi', 'hello', 'hey'):
๐Ÿ”€ Decision CHECKS whether msg is present in ('hi', 'hello', 'hey'). If True, the indented lines below run; otherwise Python jumps to the elif/else part
8
print("Bot: Hello! What would you like today?")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Hello! What would you like tโ€ฆ" on the screen
9
elif 'menu' in msg:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether 'menu' is present in msg
10
for f, p in menu.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary menu; f, p get one pair each round
11
print(f"Bot:  {f.title():<13} Rs.{p}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bot: {f.title():<13} Rs.{p}" with the values filled into { } on the screen
12
elif any(f in msg for f in menu):
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether any(f in msg for f in menu) is True
13
flavour = [f for f in menu if f in msg][0]
๐Ÿงฎ Store / Calculate Stores the item [f for f in menu if f in msg][0] in variable flavour
14
order.append(flavour)
๐Ÿงฎ Store / Calculate Adds flavour at the end of list order
15
print(f"Bot: Added one {flavour} scoop. Anything else?")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bot: Added one {flavour} scoop. Anything elโ€ฆ with the values filled into { } on the screen
16
elif 'bill' in msg:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether 'bill' is present in msg
17
total = sum(menu[f] for f in order)
๐Ÿงฎ Store / Calculate Adds up all the values in (menu[f] for f in order); the result is stored in variable total
18
print("Bot: You ordered", ", ".join(order), "- Total Rs.", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: You ordered", then the value of ", ".join(order), then the text "- Total Rs.", then the value of total on the screen
19
elif msg in ('bye', 'exit', 'quit'):
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether msg is present in ('bye', 'exit', 'quit')
20
print("Bot: Thank you! Enjoy your ice cream.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Thank you! Enjoy your ice crโ€ฆ" on the screen
21
break
๐Ÿ” Loop BREAK - leaves the loop immediately
22
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
23
print("Bot: Sorry, I did not understand. Try 'menu'.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Sorry, I did not understand.โ€ฆ" on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
12
menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65}
menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65}
23
order = []
order = []
34
print("Bot: Hi! I am ScoopBot. Type 'menu', a flavour name, 'bill' or 'bye'.")
Bot: Hi! I am ScoopBot. Type 'menu', a flavour name, 'bill' or 'bye'.
45
while True:
condition is TRUE โ†’ enters the block
56
msg = input("You: ").lower().strip()
msg = 'hello'
You: hello
67
if msg in ('hi', 'hello', 'hey'):
condition is TRUE โ†’ enters the block
78
print("Bot: Hello! What would you like today?")
Bot: Hello! What would you like today?
85
while True:
condition is TRUE โ†’ enters the block
96
msg = input("You: ").lower().strip()
msg = 'menu'
You: menu
107
if msg in ('hi', 'hello', 'hey'):
condition is FALSE โ†’ skips this block
119
elif 'menu' in msg:
condition is TRUE โ†’ enters the block
1210
for f, p in menu.items():
next item taken
f = 'chocolate', p = 60
1311
print(f"Bot:  {f.title():<13} Rs.{p}")
Bot:  Chocolate     Rs.60
1410
for f, p in menu.items():
next item taken
f = 'vanilla', p = 50
1511
print(f"Bot:  {f.title():<13} Rs.{p}")
Bot:  Vanilla       Rs.50
1610
for f, p in menu.items():
next item taken
f = 'mango', p = 55
1711
print(f"Bot:  {f.title():<13} Rs.{p}")
Bot:  Mango         Rs.55
1810
for f, p in menu.items():
next item taken
f = 'butterscotch', p = 65
1911
print(f"Bot:  {f.title():<13} Rs.{p}")
Bot:  Butterscotch  Rs.65
2010
for f, p in menu.items():
no items left โ†’ loop ends
215
while True:
condition is TRUE โ†’ enters the block
226
msg = input("You: ").lower().strip()
msg = 'i want mango'
You: I want mango
237
if msg in ('hi', 'hello', 'hey'):
condition is FALSE โ†’ skips this block
249
elif 'menu' in msg:
condition is FALSE โ†’ skips this block
2512
elif any(f in msg for f in menu):
condition is TRUE โ†’ enters the block
โžก Python jumps INTO function <genexpr>(.0=<dict_keyiterator object at 0x7f64d31bf510>)
2612
elif any(f in msg for f in menu):
condition is FALSE โ†’ skips this block
f = 'chocolate'
โฌ… function <genexpr>() ends and returns False to the caller
โžก Python jumps INTO function <genexpr>(.0=<dict_keyiterator object at 0x7f64d31bf510>)
2712
elif any(f in msg for f in menu):
condition is FALSE โ†’ skips this block
f = 'vanilla'
โฌ… function <genexpr>() ends and returns False to the caller
โžก Python jumps INTO function <genexpr>(.0=<dict_keyiterator object at 0x7f64d31bf510>)

โ€ฆ Python runs 64 more line-steps in the same way (loops repeat the same lines). Final values: menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65}, order = ['mango', 'chocolate'], msg = 'bye', f = 'butterscotch', p = 65, flavour = 'chocolate', total = 115

Q30 PYTHON

Unit 7 (Advanced learners): Program to print the POS (Parts of Speech) tags of a statement.

# POS tagging with NLTK
# one-time setup:  pip install nltk
# then in Python:  nltk.download('punkt_tab'); nltk.download('averaged_perceptron_tagger_eng')
import nltk
sentence = "Kendriya Vidyalaya students quickly built an amazing AI chatbot."
tokens = nltk.word_tokenize(sentence)
tags = nltk.pos_tag(tokens)
print("Tokens:", tokens)
print("\nWord          POS tag")
for word, tag in tags:
    print(f"{word:<13} {tag}")
โ–ถ Sample Output
Tokens: ['Kendriya', 'Vidyalaya', 'students', 'quickly', 'built', 'an', 'amazing', 'AI', 'chatbot', '.']

Word          POS tag
Kendriya      NNP
Vidyalaya     NNP
students      NNS
quickly       RB
built         VBD
an            DT
amazing       JJ
AI            NNP
chatbot       NN
.             .
๐Ÿ’ก Explanation: Tokenisation splits the sentence into words; pos_tag() labels each with a Penn Treebank tag: NNP proper noun, NNS plural noun, RB adverb, VBD past-tense verb, DT determiner, JJ adjective, NN noun.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module nltk
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xi_ai_q30.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ POS tagging with NLTK
๐Ÿ“Œ one-time setup: pip install nltk
๐Ÿ“Œ then in Python: nltk.download('punkt_tab'); nltk.download('averaged_perceptron_tagger_eng')
4
import nltk
๐Ÿ“ฆ Library / Data Loads the module nltk - natural-language processing
5
sentence = "Kendriya Vidyalaya students quickly built an amazing AI chatbot."
๐Ÿงฎ Store / Calculate Stores the text "Kendriya Vidyalaya students quickly built anโ€ฆ in variable sentence
6
tokens = nltk.word_tokenize(sentence)
๐Ÿงฎ Store / Calculate Calls nltk.word_tokenize(sentence); the result is stored in variable tokens
7
tags = nltk.pos_tag(tokens)
๐Ÿงฎ Store / Calculate Calls nltk.pos_tag(tokens); the result is stored in variable tags
8
print("Tokens:", tokens)
๐Ÿ–ฅ๏ธ Output Displays the text "Tokens:", then the value of tokens on the screen
9
print("\nWord          POS tag")
๐Ÿ–ฅ๏ธ Output Displays the text "Word POS tag" on the screen
10
for word, tag in tags:
๐Ÿ” Loop LOOP: takes each item of tags one-by-one into word, tag and runs the indented block for it
11
print(f"{word:<13} {tag}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{word:<13} {tag}" with the values filled into { } on the screen
Q31 THEORY / VIVA

Unit 7: Write an article on 'IBM Project Debater - Interesting facts'.

IBM PROJECT DEBATER - INTERESTING FACTS

* Project Debater is an AI system built by IBM Research (largely at its Haifa,
  Israel lab) - the first AI designed to debate humans on complex topics.
* Work on it began around 2012, after IBM's earlier "grand challenges" Deep Blue
  (chess, 1997) and Watson (Jeopardy!, 2011).
* In February 2019 at IBM Think, San Francisco, it debated champion debater
  Harish Natarajan on "Should we subsidise preschool?". The audience judged the
  human as the winner, but felt the AI gave them more new information.
* It searches a huge collection of newspaper and journal articles (hundreds of
  millions of sentences), picks relevant claims and evidence, and builds a
  speech in minutes.
* It uses NLP skills: argument mining, stance detection, building a persuasive
  narrative, and listening to and rebutting the opponent's points.
* Its research was published in the journal Nature (March 2021).
* Uses: helping people see both sides of an issue, policy analysis, education.

MY VIEW (3-4 lines): Project Debater shows that NLP can go beyond answering
questions to reasoning with arguments, but humans are still better at emotion,
humour and judging what matters most to the audience.
โ–ถ Result
Article of about 250 words written with title, facts, applications and personal view.
๐Ÿ’ก Explanation: This activity links Unit 7 (NLP) with real research: debating requires understanding language, finding evidence and generating coherent speech - key NLP tasks.
Q32 THEORY / VIVA

Unit 8: Summarize your insights and interpretations from the video 'Humans Need Not Apply'.

VIDEO : "Humans Need Not Apply" by CGP Grey (2014, about 15 minutes)

KEY POINTS
1. Horses were replaced by engines; the video argues many human jobs may be
   replaced by "mechanical muscles" and "mechanical minds" in a similar way.
2. General-purpose robots (e.g. Baxter) can be trained by showing, and are
   cheaper than a worker over time.
3. Self-driving cars could affect drivers - one of the largest job groups.
4. Software "bots" can do white-collar work: writing reports, legal document
   review, stock trading, even medical diagnosis.
5. Creative jobs are not completely safe - computers can already compose music.
6. Automation does not need to be perfect, only better/cheaper than humans.

MY INTERPRETATION
* Jobs with routine, repetitive tasks are most at risk.
* New jobs will appear (AI trainer, data annotator, AI ethicist), so lifelong
  learning, creativity, empathy and critical thinking are essential.
* Society must plan for re-skilling so that technology benefits everyone.
โ–ถ Conclusion
Insight: AI will change most jobs; the safest strategy is to keep learning skills that
complement AI (creativity, empathy, problem solving).
๐Ÿ’ก Explanation: The video helps students reflect on the social impact of automation and the importance of ethics and re-skilling - a key part of the AI Ethics and Values unit.
Q33 THEORY / VIVA

Unit 8: Comparative study of AI policies (guidelines and principles) established by various organisations and regulatory bodies.

+-------------------------+-----------+---------------------------------------------+
| Policy / Framework      | Body      | Key principles / features                   |
+-------------------------+-----------+---------------------------------------------+
| National Strategy for   | NITI      | #AIforAll; focus sectors: health, agri,     |
| AI (2018) & Responsible | Aayog,    | education, smart cities, mobility; RAI      |
| AI principles (2021)    | India     | principles - safety, equality, inclusivity, |
|                         |           | privacy, transparency, accountability       |
| AI Principles (2019)    | OECD      | inclusive growth, human rights & fairness,  |
|                         |           | transparency, robustness & safety,          |
|                         |           | accountability                              |
| Recommendation on the   | UNESCO    | human rights & dignity, do no harm,         |
| Ethics of AI (2021)     | (193      | environment, gender equality, privacy,      |
|                         | members)  | human oversight                             |
| AI Act (2024)           | European  | RISK-BASED law: unacceptable risk banned,   |
|                         | Union     | high-risk strictly regulated, transparency  |
|                         |           | for chatbots / deepfakes, minimal risk free |
| Blueprint for an AI     | White     | safe systems, protection from algorithmic   |
| Bill of Rights (2022)   | House,USA | discrimination, data privacy, notice &      |
|                         |           | explanation, human alternatives             |
+-------------------------+-----------+---------------------------------------------+

COMMON PRINCIPLES : Fairness (no bias), Transparency/Explainability, Privacy,
                    Safety & Security, Accountability, Human oversight
DIFFERENCE        : EU AI Act is a binding LAW; NITI Aayog, OECD and UNESCO
                    give guiding principles; India focuses on AI for inclusive
                    social development.
โ–ถ Conclusion
Conclusion: all frameworks place humans at the centre of AI; India's approach is
'AI for All' with responsible-AI principles.
๐Ÿ’ก Explanation: Comparing policies shows that the world broadly agrees on fairness, transparency, privacy, safety and accountability; they differ in whether the rules are legally binding.
Q34 ACTIVITY

Unit 8: Understanding ethical dilemmas using Moral Machine and Survival of the Best Fit.

A) MORAL MACHINE  (https://www.moralmachine.net - MIT Media Lab)
   1. Click "Start Judging". For 13 scenarios decide what a self-driving car
      with failed brakes should do (swerve or stay; passengers vs pedestrians).
   2. At the end view "Results" - compare your choices with others on:
      saving more lives, protecting passengers, upholding the law, age, fitness.
   3. Record 3 scenarios that were hardest and why.

B) SURVIVAL OF THE BEST FIT  (https://www.survivalofthebestfit.com)
   1. Play the role of a hiring manager of a growing company.
   2. First select candidates yourself, then train an AI on your past choices.
   3. Observe how the AI copies the hidden bias (e.g. preferring applicants from
      one group) and rejects equally skilled people.

REFLECTION
 * There is no single "correct" answer in moral dilemmas - values differ.
 * AI learns bias from biased historical data ("garbage in, garbage out").
 * Remedy: diverse data, fairness checks, transparency and human review.
โ–ถ Sample Observation
My Moral Machine result: strongest preference - 'saving more lives'.
Survival of the Best Fit: the AI started rejecting equally skilled applicants from one
group because my past choices were biased - bias in data became bias in AI.
๐Ÿ’ก Explanation: These games show that AI decisions need human values and that biased training data produces biased AI - the core idea of AI ethics.

๐Ÿ“ Project Work Reference (CBSE 843)

CAPSTONE PROJECT (12 marks) - as per "Project Guidelines" on page 2 of the CBSE-IBM AI Projects Cookbook
Stages to be completed in the project documentation:
  Prepare for the project -> Form a team -> Define the problem (SDG aligned) ->
  Understand your users -> Brainstorm the solution -> Design your solution.

PRACTICAL FILE must also include:
  * One certification - IBM SkillsBuild (courses listed in each unit) / any industry certification
  * At least one activity from each unit
  * One participation certificate of a bootcamp / internship

The 10 Live Projects for Class XI (regression, KNN, k-means, NLP chatbot, bias audit ...) give
ready ideas for the capstone; each can be downloaded as a complete project report.

๐ŸŽ“ Class XII โ€” Artificial Intelligence (843)

PM SHRI KV Shalimar Bagh | Session 2026-27 | 25 Practicals (12 Python programs + 13 activities) as per CBSE curriculum 2026-27

๐Ÿงญ How does the computer run a Python program and a MySQL query? (read this first)
๐Ÿ Python program
You write main.pyโžœPython interpreter checks the syntaxโžœconverts it to bytecodeโžœPVM runs it line by lineโžœOutput
  1. Execution starts at line 1 and goes top to bottom.
  2. input() stops and waits for you; what you type comes back as text - so we use int() / float() to make it a number.
  3. if / elif / else: only ONE block runs - the first whose condition is True.
  4. for repeats once per item; while repeats while the condition is True; break leaves the loop.
  5. A def block is only remembered. It runs when the function is called, then control comes back to the calling line with the return value.
  6. If an error happens inside try, Python jumps to except instead of stopping.

๐Ÿ’ก Real-life example: like a cook following a recipe card - step 1, step 2โ€ฆ; "if the dal is thick, add water" is a condition; "stir 5 times" is a loop.

๐Ÿฌ MySQL query
You type a query ;โžœMySQL parser checks itโžœoptimizer makes a planโžœreads the table rowsโžœResult table / Query OK

A SELECT is written as SELECT โ€ฆ FROM โ€ฆ WHERE โ€ฆ but MySQL executes it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
  • DDL (CREATE, ALTER, DROP) changes the structure; DML (INSERT, UPDATE, DELETE) changes the data; SELECT only reads.
  • That is why an alias made in SELECT cannot be used in WHERE (WHERE runs before SELECT), but can be used in ORDER BY.

๐Ÿ’ก Real-life example: in the school library - go to the shelf (FROM), pick only Class XII books (WHERE), make piles subject-wise (GROUP BY), keep piles with 5+ books (HAVING), note title & author (SELECT), arrange Aโ†’Z (ORDER BY).

๐Ÿ”— Python + MySQL together
connect()โžœcursor()โžœexecute(SQL)โžœfetchall() / commit()โžœclose()

Python sends the SQL text to MySQL through the cursor. SELECT results come back as a list of tuples; INSERT/UPDATE/DELETE need commit() to be saved permanently.

๐Ÿ‘‰ Below every program open ๐Ÿ” How this program runs to see the meaning of each line and a dry run with the sample input. Every project has a ๐Ÿ” How it Runs tab.

๐Ÿ“‘ CBSE Practical Assessment Scheme โ€” Class XII AI (843)

ComponentMarks
Capstone Project + Project Documentation (Project 15 + Documentation 6 + Video 4)25
Practical File (min. 6 Python programs, 3 Orange Data Mining programs, 1 Data Story)10
Lab Test (Python and Orange Data Mining)10
Viva Voce (based on Capstone Project + Practical File)5
TOTAL (Practical)50

Theory 50 + Practical 50 = 100. Every Python program below was run and its real output is shown; activities give the procedure and a model answer for the practical file.

Q1 PYTHON

Python 1: Write Python code to create a Pandas DataFrame using any sequence data type. (a) Display the DataFrame (b) Display first 5 records (c) Display last 10 records (d) Display the number of missing values in the dataset.

import pandas as pd
import numpy as np
# list of lists (sequence) -> DataFrame
records = [
    [101, 'Aditi', 17, 88, 'Delhi'],     [102, 'Bharat', 18, 76, 'Noida'],
    [103, 'Chirag', 17, np.nan, 'Delhi'], [104, 'Divya', 17, 91, None],
    [105, 'Eshan', 18, 67, 'Gurugram'],   [106, 'Fatima', 17, 82, 'Delhi'],
    [107, 'Gaurav', np.nan, 74, 'Noida'], [108, 'Harsh', 18, 59, 'Delhi'],
    [109, 'Ira', 17, 95, 'Faridabad'],    [110, 'Jatin', 17, np.nan, 'Delhi'],
    [111, 'Kavya', 18, 86, 'Noida'],      [112, 'Lakshay', 17, 71, 'Delhi']]
df = pd.DataFrame(records, columns=['RollNo', 'Name', 'Age', 'AI_Marks', 'City'])

print("(a) DataFrame:\n", df)
print("\n(b) First 5 records:\n", df.head())
print("\n(c) Last 10 records:\n", df.tail(10))
print("\n(d) Missing values in each column:\n", df.isnull().sum())
print("Total missing values:", df.isnull().sum().sum())
โ–ถ Sample Output
(a) DataFrame:
     RollNo     Name   Age  AI_Marks       City
0      101    Aditi  17.0      88.0      Delhi
1      102   Bharat  18.0      76.0      Noida
2      103   Chirag  17.0       NaN      Delhi
3      104    Divya  17.0      91.0       None
4      105    Eshan  18.0      67.0   Gurugram
5      106   Fatima  17.0      82.0      Delhi
6      107   Gaurav   NaN      74.0      Noida
7      108    Harsh  18.0      59.0      Delhi
8      109      Ira  17.0      95.0  Faridabad
9      110    Jatin  17.0       NaN      Delhi
10     111    Kavya  18.0      86.0      Noida
11     112  Lakshay  17.0      71.0      Delhi

(b) First 5 records:
    RollNo    Name   Age  AI_Marks      City
0     101   Aditi  17.0      88.0     Delhi
1     102  Bharat  18.0      76.0     Noida
2     103  Chirag  17.0       NaN     Delhi
3     104   Divya  17.0      91.0      None
4     105   Eshan  18.0      67.0  Gurugram

(c) Last 10 records:
     RollNo     Name   Age  AI_Marks       City
2      103   Chirag  17.0       NaN      Delhi
3      104    Divya  17.0      91.0       None
4      105    Eshan  18.0      67.0   Gurugram
5      106   Fatima  17.0      82.0      Delhi
6      107   Gaurav   NaN      74.0      Noida
7      108    Harsh  18.0      59.0      Delhi
8      109      Ira  17.0      95.0  Faridabad
9      110    Jatin  17.0       NaN      Delhi
10     111    Kavya  18.0      86.0      Noida
11     112  Lakshay  17.0      71.0      Delhi

(d) Missing values in each column:
 RollNo      0
Name        0
Age         1
AI_Marks    2
City        1
dtype: int64
Total missing values: 4
๐Ÿ’ก Explanation: A list of lists is converted into a DataFrame with column labels. head() shows the first 5 rows, tail(10) the last 10 rows, and isnull().sum() counts NaN/None values column-wise.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q1.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ list of lists (sequence) -> DataFrame
4
records = [
    [101, 'Aditi', 17, 88, 'Delhi'],     [102, 'Bharat', 18, 76, 'Noida'],
    [103, 'Chirag', 17, np.nan, 'Delhi'], [104, 'Divya', 17, 91, None]โ€ฆ
๐Ÿ“ฆ Library / Data Stores a list [ [101, 'Aditi', 17, 88, 'Delhi'], [102, 'Bhaโ€ฆ in variable records
11
df = pd.DataFrame(records, columns=['RollNo', 'Name', 'Age', 'AI_Marks', 'City'])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from records; the result is stored in variable df
13
print("(a) DataFrame:\n", df)
๐Ÿ–ฅ๏ธ Output Displays the text "(a) DataFrame:", then the value of df on the screen
14
print("\n(b) First 5 records:\n", df.head())
๐Ÿ–ฅ๏ธ Output Displays the text "(b) First 5 records:", then the value of df.head() on the screen
15
print("\n(c) Last 10 records:\n", df.tail(10))
๐Ÿ–ฅ๏ธ Output Displays the text "(c) Last 10 records:", then the value of df.tail(10) on the screen
16
print("\n(d) Missing values in each column:\n", df.isnull().sum())
๐Ÿ–ฅ๏ธ Output Displays the text "(d) Missing values in each column:", then the value of df.isnull().sum() on the screen
17
print("Total missing values:", df.isnull().sum().sum())
๐Ÿ–ฅ๏ธ Output Displays the text "Total missing values:", then the value of df.isnull().sum().sum() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
35
[101, 'Aditi', 17, 88, 'Delhi'],     [102, 'Bharat', 18, 76, 'Noida'],
46
[103, 'Chirag', 17, np.nan, 'Delhi'], [104, 'Divya', 17, 91, None],
57
[105, 'Eshan', 18, 67, 'Gurugram'],   [106, 'Fatima', 17, 82, 'Delhi'],
68
[107, 'Gaurav', np.nan, 74, 'Noida'], [108, 'Harsh', 18, 59, 'Delhi'],
79
[109, 'Ira', 17, 95, 'Faridabad'],    [110, 'Jatin', 17, np.nan, 'Delhi'],
810
[111, 'Kavya', 18, 86, 'Noida'],      [112, 'Lakshay', 17, 71, 'Delhi']]
94
records = [
records = [[101, 'Aditi', 17, 88, 'Delhi'], [102, 'Bharat', 18, 76, 'Noida'],โ€ฆ
1011
df = pd.DataFrame(records, columns=['RollNo', 'Name', 'Age', 'AI_Marks', 'City'])
df = DataFrame (12 rows ร— 5 columns)
1113
print("(a) DataFrame:\n", df)
(a) DataFrame:
     RollNo     Name   Age  AI_Marks       City
0      101    Aditi  17.0      88.0      Delhi
1      102   Bharat  18.0      76.0      Noida
2      103   Chirag  17.0       NaN      Delhi
3      104    Divya  17.0      91.0       None
4      105    Eshan  18.0      67.0   Gurugramโ€ฆ
1214
print("\n(b) First 5 records:\n", df.head())
(b) First 5 records:
    RollNo    Name   Age  AI_Marks      City
0     101   Aditi  17.0      88.0     Delhi
1     102  Bharat  18.0      76.0     Noida
2     103  Chirag  17.0       NaN     Delhi
3     104   Divya  17.0      91.0      None
4     105   Eshan  18.0      67.0  Gurugram
1315
print("\n(c) Last 10 records:\n", df.tail(10))
(c) Last 10 records:
     RollNo     Name   Age  AI_Marks       City
2      103   Chirag  17.0       NaN      Delhi
3      104    Divya  17.0      91.0       None
4      105    Eshan  18.0      67.0   Gurugram
5      106   Fatima  17.0      82.0      Delhi
6      107   Gaurav   NaN      74.0    โ€ฆ
1416
print("\n(d) Missing values in each column:\n", df.isnull().sum())
(d) Missing values in each column:
 RollNo      0
Name        0
Age         1
AI_Marks    2
City        1
dtype: int64
1517
print("Total missing values:", df.isnull().sum().sum())
Total missing values: 4
Q2 PYTHON

Python 2: Download a dataset in CSV form from any public open-source website. (a) Read the CSV file and convert it into a Pandas DataFrame (b) Perform statistical functions to check the data, check missing values and fill the missing data.

import pandas as pd
# health_survey.csv : sample of a school health-survey dataset (with gaps)
df = pd.read_csv("health_survey.csv")
print("Shape:", df.shape)
print(df.head())
print("\nData types:\n", df.dtypes)
print("\nStatistics:\n", df.describe().round(2))
print("\nMissing values before cleaning:\n", df.isnull().sum())

# fill numeric gaps with mean / median and text gaps with mode
df['Height_cm'] = df['Height_cm'].fillna(df['Height_cm'].mean().round(1))
df['Weight_kg'] = df['Weight_kg'].fillna(df['Weight_kg'].median())
df['Sleep_hrs'] = df['Sleep_hrs'].fillna(df['Sleep_hrs'].mean().round(1))
df['Diet'] = df['Diet'].fillna(df['Diet'].mode()[0])
print("\nMissing values after cleaning:", df.isnull().sum().sum())
print(df)
โ–ถ Sample Output
Shape: (12, 6)
     Name  Age  Height_cm  Weight_kg  Sleep_hrs     Diet
0   Aditi   16      158.0       50.0        7.5      Veg
1  Bharat   17      170.0       64.0        NaN  Non-Veg
2  Chirag   16        NaN       58.0        6.5      Veg
3   Divya   17      162.0       52.0        8.0      NaN
4   Eshan   16      175.0       80.0        6.0  Non-Veg

Data types:
 Name          object
Age            int64
Height_cm    float64
Weight_kg    float64
Sleep_hrs    float64
Diet          object
dtype: object

Statistics:
          Age  Height_cm  Weight_kg  Sleep_hrs
count  12.00      10.00      11.00      10.00
mean   16.50     165.50      62.09       6.95
std     0.52       8.14      14.02       0.83
min    16.00     155.00      45.00       5.50
25%    16.00     158.50      51.00       6.50
50%    16.50     165.00      61.00       7.00
75%    17.00     171.50      68.00       7.50
max    17.00     178.00      90.00       8.00

Missing values before cleaning:
 Name         0
Age          0
Height_cm    2
Weight_kg    1
Sleep_hrs    2
Diet         1
dtype: int64

Missing values after cleaning: 0
       Name  Age  Height_cm  Weight_kg  Sleep_hrs     Diet
0     Aditi   16      158.0       50.0        7.5      Veg
1    Bharat   17      170.0       64.0        7.0  Non-Veg
2    Chirag   16      165.5       58.0        6.5      Veg
3     Divya   17      162.0       52.0        8.0      Veg
4     Eshan   16      175.0       80.0        6.0  Non-Veg
5    Fatima   17      155.0       61.0        7.0      Veg
6    Gaurav   16      168.0       61.0        7.5      Veg
7     Harsh   17      172.0       90.0        5.5  Non-Veg
8       Ira   16      160.0       47.0        8.0      Veg
9     Jatin   17      165.5       66.0        7.0      Veg
10    Kavya   16      157.0       45.0        7.0      Veg
11  Lakshay   17      178.0       70.0        6.5  Non-Veg
๐Ÿ’ก Explanation: Real datasets have missing values. Numeric gaps are commonly filled with the mean (or median if there are outliers) and categorical gaps with the mode. Public sources: data.gov.in, Kaggle, UCI ML Repository.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q2.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
๐Ÿ“Œ health_survey.csv : sample of a school health-survey dataset (with gaps)
3
df = pd.read_csv("health_survey.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "health_survey.csv" into a DataFrame (table); the result is stored in variable df
4
print("Shape:", df.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape:", then the value of df.shape on the screen
5
print(df.head())
๐Ÿ–ฅ๏ธ Output Displays the value of df.head() on the screen
6
print("\nData types:\n", df.dtypes)
๐Ÿ–ฅ๏ธ Output Displays the text "Data types:", then the value of df.dtypes on the screen
7
print("\nStatistics:\n", df.describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays the text "Statistics:", then the value of df.describe().round(2) on the screen
8
print("\nMissing values before cleaning:\n", df.isnull().sum())
๐Ÿ–ฅ๏ธ Output Displays the text "Missing values before cleaning:", then the value of df.isnull().sum() on the screen
๐Ÿ“Œ fill numeric gaps with mean / median and text gaps with mode
11
df['Height_cm'] = df['Height_cm'].fillna(df['Height_cm'].mean().round(1))
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df['Height_cm'] with df['Height_cm'].mean().round(1); the result is put into df['Height_cm'] (item 'Height_cm' of df)
12
df['Weight_kg'] = df['Weight_kg'].fillna(df['Weight_kg'].median())
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df['Weight_kg'] with df['Weight_kg'].median(); the result is put into df['Weight_kg'] (item 'Weight_kg' of df)
13
df['Sleep_hrs'] = df['Sleep_hrs'].fillna(df['Sleep_hrs'].mean().round(1))
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df['Sleep_hrs'] with df['Sleep_hrs'].mean().round(1); the result is put into df['Sleep_hrs'] (item 'Sleep_hrs' of df)
14
df['Diet'] = df['Diet'].fillna(df['Diet'].mode()[0])
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df['Diet'] with df['Diet'].mode()[0]; the result is put into df['Diet'] (item 'Diet' of df)
15
print("\nMissing values after cleaning:", df.isnull().sum().sum())
๐Ÿ–ฅ๏ธ Output Displays the text "Missing values after cleaning:", then the value of df.isnull().sum().sum() on the screen
16
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
23
df = pd.read_csv("health_survey.csv")
df = DataFrame (12 rows ร— 6 columns)
34
print("Shape:", df.shape)
Shape: (12, 6)
45
print(df.head())
     Name  Age  Height_cm  Weight_kg  Sleep_hrs     Diet
0   Aditi   16      158.0       50.0        7.5      Veg
1  Bharat   17      170.0       64.0        NaN  Non-Veg
2  Chirag   16        NaN       58.0        6.5      Veg
3   Divya   17      162.0       52.0        8.0      NaN
4   Eshan   โ€ฆ
56
print("\nData types:\n", df.dtypes)
Data types:
 Name          object
Age            int64
Height_cm    float64
Weight_kg    float64
Sleep_hrs    float64
Diet          object
dtype: object
67
print("\nStatistics:\n", df.describe().round(2))
Statistics:
          Age  Height_cm  Weight_kg  Sleep_hrs
count  12.00      10.00      11.00      10.00
mean   16.50     165.50      62.09       6.95
std     0.52       8.14      14.02       0.83
min    16.00     155.00      45.00       5.50
25%    16.00     158.50      51.00       6.50
50%    โ€ฆ
78
print("\nMissing values before cleaning:\n", df.isnull().sum())
Missing values before cleaning:
 Name         0
Age          0
Height_cm    2
Weight_kg    1
Sleep_hrs    2
Diet         1
dtype: int64
811
df['Height_cm'] = df['Height_cm'].fillna(df['Height_cm'].mean().round(1))
912
df['Weight_kg'] = df['Weight_kg'].fillna(df['Weight_kg'].median())
1013
df['Sleep_hrs'] = df['Sleep_hrs'].fillna(df['Sleep_hrs'].mean().round(1))
1114
df['Diet'] = df['Diet'].fillna(df['Diet'].mode()[0])
1215
print("\nMissing values after cleaning:", df.isnull().sum().sum())
Missing values after cleaning: 0
1316
print(df)
       Name  Age  Height_cm  Weight_kg  Sleep_hrs     Diet
0     Aditi   16      158.0       50.0        7.5      Veg
1    Bharat   17      170.0       64.0        7.0  Non-Veg
2    Chirag   16      165.5       58.0        6.5      Veg
3     Divya   17      162.0       52.0        8.0      Veg
4 โ€ฆ
Q3 PYTHON

Python 3: Import data from a CSV file into a DataFrame, process it and export the result to a new CSV file.

import pandas as pd
df = pd.read_csv("health_survey.csv")                    # IMPORT
df = df.dropna()                                         # keep complete rows only
df['BMI'] = (df['Weight_kg'] / (df['Height_cm'] / 100) ** 2).round(1)
df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100],
                      labels=['Underweight', 'Normal', 'Overweight', 'Obese'])
print(df[['Name', 'Height_cm', 'Weight_kg', 'BMI', 'Status']])
df.to_csv("bmi_report.csv", index=False)                 # EXPORT
print("\nExported", len(df), "rows to bmi_report.csv")
check = pd.read_csv("bmi_report.csv")                    # verify
print("Columns in exported file:", list(check.columns))
โ–ถ Sample Output
       Name  Height_cm  Weight_kg   BMI       Status
0     Aditi      158.0       50.0  20.0       Normal
4     Eshan      175.0       80.0  26.1   Overweight
6    Gaurav      168.0       61.0  21.6       Normal
7     Harsh      172.0       90.0  30.4        Obese
8       Ira      160.0       47.0  18.4  Underweight
11  Lakshay      178.0       70.0  22.1       Normal

Exported 6 rows to bmi_report.csv
Columns in exported file: ['Name', 'Age', 'Height_cm', 'Weight_kg', 'Sleep_hrs', 'Diet', 'BMI', 'Status']
๐Ÿ’ก Explanation: read_csv() imports and to_csv() exports. index=False avoids writing the row numbers as an extra column. pd.cut() converts a number into categories (binning).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module pandas
โžœ
โ‘ข OUTPUTprints the result on the screen, saves data in a file
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q3.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
df = pd.read_csv("health_survey.csv")                    # IMPORT
๐Ÿ“ฆ Library / Data Reads the CSV file "health_survey.csv" into a DataFrame (table); the result is stored in variable df
3
df = df.dropna()                                         # keep complete rows only
๐Ÿ“ฆ Library / Data Removes the rows having missing values from df; the result is stored in variable df
4
df['BMI'] = (df['Weight_kg'] / (df['Height_cm'] / 100) ** 2).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of df['Weight_kg'] / (df['Height_cm'] / 100) ** 2 to 1 decimal places; the result is put into df['BMI'] (item 'BMI' of df)
5
df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100],
                      labels=['Underweight', 'Normal', 'Overweight', 'Obese'])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df['Status'] (item 'Status' of df)
7
print(df[['Name', 'Height_cm', 'Weight_kg', 'BMI', 'Status']])
๐Ÿ–ฅ๏ธ Output Displays the value of df[['Name', 'Height_cm', 'Weight_kg', 'BMI', โ€ฆ on the screen
8
df.to_csv("bmi_report.csv", index=False)                 # EXPORT
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "bmi_report.csv"
9
print("\nExported", len(df), "rows to bmi_report.csv")
๐Ÿ–ฅ๏ธ Output Displays the text "Exported", then the value of len(df), then the text "rows to bmi_report.csv" on the screen
10
check = pd.read_csv("bmi_report.csv")                    # verify
๐Ÿ“ฆ Library / Data Reads the CSV file "bmi_report.csv" into a DataFrame (table); the result is stored in variable check
11
print("Columns in exported file:", list(check.columns))
๐Ÿ–ฅ๏ธ Output Displays the text "Columns in exported file:", then the value of list(check.columns) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
df = pd.read_csv("health_survey.csv")                    # IMPORT
df = DataFrame (12 rows ร— 6 columns)
33
df = df.dropna()                                         # keep complete rows only
df = DataFrame (6 rows ร— 6 columns)
44
df['BMI'] = (df['Weight_kg'] / (df['Height_cm'] / 100) ** 2).round(1)
df = DataFrame (6 rows ร— 7 columns)
55
df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100],
66
labels=['Underweight', 'Normal', 'Overweight', 'Obese'])
75
df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100],
df = DataFrame (6 rows ร— 8 columns)
87
print(df[['Name', 'Height_cm', 'Weight_kg', 'BMI', 'Status']])
       Name  Height_cm  Weight_kg   BMI       Status
0     Aditi      158.0       50.0  20.0       Normal
4     Eshan      175.0       80.0  26.1   Overweight
6    Gaurav      168.0       61.0  21.6       Normal
7     Harsh      172.0       90.0  30.4        Obese
8       Ira      160.0       47.โ€ฆ
98
df.to_csv("bmi_report.csv", index=False)                 # EXPORT
109
print("\nExported", len(df), "rows to bmi_report.csv")
Exported 6 rows to bmi_report.csv
1110
check = pd.read_csv("bmi_report.csv")                    # verify
check = DataFrame (6 rows ร— 8 columns)
1211
print("Columns in exported file:", list(check.columns))
Columns in exported file: ['Name', 'Age', 'Height_cm', 'Weight_kg', 'Sleep_hrs', 'Diet', 'BMI', 'Status']
Q4 PYTHON

Python 4: Handle missing values in a dataset using dropna(), fillna() and interpolate().

import pandas as pd
import numpy as np
aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    'AQI': [210, np.nan, 245, 260, np.nan, 300, 280],
                    'Temp': [31, 30, np.nan, 29, 28, np.nan, 27]})
print("Original:\n", aqi)
print("\n1. dropna() - remove rows with any missing value:\n", aqi.dropna())
print("\n2. fillna(0):\n", aqi.fillna(0))
print("\n3. fillna(column mean):\n", aqi.fillna(aqi[['AQI', 'Temp']].mean().round(1)))
print("\n4. ffill() - carry previous value forward:\n", aqi.ffill())
print("\n5. interpolate() - estimate from neighbours:\n", aqi.set_index('Day').interpolate())
โ–ถ Sample Output
Original:
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue    NaN  30.0
2  Wed  245.0   NaN
3  Thu  260.0  29.0
4  Fri    NaN  28.0
5  Sat  300.0   NaN
6  Sun  280.0  27.0

1. dropna() - remove rows with any missing value:
    Day    AQI  Temp
0  Mon  210.0  31.0
3  Thu  260.0  29.0
6  Sun  280.0  27.0

2. fillna(0):
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue    0.0  30.0
2  Wed  245.0   0.0
3  Thu  260.0  29.0
4  Fri    0.0  28.0
5  Sat  300.0   0.0
6  Sun  280.0  27.0

3. fillna(column mean):
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue  259.0  30.0
2  Wed  245.0  29.0
3  Thu  260.0  29.0
4  Fri  259.0  28.0
5  Sat  300.0  29.0
6  Sun  280.0  27.0

4. ffill() - carry previous value forward:
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue  210.0  30.0
2  Wed  245.0  30.0
3  Thu  260.0  29.0
4  Fri  260.0  28.0
5  Sat  300.0  28.0
6  Sun  280.0  27.0

5. interpolate() - estimate from neighbours:
        AQI  Temp
Day             
Mon  210.0  31.0
Tue  227.5  30.0
Wed  245.0  29.5
Thu  260.0  29.0
Fri  280.0  28.0
Sat  300.0  27.5
Sun  280.0  27.0
๐Ÿ’ก Explanation: Choice of method depends on the data: dropna() loses rows, fillna(mean) keeps the average, ffill() repeats the last value and interpolate() estimates a value between neighbours - best for time-series like AQI.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, numpy
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q4.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
2
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
3
aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    'AQI': [210, np.nan, 245, 260, np.nan, 300, 280],
         โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'โ€ฆ; the result is stored in variable aqi
6
print("Original:\n", aqi)
๐Ÿ–ฅ๏ธ Output Displays the text "Original:", then the value of aqi on the screen
7
print("\n1. dropna() - remove rows with any missing value:\n", aqi.dropna())
๐Ÿ–ฅ๏ธ Output Displays the text "1. dropna() - remove rows with anโ€ฆ", then the value of aqi.dropna() on the screen
8
print("\n2. fillna(0):\n", aqi.fillna(0))
๐Ÿ–ฅ๏ธ Output Displays the text "2. fillna(0):", then the value of aqi.fillna(0) on the screen
9
print("\n3. fillna(column mean):\n", aqi.fillna(aqi[['AQI', 'Temp']].mean().round(1)))
๐Ÿ–ฅ๏ธ Output Displays the text "3. fillna(column mean):", then the value of aqi.fillna(aqi[['AQI', 'Temp']].mean().round(โ€ฆ on the screen
10
print("\n4. ffill() - carry previous value forward:\n", aqi.ffill())
๐Ÿ–ฅ๏ธ Output Displays the text "4. ffill() - carry previous valueโ€ฆ", then the value of aqi.ffill() on the screen
11
print("\n5. interpolate() - estimate from neighbours:\n", aqi.set_index('Day').interpolate())
๐Ÿ–ฅ๏ธ Output Displays the text "5. interpolate() - estimate from โ€ฆ", then the value of aqi.set_index('Day').interpolate() on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import pandas as pd
22
import numpy as np
33
aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
44
'AQI': [210, np.nan, 245, 260, np.nan, 300, 280],
55
'Temp': [31, 30, np.nan, 29, 28, np.nan, 27]})
63
aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
aqi = DataFrame (7 rows ร— 3 columns)
76
print("Original:\n", aqi)
Original:
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue    NaN  30.0
2  Wed  245.0   NaN
3  Thu  260.0  29.0
4  Fri    NaN  28.0
5  Sat  300.0   NaN
6  Sun  280.0  27.0
87
print("\n1. dropna() - remove rows with any missing value:\n", aqi.dropna())
1. dropna() - remove rows with any missing value:
    Day    AQI  Temp
0  Mon  210.0  31.0
3  Thu  260.0  29.0
6  Sun  280.0  27.0
98
print("\n2. fillna(0):\n", aqi.fillna(0))
2. fillna(0):
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue    0.0  30.0
2  Wed  245.0   0.0
3  Thu  260.0  29.0
4  Fri    0.0  28.0
5  Sat  300.0   0.0
6  Sun  280.0  27.0
109
print("\n3. fillna(column mean):\n", aqi.fillna(aqi[['AQI', 'Temp']].mean().round(1)))
3. fillna(column mean):
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue  259.0  30.0
2  Wed  245.0  29.0
3  Thu  260.0  29.0
4  Fri  259.0  28.0
5  Sat  300.0  29.0
6  Sun  280.0  27.0
1110
print("\n4. ffill() - carry previous value forward:\n", aqi.ffill())
4. ffill() - carry previous value forward:
    Day    AQI  Temp
0  Mon  210.0  31.0
1  Tue  210.0  30.0
2  Wed  245.0  30.0
3  Thu  260.0  29.0
4  Fri  260.0  28.0
5  Sat  300.0  28.0
6  Sun  280.0  27.0
1211
print("\n5. interpolate() - estimate from neighbours:\n", aqi.set_index('Day').interpolate
5. interpolate() - estimate from neighbours:
        AQI  Temp
Day             
Mon  210.0  31.0
Tue  227.5  30.0
Wed  245.0  29.5
Thu  260.0  29.0
Fri  280.0  28.0
Sat  300.0  27.5
Sun  280.0  27.0
Q5 PYTHON

Python 5: Python code to evaluate a classification model - confusion matrix, accuracy, precision, recall and F1 score.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score,
                             recall_score, f1_score, classification_report)
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, test_size=0.25, random_state=7)
model = LogisticRegression(max_iter=5000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Accuracy :", round(accuracy_score(y_test, y_pred), 4))
print("Precision:", round(precision_score(y_test, y_pred), 4))
print("Recall   :", round(recall_score(y_test, y_pred), 4))
print("F1 Score :", round(f1_score(y_test, y_pred), 4))
print("\n", classification_report(y_test, y_pred, target_names=data.target_names))
โ–ถ Sample Output
Confusion Matrix:
 [[39  6]
 [ 1 97]]
Accuracy : 0.951
Precision: 0.9417
Recall   : 0.9898
F1 Score : 0.9652

               precision    recall  f1-score   support

   malignant       0.97      0.87      0.92        45
      benign       0.94      0.99      0.97        98

    accuracy                           0.95       143
   macro avg       0.96      0.93      0.94       143
weighted avg       0.95      0.95      0.95       143
๐Ÿ’ก Explanation: The model is trained on 75% data and evaluated on unseen 25% (hold-out validation). In medical diagnosis, Recall is very important because a False Negative (missing a disease) is dangerous.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules sklearn.datasets, sklearn.model_selection, sklearn.linear_model, sklearn.metrics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q5.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
from sklearn.datasets import load_breast_cancer
๐Ÿ“ฆ Library / Data Loads load_breast_cancer from the sklearn.datasets module
2
from sklearn.model_selection import train_test_split
๐Ÿ“ฆ Library / Data Loads train_test_split from the sklearn.model_selection module
3
from sklearn.linear_model import LogisticRegression
๐Ÿ“ฆ Library / Data Loads LogisticRegression from the sklearn.linear_model module
4
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score,
                             recall_score, f1_score, classification_report)
๐Ÿ“ฆ Library / Data Loads confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, classification_report from the sklearn.metrics module
6
data = load_breast_cancer()
๐Ÿงฎ Store / Calculate Loads the built-in breast cancer dataset; the result is stored in variable data
7
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, test_size=0.25, random_state=7)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_train, X_test, y_train, y_test
9
model = LogisticRegression(max_iter=5000)
๐Ÿงฎ Store / Calculate Creates a Logistic Regression model; the result is stored in variable model
10
model.fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model model on the given data
11
y_pred = model.predict(X_test)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for X_test; the result is stored in variable y_pred
12
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
๐Ÿ–ฅ๏ธ Output Displays the text "Confusion Matrix:", then the value of confusion_matrix(y_test, y_pred) on the screen
13
print("Accuracy :", round(accuracy_score(y_test, y_pred), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Accuracy :", then the value of round(accuracy_score(y_test, y_pred), 4) on the screen
14
print("Precision:", round(precision_score(y_test, y_pred), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Precision:", then the value of round(precision_score(y_test, y_pred), 4) on the screen
15
print("Recall   :", round(recall_score(y_test, y_pred), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Recall :", then the value of round(recall_score(y_test, y_pred), 4) on the screen
16
print("F1 Score :", round(f1_score(y_test, y_pred), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "F1 Score :", then the value of round(f1_score(y_test, y_pred), 4) on the screen
17
print("\n", classification_report(y_test, y_pred, target_names=data.target_names))
๐Ÿ–ฅ๏ธ Output Displays a blank, then the value of classification_report(y_test, y_pred, target_โ€ฆ on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
from sklearn.datasets import load_breast_cancer
22
from sklearn.model_selection import train_test_split
33
from sklearn.linear_model import LogisticRegression
44
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score,
56
data = load_breast_cancer()
data = Bunch model
67
X_train, X_test, y_train, y_test = train_test_split(
78
data.data, data.target, test_size=0.25, random_state=7)
87
X_train, X_test, y_train, y_test = train_test_split(
X_train = array of shape (426, 30), X_test = array of shape (143, 30), y_train = array of shape (426,), y_test = array of shape (143,)
99
model = LogisticRegression(max_iter=5000)
model = LogisticRegression model
1010
model.fit(X_train, y_train)
1111
y_pred = model.predict(X_test)
y_pred = array of shape (143,)
1212
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
Confusion Matrix:
 [[39  6]
 [ 1 97]]
1313
print("Accuracy :", round(accuracy_score(y_test, y_pred), 4))
Accuracy : 0.951
1414
print("Precision:", round(precision_score(y_test, y_pred), 4))
Precision: 0.9417
1515
print("Recall   :", round(recall_score(y_test, y_pred), 4))
Recall   : 0.9898
1616
print("F1 Score :", round(f1_score(y_test, y_pred), 4))
F1 Score : 0.9652
1717
print("\n", classification_report(y_test, y_pred, target_names=data.target_names))
               precision    recall  f1-score   support

   malignant       0.97      0.87      0.92        45
      benign       0.94      0.99      0.97        98

    accuracy                           0.95       143
   macro avg       0.96      0.93      0.94       143
weighted avg       0.95โ€ฆ
Q6 PYTHON

Python 6: Python code to evaluate a regression model using MAE, MSE, RMSE and R-squared.

import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
actual    = np.array([250, 300, 320, 410, 380, 450, 500, 520])   # house price (lakh)
predicted = np.array([260, 290, 330, 400, 395, 430, 510, 540])
mae = mean_absolute_error(actual, predicted)
mse = mean_squared_error(actual, predicted)
rmse = np.sqrt(mse)
r2 = r2_score(actual, predicted)
print("Errors (actual - predicted):", actual - predicted)
print("MAE  =", round(mae, 2))
print("MSE  =", round(mse, 2))
print("RMSE =", round(rmse, 2))
print("R2   =", round(r2, 4))
# manual check of MSE
print("Manual MSE =", np.mean((actual - predicted) ** 2))
โ–ถ Sample Output
Errors (actual - predicted): [-10  10 -10  10 -15  20 -10 -20]
MAE  = 13.12
MSE  = 190.62
RMSE = 13.81
R2   = 0.9768
Manual MSE = 190.625
๐Ÿ’ก Explanation: MSE = mean of squared errors (penalises big errors), RMSE = square root of MSE (same unit as the data), MAE = mean absolute error, R2 = how much variation the model explains (1 = perfect).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules numpy, sklearn.metrics
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q6.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
1
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
2
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
๐Ÿ“ฆ Library / Data Loads mean_absolute_error, mean_squared_error, r2_score from the sklearn.metrics module
3
actual    = np.array([250, 300, 320, 410, 380, 450, 500, 520])   # house price (lakh)
๐Ÿ“ฆ Library / Data Makes a NumPy array from [250, 300, 320, 410, 380, 450, 500, 520]; the result is stored in variable actual
4
predicted = np.array([260, 290, 330, 400, 395, 430, 510, 540])
๐Ÿ“ฆ Library / Data Makes a NumPy array from [260, 290, 330, 400, 395, 430, 510, 540]; the result is stored in variable predicted
5
mae = mean_absolute_error(actual, predicted)
๐Ÿงฎ Store / Calculate Finds MAE = average of absolute errors; the result is stored in variable mae
6
mse = mean_squared_error(actual, predicted)
๐Ÿงฎ Store / Calculate Finds MSE = average of squared errors; the result is stored in variable mse
7
rmse = np.sqrt(mse)
๐Ÿ“ฆ Library / Data Finds the square root of mse; the result is stored in variable rmse
8
r2 = r2_score(actual, predicted)
๐Ÿงฎ Store / Calculate Finds Rยฒ = how well the line fits (1 is perfect); the result is stored in variable r2
9
print("Errors (actual - predicted):", actual - predicted)
๐Ÿ–ฅ๏ธ Output Displays the text "Errors (actual - predicted):", then the value of actual - predicted on the screen
10
print("MAE  =", round(mae, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "MAE =", then the value of round(mae, 2) on the screen
11
print("MSE  =", round(mse, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "MSE =", then the value of round(mse, 2) on the screen
12
print("RMSE =", round(rmse, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "RMSE =", then the value of round(rmse, 2) on the screen
13
print("R2   =", round(r2, 4))
๐Ÿ–ฅ๏ธ Output Displays the text "R2 =", then the value of round(r2, 4) on the screen
๐Ÿ“Œ manual check of MSE
15
print("Manual MSE =", np.mean((actual - predicted) ** 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Manual MSE =", then the value of np.mean((actual - predicted) ** 2) on the screen
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import numpy as np
22
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
33
actual    = np.array([250, 300, 320, 410, 380, 450, 500, 520])   # house price (lakh)
actual = array([250, 300, 320, 410, 380, 450, 500, 520])
44
predicted = np.array([260, 290, 330, 400, 395, 430, 510, 540])
predicted = array([260, 290, 330, 400, 395, 430, 510, 540])
55
mae = mean_absolute_error(actual, predicted)
mae = 13.125
66
mse = mean_squared_error(actual, predicted)
mse = 190.625
77
rmse = np.sqrt(mse)
rmse = np.float64(13.806701271484076)
88
r2 = r2_score(actual, predicted)
r2 = 0.9767840152235966
99
print("Errors (actual - predicted):", actual - predicted)
Errors (actual - predicted): [-10  10 -10  10 -15  20 -10 -20]
1010
print("MAE  =", round(mae, 2))
MAE  = 13.12
1111
print("MSE  =", round(mse, 2))
MSE  = 190.62
1212
print("RMSE =", round(rmse, 2))
RMSE = 13.81
1313
print("R2   =", round(r2, 4))
R2   = 0.9768
1415
print("Manual MSE =", np.mean((actual - predicted) ** 2))
Manual MSE = 190.625
Q7 PYTHON

Python 7 (Optional): Demonstration of train-test split in Linear Regression using Python.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
area = np.array([600, 750, 800, 900, 1000, 1100, 1200, 1350, 1500, 1600, 1750, 1900]).reshape(-1, 1)
price = np.array([32, 39, 41, 47, 52, 56, 61, 68, 76, 80, 88, 95])      # lakh Rs
X_train, X_test, y_train, y_test = train_test_split(area, price, test_size=0.25, random_state=1)
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print("Train size:", len(X_train), " Test size:", len(X_test))
print("Equation : Price = %.4f x Area + %.3f" % (model.coef_[0], model.intercept_))
for a, y, p in zip(X_test.ravel(), y_test, pred):
    print(f"Area {a:5} sq ft  actual {y:3}  predicted {p:6.2f}")
print("RMSE on test data:", round(np.sqrt(mean_squared_error(y_test, pred)), 3))
print("R2 on test data  :", round(r2_score(y_test, pred), 4))
plt.scatter(X_train, y_train, label='Train'); plt.scatter(X_test, y_test, color='red', label='Test')
plt.plot(area, model.predict(area), color='green', label='Regression line')
plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in Linear Regression')
plt.legend(); plt.show()
โ–ถ Sample Output
Train size: 9  Test size: 3
Equation : Price = 0.0486 x Area + 2.631
Area   800 sq ft  actual  41  predicted  41.53
Area   900 sq ft  actual  47  predicted  46.39
Area  1000 sq ft  actual  52  predicted  51.25
RMSE on test data: 0.634
R2 on test data  : 0.9801
Figure 1
Figure 1
๐Ÿ’ก Explanation: The model learns only from the training set and is judged on the test set it has never seen - this checks whether the model generalises instead of memorising (overfitting).
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; modules numpy, matplotlib.pyplot, sklearn.model_selection, sklearn.linear_model, sklearn.metrics
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q7.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
2
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
3
from sklearn.model_selection import train_test_split
๐Ÿ“ฆ Library / Data Loads train_test_split from the sklearn.model_selection module
4
from sklearn.linear_model import LinearRegression
๐Ÿ“ฆ Library / Data Loads LinearRegression from the sklearn.linear_model module
5
from sklearn.metrics import mean_squared_error, r2_score
๐Ÿ“ฆ Library / Data Loads mean_squared_error, r2_score from the sklearn.metrics module
6
area = np.array([600, 750, 800, 900, 1000, 1100, 1200, 1350, 1500, 1600, 1750, 1900]).reshape(-1, 1)
๐Ÿ“ฆ Library / Data Changes the shape of np.array([600, 750, 800, 900, 1000, 1100, 120โ€ฆ to (-1, 1); the result is stored in variable area
7
price = np.array([32, 39, 41, 47, 52, 56, 61, 68, 76, 80, 88, 95])      # lakh Rs
๐Ÿ“ฆ Library / Data Makes a NumPy array from [32, 39, 41, 47, 52, 56, 61, 68, 76, 80, 88, โ€ฆ; the result is stored in variable price
8
X_train, X_test, y_train, y_test = train_test_split(area, price, test_size=0.25, random_state=1)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_train, X_test, y_train, y_test
9
model = LinearRegression().fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model LinearRegression() on the given data; the result is stored in variable model
10
pred = model.predict(X_test)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for X_test; the result is stored in variable pred
11
print("Train size:", len(X_train), " Test size:", len(X_test))
๐Ÿ–ฅ๏ธ Output Displays the text "Train size:", then the value of len(X_train), then the text "Test size:", then the value of len(X_test) on the screen
12
print("Equation : Price = %.4f x Area + %.3f" % (model.coef_[0], model.intercept_))
๐Ÿ–ฅ๏ธ Output Displays the value of "Equation : Price = %.4f x Area + %.3f" % (moโ€ฆ on the screen
13
for a, y, p in zip(X_test.ravel(), y_test, pred):
๐Ÿ” Loop LOOP that walks through X_test.ravel(), y_test, pred together; a, y, p get one item from each
14
print(f"Area {a:5} sq ft  actual {y:3}  predicted {p:6.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Area {a:5} sq ft actual {y:3} predicted {p:โ€ฆ with the values filled into { } on the screen
15
print("RMSE on test data:", round(np.sqrt(mean_squared_error(y_test, pred)), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "RMSE on test data:", then the value of round(np.sqrt(mean_squared_error(y_test, predโ€ฆ on the screen
16
print("R2 on test data  :", round(r2_score(y_test, pred), 4))
๐Ÿ–ฅ๏ธ Output Displays the text "R2 on test data :", then the value of round(r2_score(y_test, pred), 4) on the screen
17
plt.scatter(X_train, y_train, label='Train'); plt.scatter(X_test, y_test, color='red', label='Test')
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of X_train, y_train
17
plt.scatter(X_train, y_train, label='Train'); plt.scatter(X_test, y_test, color='red', label='Test')
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of X_test, y_test
18
plt.plot(area, model.predict(area), color='green', label='Regression line')
๐Ÿ–ฅ๏ธ Output Draws a line chart of area, model.predict(area)
19
plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in Linear Regression')
๐Ÿ–ฅ๏ธ Output Writes 'Area (sq ft)' as the label of the X-axis
19
plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in Linear Regression')
๐Ÿ–ฅ๏ธ Output Writes 'Price (lakh Rs)' as the label of the Y-axis
19
plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in Linear Regression')
๐Ÿ–ฅ๏ธ Output Writes 'Train-Test Split in Linear Regression' as the title of the chart
20
plt.legend(); plt.show()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
20
plt.legend(); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
11
import numpy as np
22
import matplotlib.pyplot as plt
33
from sklearn.model_selection import train_test_split
44
from sklearn.linear_model import LinearRegression
55
from sklearn.metrics import mean_squared_error, r2_score
66
area = np.array([600, 750, 800, 900, 1000, 1100, 1200, 1350, 1500, 1600, 1750, 1900]).resh
area = array of shape (12, 1)
77
price = np.array([32, 39, 41, 47, 52, 56, 61, 68, 76, 80, 88, 95])      # lakh Rs
price = array of shape (12,)
88
X_train, X_test, y_train, y_test = train_test_split(area, price, test_size=0.25, random_st
X_train = array of shape (9, 1), X_test = array([[800], [900], [1000]]), y_train = array of shape (9,), y_test = array([41, 47, 52])
99
model = LinearRegression().fit(X_train, y_train)
model = LinearRegression model
1010
pred = model.predict(X_test)
pred = array([41.52945428261654, 46.391760028912174, 51.2540657752078])
1111
print("Train size:", len(X_train), " Test size:", len(X_test))
Train size: 9  Test size: 3
1212
print("Equation : Price = %.4f x Area + %.3f" % (model.coef_[0], model.intercept_))
Equation : Price = 0.0486 x Area + 2.631
1313
for a, y, p in zip(X_test.ravel(), y_test, pred):
next item taken
a = np.int64(800), y = np.int64(41), p = np.float64(41.52945428261654)
1414
print(f"Area {a:5} sq ft  actual {y:3}  predicted {p:6.2f}")
Area   800 sq ft  actual  41  predicted  41.53
1513
for a, y, p in zip(X_test.ravel(), y_test, pred):
next item taken
a = np.int64(900), y = np.int64(47), p = np.float64(46.391760028912174)
1614
print(f"Area {a:5} sq ft  actual {y:3}  predicted {p:6.2f}")
Area   900 sq ft  actual  47  predicted  46.39
1713
for a, y, p in zip(X_test.ravel(), y_test, pred):
next item taken
a = np.int64(1000), y = np.int64(52), p = np.float64(51.2540657752078)
1814
print(f"Area {a:5} sq ft  actual {y:3}  predicted {p:6.2f}")
Area  1000 sq ft  actual  52  predicted  51.25
1913
for a, y, p in zip(X_test.ravel(), y_test, pred):
no items left โ†’ loop ends
2015
print("RMSE on test data:", round(np.sqrt(mean_squared_error(y_test, pred)), 3))
RMSE on test data: 0.634
2116
print("R2 on test data  :", round(r2_score(y_test, pred), 4))
R2 on test data  : 0.9801
2217
plt.scatter(X_train, y_train, label='Train'); plt.scatter(X_test, y_test, color='red', lab
2318
plt.plot(area, model.predict(area), color='green', label='Regression line')
2419
plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in 
2520
plt.legend(); plt.show()
Q8 PYTHON

Python 8: Build a TensorFlow model to convert Celsius to Fahrenheit (a single-neuron neural network that learns the formula from data).

import numpy as np
import tensorflow as tf
tf.random.set_seed(42)
celsius    = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit = np.array([-40, 14, 32, 46.4, 59, 71.6, 100.4], dtype=float)

model = tf.keras.Sequential([tf.keras.Input(shape=(1,)),
                             tf.keras.layers.Dense(units=1)])   # 1 neuron
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
history = model.fit(celsius, fahrenheit, epochs=1000, verbose=0)
print("Training finished. Final loss (MSE):", round(history.history['loss'][-1], 4))

w, b = model.layers[0].get_weights()
print("Learnt weight :", round(float(w[0][0]), 4), " (formula: 1.8)")
print("Learnt bias   :", round(float(b[0]), 4), " (formula: 32)")
for c in [100.0, 37.0, -5.0]:
    f = model.predict(np.array([[c]]), verbose=0)[0][0]
    print(f"{c} C -> {f:.2f} F   (actual {c * 1.8 + 32:.2f} F)")
โ–ถ Sample Output
Training finished. Final loss (MSE): 0.0006
Learnt weight : 1.8002  (formula: 1.8)
Learnt bias   : 31.9751  (formula: 32)
100.0 C -> 212.00 F   (actual 212.00 F)
37.0 C -> 98.58 F   (actual 98.60 F)
-5.0 C -> 22.97 F   (actual 23.00 F)
๐Ÿ’ก Explanation: The network is never told F = 1.8C + 32. It starts with random weight and bias and, using the Adam optimiser, keeps adjusting them to reduce the mean squared error - learning the formula from examples. (pip install tensorflow)
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; modules numpy, tensorflow
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q8.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
2
import tensorflow as tf
๐Ÿ“ฆ Library / Data Loads the module tensorflow (nick-name tf) - deep learning
3
tf.random.set_seed(42)
๐Ÿงฎ Store / Calculate Calls tf.random.set_seed(42)
4
celsius    = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
๐Ÿ“ฆ Library / Data Makes a NumPy array from [-40, -10, 0, 8, 15, 22, 38]; the result is stored in variable celsius
5
fahrenheit = np.array([-40, 14, 32, 46.4, 59, 71.6, 100.4], dtype=float)
๐Ÿ“ฆ Library / Data Makes a NumPy array from [-40, 14, 32, 46.4, 59, 71.6, 100.4]; the result is stored in variable fahrenheit
7
model = tf.keras.Sequential([tf.keras.Input(shape=(1,)),
                             tf.keras.layers.Dense(units=1)])   # 1 neuron
๐Ÿงฎ Store / Calculate Calls tf.keras.Sequential([tf.keras.Input(shape=(1โ€ฆ); the result is stored in variable model
9
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
๐Ÿงฎ Store / Calculate Calls model.compile()
10
history = model.fit(celsius, fahrenheit, epochs=1000, verbose=0)
๐Ÿ“ฆ Library / Data Trains (fits) the model model on the given data; the result is stored in variable history
11
print("Training finished. Final loss (MSE):", round(history.history['loss'][-1], 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Training finished. Final loss (MSโ€ฆ", then the value of round(history.history['loss'][-1], 4) on the screen
13
w, b = model.layers[0].get_weights()
๐Ÿงฎ Store / Calculate Calls model.layers[0].get_weights(); the result is stored in variables w, b
14
print("Learnt weight :", round(float(w[0][0]), 4), " (formula: 1.8)")
๐Ÿ–ฅ๏ธ Output Displays the text "Learnt weight :", then the value of round(float(w[0][0]), 4), then the text "(formula: 1.8)" on the screen
15
print("Learnt bias   :", round(float(b[0]), 4), " (formula: 32)")
๐Ÿ–ฅ๏ธ Output Displays the text "Learnt bias :", then the value of round(float(b[0]), 4), then the text "(formula: 32)" on the screen
16
for c in [100.0, 37.0, -5.0]:
๐Ÿ” Loop LOOP: takes each item of [100.0, 37.0, -5.0] one-by-one into c and runs the indented block for it
17
f = model.predict(np.array([[c]]), verbose=0)[0][0]
๐Ÿ“ฆ Library / Data Stores the item model.predict(np.array([[c]]), verbose=0)[0][โ€ฆ in variable f
18
print(f"{c} C -> {f:.2f} F   (actual {c * 1.8 + 32:.2f} F)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c} C -> {f:.2f} F (actual {c * 1.8 + 32:.2โ€ฆ with the values filled into { } on the screen
Q9 PYTHON

Python 9 (Advanced learners): Working with OpenCV to load, display and resize images.

import cv2
img = cv2.imread("flower.jpg")
print("Original size (h, w, channels):", img.shape)
small = cv2.resize(img, (200, 150))                       # (width, height)
half = cv2.resize(img, None, fx=0.5, fy=0.5)              # scale factor
big = cv2.resize(img, (600, 450), interpolation=cv2.INTER_CUBIC)
print("Resized to 200x150 :", small.shape)
print("Half size          :", half.shape)
print("Enlarged 600x450   :", big.shape)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", img)
cv2.imshow("Resized 200x150", small)
cv2.imshow("Grayscale", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
โ–ถ Sample Output
Original size (h, w, channels): (300, 400, 3)
Resized to 200x150 : (150, 200, 3)
Half size          : (150, 200, 3)
Enlarged 600x450   : (450, 600, 3)
Window: Original
Window: Original
Window: Resized 200x150
Window: Resized 200x150
Window: Grayscale
Window: Grayscale
๐Ÿ’ก Explanation: cv2.resize() takes the new size as (width, height) - opposite to img.shape which is (height, width). INTER_CUBIC gives smoother results when enlarging.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses module cv2
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q9.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import cv2
๐Ÿ“ฆ Library / Data Loads the module cv2 - OpenCV image processing
2
img = cv2.imread("flower.jpg")
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable img
3
print("Original size (h, w, channels):", img.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Original size (h, w, channels):", then the value of img.shape on the screen
4
small = cv2.resize(img, (200, 150))                       # (width, height)
๐Ÿ“ฆ Library / Data Changes the size of the image; the result is stored in variable small
5
half = cv2.resize(img, None, fx=0.5, fy=0.5)              # scale factor
๐Ÿ“ฆ Library / Data Changes the size of the image; the result is stored in variable half
6
big = cv2.resize(img, (600, 450), interpolation=cv2.INTER_CUBIC)
๐Ÿ“ฆ Library / Data Changes the size of the image; the result is stored in variable big
7
print("Resized to 200x150 :", small.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Resized to 200x150 :", then the value of small.shape on the screen
8
print("Half size          :", half.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Half size :", then the value of half.shape on the screen
9
print("Enlarged 600x450   :", big.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Enlarged 600x450 :", then the value of big.shape on the screen
10
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
๐Ÿ“ฆ Library / Data Converts the colour format of the image; the result is stored in variable gray
11
cv2.imshow("Original", img)
๐Ÿ–ฅ๏ธ Output Shows the image in a window
12
cv2.imshow("Resized 200x150", small)
๐Ÿ–ฅ๏ธ Output Shows the image in a window
13
cv2.imshow("Grayscale", gray)
๐Ÿ–ฅ๏ธ Output Shows the image in a window
14
cv2.waitKey(0)
๐Ÿ“ฆ Library / Data Waits for a key press
15
cv2.destroyAllWindows()
๐Ÿ“ฆ Library / Data Closes all image windows
Q10 PYTHON

Unit 3 Activity: Binary Art - recreate an image with 0s and 1s using Python.

import cv2
img = cv2.imread("flower.jpg", cv2.IMREAD_GRAYSCALE)
small = cv2.resize(img, (40, 22))                 # very low resolution
_, binary = cv2.threshold(small, 150, 1, cv2.THRESH_BINARY_INV)
print("Binary image (1 = dark pixel, 0 = light pixel):\n")
for row in binary:
    print("".join(str(v) for v in row))
print("\nShape of binary image:", binary.shape)
print("Number of 1s:", int(binary.sum()), " Number of 0s:", binary.size - int(binary.sum()))
โ–ถ Sample Output
Binary image (1 = dark pixel, 0 = light pixel):

0000000000000000000000000000000000000000
0000000000000000000000000000000000000000
0000000000000000000000000000000000000000
0000000000000000001111100000000000000000
0000000000000011111111111100000000000000
0000000000000011111111111100000000000000
0000000000000111111001111110000000000000
0000000000000111110000011110000000000000
0000000000000111100000011111000000000000
0000000000000111110000111110000000000000
0000000000000011111111111100000000000000
0000000000000011111111111100000000000000
0000000000000000111111110000000000000000
0000000000000000000111100000000000000000
0000000000000000000011111000000000000000
0000000000000001111010011100000000000000
0000000000000011110010000000000000000000
0000000000000000000010000000000000000000
1111111111111111111111111111111111111111
1111111111111111111111111111111111111111
1111111111111111111111111111111111111111
1111111111111111111111111111111111111111

Shape of binary image: (22, 40)
Number of 1s: 284  Number of 0s: 596
๐Ÿ’ก Explanation: A computer sees an image as numbers. Thresholding turns every grayscale pixel into 1 (dark) or 0 (light), so the picture can be drawn with digits - the idea behind binary images used in computer vision.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses a for loop; module cv2
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q10.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿ” Loop๐Ÿ“ฆ Library / Data
LineCodeWhat it does
1
import cv2
๐Ÿ“ฆ Library / Data Loads the module cv2 - OpenCV image processing
2
img = cv2.imread("flower.jpg", cv2.IMREAD_GRAYSCALE)
๐Ÿ“ฆ Library / Data Reads the image file "flower.jpg" into a NumPy array of pixels; the result is stored in variable img
3
small = cv2.resize(img, (40, 22))                 # very low resolution
๐Ÿ“ฆ Library / Data Changes the size of the image; the result is stored in variable small
4
_, binary = cv2.threshold(small, 150, 1, cv2.THRESH_BINARY_INV)
๐Ÿ“ฆ Library / Data Turns the image into black & white using a cut-off; the result is stored in variables _, binary
5
print("Binary image (1 = dark pixel, 0 = light pixel):\n")
๐Ÿ–ฅ๏ธ Output Displays the text "Binary image (1 = dark pixel, 0 =โ€ฆ" on the screen
6
for row in binary:
๐Ÿ” Loop LOOP: takes each item of binary one-by-one into row and runs the indented block for it
7
print("".join(str(v) for v in row))
๐Ÿ–ฅ๏ธ Output Displays the value of "".join(str(v) for v in row) on the screen
8
print("\nShape of binary image:", binary.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape of binary image:", then the value of binary.shape on the screen
9
print("Number of 1s:", int(binary.sum()), " Number of 0s:", binary.size - int(binary.sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Number of 1s:", then the value of int(binary.sum()), then the text "Number of 0s:", then the value of binary.size - int(binary.sum()) on the screen
Q11 PYTHON

Python 10 (Advanced learners): Write Python code to initialise the Gemini API and create a chatbot.

# pip install google-genai
# Get a free API key from https://aistudio.google.com  (never share your key)
import os
from google import genai

client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
chat = client.chats.create(model="gemini-2.5-flash")

print("StudyBuddy: Hi! Ask me anything about AI. Type 'bye' to exit.")
while True:
    question = input("You: ")
    if question.lower() in ("bye", "exit", "quit"):
        print("StudyBuddy: Goodbye! Keep learning.")
        break
    response = chat.send_message(question)
    print("StudyBuddy:", response.text)
โ–ถ Sample run (AI replies will differ; needs internet and an API key)
StudyBuddy: Hi! Ask me anything about AI. Type 'bye' to exit.
You: What is a neural network in one line?
StudyBuddy: A neural network is a set of connected layers of artificial neurons that learn
patterns from data by adjusting weights.
You: bye
StudyBuddy: Goodbye! Keep learning.
๐Ÿ’ก Explanation: The client connects to Google's Gemini model using an API key stored in an environment variable. chats.create() keeps the conversation history so follow-up questions are understood. Model names change over time - check the current name in Google AI Studio. Answers are generated, so they vary from run to run.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTreads 1 value from the keyboard โ†’ question
โžœ
โ‘ก PROCESSuses a while loop; decisions with if / elif / else; modules os, google
โžœ
โ‘ข OUTPUTprints the result on the screen
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q11.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
โ‘  What each line does (colour = type of statement)
โŒจ๏ธ Input๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ”€ Decision๐Ÿ” Loop๐Ÿ“ File๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ pip install google-genai
๐Ÿ“Œ Get a free API key from https://aistudio.google.com (never share your key)
3
import os
๐Ÿ“ฆ Library / Data Loads the module os - file and folder operations
4
from google import genai
๐Ÿ“ฆ Library / Data Loads genai from the google module
6
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
๐Ÿ“ File Calls genai.Client(); the result is stored in variable client
7
chat = client.chats.create(model="gemini-2.5-flash")
๐Ÿงฎ Store / Calculate Calls client.chats.create(); the result is stored in variable chat
9
print("StudyBuddy: Hi! Ask me anything about AI. Type 'bye' to exit.")
๐Ÿ–ฅ๏ธ Output Displays the text "StudyBuddy: Hi! Ask me anything aโ€ฆ" on the screen
10
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
11
question = input("You: ")
โŒจ๏ธ Input Shows the message "You: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable question
12
if question.lower() in ("bye", "exit", "quit"):
๐Ÿ”€ Decision CHECKS whether question.lower() is present in ("bye", "exit", "quit"). If True, the indented lines below run; otherwise they are skipped
13
print("StudyBuddy: Goodbye! Keep learning.")
๐Ÿ–ฅ๏ธ Output Displays the text "StudyBuddy: Goodbye! Keep learninโ€ฆ" on the screen
14
break
๐Ÿ” Loop BREAK - leaves the loop immediately
15
response = chat.send_message(question)
๐Ÿงฎ Store / Calculate Calls chat.send_message(question); the result is stored in variable response
16
print("StudyBuddy:", response.text)
๐Ÿ–ฅ๏ธ Output Displays the text "StudyBuddy:", then the value of response.text on the screen
Q12 ACTIVITY

Unit 2 Activity: Calculate MSE and RMSE values for the given data using MS Excel.

DATA             A          B            C                    D
            1  Actual    Predicted    Error (A-B)         Squared Error
            2   250        260         =A2-B2              =C2^2
            3   300        290         =A3-B3              =C3^2
            4   320        330         ...                 ...
            5   410        400
            6   380        395
            7   450        430
            8   500        510
            9   520        540

STEPS
1. Fill C2:D9 by dragging the formulas down.
2. MSE  :  =AVERAGE(D2:D9)          (or  =SUMXMY2(A2:A9,B2:B9)/COUNT(A2:A9) )
3. RMSE :  =SQRT(AVERAGE(D2:D9))
4. MAE  :  =AVERAGE(ABS(C2:C9))     (press Ctrl+Shift+Enter in old Excel)
โ–ถ Result in Excel
Errors: -10, 10, -10, 10, -15, 20, -10, -20
MSE  = 193.75
RMSE = 13.92
MAE  = 13.13
๐Ÿ’ก Explanation: MSE squares every error so large mistakes count more; RMSE brings the value back to the original unit. Lower values mean a better regression model.
Q13 ACTIVITY

Unit 2 Activity: Calculate Precision, Recall, F1 score and Accuracy from the given confusion matrix.

GIVEN CONFUSION MATRIX (spam detection on 200 emails)
                        Predicted: Spam   Predicted: Not Spam
   Actual: Spam             TP = 60            FN = 15
   Actual: Not Spam         FP = 10            TN = 115

SOLUTION
 Accuracy  = (TP + TN) / Total        = (60 + 115) / 200   = 175/200 = 0.875
 Precision = TP / (TP + FP)           = 60 / 70                       = 0.857
 Recall    = TP / (TP + FN)           = 60 / 75                       = 0.800
 F1 Score  = 2 x P x R / (P + R)      = 2 x 0.857 x 0.8 / 1.657       = 0.828
โ–ถ Result
Accuracy = 87.5 %   Precision = 85.7 %   Recall = 80.0 %   F1 = 82.8 %
๐Ÿ’ก Explanation: Precision answers 'of the emails marked spam, how many were spam?'; Recall answers 'of all spam emails, how many did we catch?'. F1 is their harmonic mean.
Q14 ACTIVITY

Orange 1: Perform the step-wise procedure of Data Visualization using the Orange Data Mining tool (Iris dataset - Scatter Plot, Box Plot, Distributions).

SOFTWARE : Orange Data Mining (free) - https://orangedatamining.com/download/

STEPS
1. Open Orange -> a blank canvas with the widget panel on the left.
2. Data -> drag the "File" widget -> double-click -> select "iris.tab"
   (150 rows, 4 features: sepal length/width, petal length/width, target: iris).
3. Connect File -> "Data Table" to view the data.
4. Connect File -> "Scatter Plot": X axis = petal length, Y axis = petal width,
   Color = iris. Click "Find Informative Projections".
5. Connect File -> "Box Plot" (variable petal length, subgroups = iris).
6. Connect File -> "Distributions" (variable sepal length, split by iris).
7. Take snapshots of each widget output and paste in the practical file.

WORKFLOW :  [File] ---> [Data Table]
               |------> [Scatter Plot]
               |------> [Box Plot]
               |------> [Distributions]
โ–ถ Observation
Observation: Setosa forms a separate cluster (small petals); Versicolor and Virginica
overlap slightly. Petal features are the most informative.
๐Ÿ’ก Explanation: Visualising before modelling shows which features separate the classes. In Iris, petal length and petal width separate Setosa completely and Versicolor/Virginica almost completely.
Q15 ACTIVITY

Orange 2: Perform Classification with the Orange Data Mining tool.

STEPS
1. File (iris.tab) -> "Data Sampler" (Fixed proportion 70 %) to create
   training data (Data Sample) and test data (Remaining Data).
2. Add learners from the Model panel: "kNN" (k = 5), "Tree", "Logistic
   Regression", "Naive Bayes".
3. Connect Data Sample -> each learner.
4. Add "Predictions" widget: connect the learners (Model) and Remaining Data
   (Data) to it -> it shows the predicted class for each test flower.
5. Optional: Tree -> "Tree Viewer" to see the decision rules.

WORKFLOW
 [File] -> [Data Sampler] --(Data Sample)--> [kNN] [Tree] [Logistic Regression]
                 |                                 \      |      /
                 +------(Remaining Data)--------> [Predictions]
โ–ถ Observation
Predictions widget: 45 test flowers classified; Tree rule learnt -
'petal length <= 1.9 -> Setosa'.
๐Ÿ’ก Explanation: Classification is supervised learning: the model learns from labelled examples and predicts the class of new data. Tree Viewer shows the human-readable if-else rules learnt by the tree.
Q16 ACTIVITY

Orange 3: Evaluate the Classification Model with Orange (Test and Score, Confusion Matrix).

STEPS
1. File (iris.tab) -> "Test and Score".
2. Connect learners kNN, Tree, Logistic Regression, Naive Bayes -> Test and Score.
3. In Test and Score choose "Cross validation" with Number of folds = 10
   (also try "Random sampling" 70:30).
4. Read the evaluation table: AUC, CA (classification accuracy), F1,
   Precision, Recall for every model.
5. Connect Test and Score -> "Confusion Matrix"; select each learner on the
   left to view its matrix.
6. Note which model performs best and why.
โ–ถ Observation (values may vary slightly with Orange version)
10-fold CV (sample result): Logistic Regression CA = 0.96, kNN CA = 0.95, Tree CA = 0.94
Confusion matrix: all Setosa correct; a few Versicolor <-> Virginica mix-ups.
๐Ÿ’ก Explanation: Cross-validation splits the data into k folds, trains k times and averages the scores, giving a more reliable estimate than a single split. CA = classification accuracy.
Q17 ACTIVITY

Orange 4: Perform Image Analytics using the Orange Data Mining tool.

SETUP : Options -> Add-ons -> tick "Image Analytics" -> OK -> restart Orange.

STEPS
1. Collect images in folders, e.g. "animals/cat", "animals/dog", "animals/bird"
   (10-15 images per folder).
2. Image Analytics -> "Import Images" -> select the "animals" folder.
3. Connect -> "Image Viewer" to check the images.
4. Connect -> "Image Embedding" (embedder: SqueezeNet - works offline;
   Inception v3 needs internet). Each image becomes a vector of numbers.
5. Embeddings -> "Distances" (Cosine) -> "Hierarchical Clustering" -> view
   the dendrogram; connect selected cluster -> Image Viewer.
6. Optional: Embeddings -> "Test and Score" with Logistic Regression
   (target = folder category) to classify images.

WORKFLOW : [Import Images] -> [Image Embedding] -> [Distances] -> [Hierarchical Clustering] -> [Image Viewer]
โ–ถ Sample Observation
Hierarchical clustering grouped the images into 3 clusters matching cat, dog and bird;
2 images were placed in the wrong cluster.
๐Ÿ’ก Explanation: Image Embedding uses a pre-trained deep neural network to convert each picture into numeric features; similar images get similar vectors, so clustering and classification become possible without coding.
Q18 ACTIVITY

Orange 5: Write down the steps to visualise word frequencies with a Word Cloud using the Orange Data Mining tool.

SETUP : Options -> Add-ons -> tick "Text" (Text Mining) -> restart Orange.

STEPS
1. Text Mining -> "Corpus" widget -> load a corpus (e.g. "book-excerpts" or
   your own .txt/.csv of product reviews).
2. Connect -> "Preprocess Text": Transformation (lowercase, remove accents),
   Tokenization (words), Filtering (stopwords - English, numbers).
3. Connect Preprocess Text -> "Word Cloud".
4. Bigger words = more frequent. Click a word to see documents containing it
   (connect to Corpus Viewer).
5. Optional: Preprocess Text -> "Bag of Words" -> "Word Cloud" weights.

WORKFLOW : [Corpus] -> [Preprocess Text] -> [Word Cloud] -> [Corpus Viewer]
โ–ถ Sample Observation
For 200 canteen reviews the largest words were: food, tasty, price, samosa, clean, slow.
๐Ÿ’ก Explanation: Removing stopwords (the, is, and) is essential, otherwise they dominate the word cloud. A word cloud is a quick visual summary of what a large text collection is about.
Q19 ACTIVITY

Orange 6 (Unit 5): Perform Big Data analytics with the Orange Data Mining tool.

DATASET : a large CSV, e.g. a public air-quality / taxi-trip / sales dataset with
          tens of thousands of rows (data.gov.in, Kaggle).

STEPS
1. "File" widget -> load the large CSV (check rows x columns in the info box).
2. "Data Info" / "Feature Statistics" -> see mean, dispersion and missing values.
3. "Preprocess" -> Impute missing values, Normalize features.
4. "Data Sampler" -> take a 10 % random sample to explore faster (Volume).
5. "Pivot Table" / "Group By" -> aggregate, e.g. average AQI by city and month.
6. "Line Plot" / "Bar Plot" / "Heat Map" -> visualise trends.
7. "k-Means" (k from 2 to 6, silhouette score) -> find natural groups.
8. Interpret the result in 5-6 lines (Value).

BIG DATA 5 Vs : Volume, Velocity, Variety, Veracity, Value
โ–ถ Sample Observation
Sample insight: average AQI in winter months (Nov-Jan) was nearly double the monsoon
months; k-Means grouped cities into 3 pollution levels.
๐Ÿ’ก Explanation: Orange can explore large tables visually; sampling, aggregation and clustering are basic big-data analytics steps that turn huge raw data into useful insight (Value).
Q20 ACTIVITY

Unit 6 Activity: Explore Machine Learning for Kids to create a neural network for identifying animals and birds.

WEBSITE : https://machinelearningforkids.co.uk  ("Try it now" - no login needed)

STEPS
1. Projects -> "+ Add a new project" -> Name "AnimalOrBird", Recognising: Images.
2. Train -> "+ Add new label": animal, bird.
3. Add 15-20 pictures to each label (drag from web pages / webcam).
4. Learn & Test -> "Train new machine learning model" (a neural network is trained
   in the cloud).
5. Test with new image URLs / webcam and note the confidence %.
6. Make -> Scratch 3 -> build a small game: "when green flag clicked -> ask URL ->
   say (recognise image (label))".
โ–ถ Sample Observation
Test: parrot -> bird (92 %), elephant -> animal (88 %), bat -> bird (61 %, wrong - add more bat images).
๐Ÿ’ก Explanation: The tool trains a neural network on the labelled images. More and more varied training images increase the confidence and accuracy of predictions.
Q21 ACTIVITY

Unit 6 Activity: Classification problem using TensorFlow Playground.

WEBSITE : https://playground.tensorflow.org

STEPS
1. Problem type = Classification. Data = "Circle" (blue points inside, orange outside).
2. Ratio of training to test data = 50 %, Noise = 0, Batch size = 10.
3. Features: X1 and X2 only. Hidden layers: 1 layer with 2 neurons -> Run.
   Observe: a straight boundary cannot separate the circle -> high test loss.
4. Increase to 2 hidden layers (4 and 2 neurons), activation = ReLU / Tanh,
   learning rate = 0.03 -> Run for 300+ epochs.
5. Try the "Spiral" dataset; add features X1^2, X2^2, sin(X1) and more neurons.
6. Record test loss and training loss for each setting (table).
โ–ถ Sample Observation
Circle, 1 layer x 2 neurons : test loss 0.45 (poor)
Circle, 2 layers (4,2)       : test loss 0.01 (good)
Spiral needed 3 layers + extra features to reach test loss below 0.10.
๐Ÿ’ก Explanation: Hidden layers and non-linear activation functions let a network draw curved decision boundaries. Too few neurons underfit; very large networks may overfit noisy data.
Q22 ACTIVITY

Unit 6 Activity: Regression problem using TensorFlow Playground.

STEPS
1. Problem type = Regression. Data = "Plane" (linear) and then "Multi Gaussian".
2. Features X1, X2. Start with 0 hidden layers (only the output neuron) -> Run.
   Plane data is learnt well because the relation is linear.
3. Switch to Multi Gaussian -> 0 hidden layers gives high loss.
4. Add 2 hidden layers (6 and 4 neurons), activation ReLU, learning rate 0.01 ->
   Run and watch the output colours match the data.
5. Add noise = 20 and observe the effect on test loss.
โ–ถ Sample Observation
Plane: test loss 0.002 with no hidden layer.
Multi Gaussian: 0.21 (no hidden layer) -> 0.03 (2 hidden layers).
๐Ÿ’ก Explanation: In regression the network predicts a continuous value (shown as colour intensity) instead of a class. Non-linear data needs hidden layers.
Q23 ACTIVITY

Unit 7 Activity: Generative AI tools - craft prompts in Google Gemini / ChatGPT, design with Canva Magic Studio and create a video with Animaker AI.

A) TEXT - Google Gemini (gemini.google.com) / ChatGPT
   Weak prompt  : "Write about water."
   Better prompt: "Act as a science teacher. Write a 120-word poster message for
                   Class 8 students on 5 ways to save water at school. Use simple
                   English and a catchy title."
   Compare the two outputs; note role, task, audience, length and format.

B) IMAGE / DESIGN - Canva (sign up with school e-mail) -> Magic Media / Magic Design
   Prompt: "Poster of children planting trees, bright flat illustration, SDG 13"

C) VIDEO - Animaker (app.animaker.com) -> AI video generator
   Prompt: "30-second explainer: how AI helps farmers predict rainfall"

D) RESPONSIBLE USE CHECKLIST
   [ ] verified facts   [ ] no personal data uploaded   [ ] mentioned "AI-generated"
   [ ] checked bias / stereotypes   [ ] respected copyright
โ–ถ Sample Observation
Better prompt produced a focused 118-word poster text with a title, 5 bullet tips and
a call to action; the weak prompt gave a long generic essay.
๐Ÿ’ก Explanation: Generative AI creates new text, images and video from prompts. A good prompt states the role, task, context, audience and output format. Outputs must be checked for accuracy, bias and copyright.
Q24 ACTIVITY

Unit 3 Activity: Creating a website containing an ML model (Teachable Machine + website).

STEPS
1. Teachable Machine -> Image Project -> classes "Mask" and "No Mask" (or
   "Ripe" / "Unripe" fruit) -> add samples -> Train Model.
2. Export Model -> "Upload my model" -> copy the shareable model URL.
3. Choose "Javascript" tab -> copy the ready-made code snippet.
4. Create a free site (Google Sites / GitHub Pages / CodePen):
     - paste the snippet into an HTML file (index.html),
     - replace the URL with your model URL,
     - publish.
5. Open the site, allow the webcam and test the live prediction.
โ–ถ Result
Website published; live webcam predictions displayed with class name and probability bars.
๐Ÿ’ก Explanation: This shows the DEPLOYMENT stage of the AI project cycle: a trained model is put on a web page so anyone can use it through a browser (TensorFlow.js runs the model).
Q25 PYTHON

Data Storytelling: Using data on student enrolment, attendance and dropout rates, create a data story exploring the impact of the Mid-Day Meal Scheme (MDMS) on dropout rates.

# Data story : Mid-Day Meal Scheme and school dropout (ILLUSTRATIVE data -
# replace with your state's figures from UDISE+ / education department reports)
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
    'Year':        [1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012],
    'Enrolment_L': [42.0, 44.5, 46.8, 48.2, 50.1, 53.6, 55.0, 56.2, 57.1, 57.8],
    'Attendance':  [61, 64, 67, 69, 71, 76, 79, 81, 83, 84],
    'Dropout':     [38.0, 36.1, 33.9, 32.0, 30.4, 26.2, 23.5, 21.0, 18.6, 17.1]})
print(df.to_string(index=False))
print("\nDropout fell by", round(df.Dropout.iloc[0] - df.Dropout.iloc[-1], 1), "percentage points")
print("Correlation (Attendance vs Dropout):", round(df.Attendance.corr(df.Dropout), 3))

fig, ax1 = plt.subplots(figsize=(8, 4.5))
ax1.plot(df.Year, df.Dropout, 'r-o', label='Dropout rate (%)')
ax1.plot(df.Year, df.Attendance, 'g-s', label='Attendance (%)')
ax1.axvline(1995, color='grey', linestyle='--'); ax1.text(1995.3, 45, 'MDMS launched (1995)')
ax1.axvline(2004, color='grey', linestyle=':'); ax1.text(2004.3, 52, 'Cooked-meal\nscheme (2004)')
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc='upper left')
ax1.set_title('Mid-Day Meals and Dropout Rate (illustrative data)')
plt.show()
โ–ถ Sample Output
 Year  Enrolment_L  Attendance  Dropout
 1994         42.0          61     38.0
 1996         44.5          64     36.1
 1998         46.8          67     33.9
 2000         48.2          69     32.0
 2002         50.1          71     30.4
 2004         53.6          76     26.2
 2006         55.0          79     23.5
 2008         56.2          81     21.0
 2010         57.1          83     18.6
 2012         57.8          84     17.1

Dropout fell by 20.9 percentage points
Correlation (Attendance vs Dropout): -0.996
Figure 1
Figure 1
๐Ÿ’ก Explanation: A data story combines DATA (numbers), VISUALS (chart) and NARRATIVE (explanation). Following Freytag's pyramid: Setup - high dropout before 1995; Rising action - MDMS launched; Climax - sharp fall after cooked meals in 2004; Resolution - attendance rose and dropout halved. Note: correlation does not prove causation - other factors (RTE Act 2009, Sarva Shiksha Abhiyan) also played a role.
NEW ๐Ÿ” How this program runs - step by step, with animation

Python reads the program from top to bottom, one line at a time. Lines indented under if / for / while run only when their condition allows.

In short - Input โžœ Process โžœ Output
โ‘  INPUTno keyboard input - the data is written inside the program
โžœ
โ‘ก PROCESSuses modules pandas, matplotlib.pyplot
โžœ
โ‘ข OUTPUTprints the result on the screen, draws a chart
๐Ÿง‘โ€๐Ÿ’ป Do it yourself - easy steps
  1. Click โ–ถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ†’ File โ†’ New File).
  2. Type the code exactly - indentation (4 spaces) matters in Python. Save it as xii_ai_q25.py.
  3. Press F5 (Run โ†’ Run Module).
  4. Match your screen with the Sample Output. Then write the code + output in your practical file.
๐ŸŽฌ Watch it run - step by step

Press โ–ถ Play or Next โ–ถ. The yellow line is the line Python is running now; the boxes show the variables in memory and what appears on the screen. Made by really running the program with the sample input.

โ‘  What each line does (colour = type of statement)
๐Ÿ–ฅ๏ธ Output๐Ÿงฎ Store / Calculate๐Ÿ“ฆ Library / Data๐Ÿ“Œ Comment
LineCodeWhat it does
๐Ÿ“Œ Data story : Mid-Day Meal Scheme and school dropout (ILLUSTRATIVE data -
๐Ÿ“Œ replace with your state's figures from UDISE+ / education department reports)
3
import pandas as pd
๐Ÿ“ฆ Library / Data Loads the module pandas (nick-name pd) - data tables (Series & DataFrame)
4
import matplotlib.pyplot as plt
๐Ÿ“ฆ Library / Data Loads the module matplotlib.pyplot (nick-name plt) - drawing charts
5
df = pd.DataFrame({
    'Year':        [1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012],
    'Enrolment_L': [42.0, 44.5, 46.8, 48.2, 50.1, 53.6, โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from { 'Year': [1994, 1996, 1998, 2000, 2002, 2004โ€ฆ; the result is stored in variable df
10
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
11
print("\nDropout fell by", round(df.Dropout.iloc[0] - df.Dropout.iloc[-1], 1), "percentage points")
๐Ÿ–ฅ๏ธ Output Displays the text "Dropout fell by", then the value of round(df.Dropout.iloc[0] - df.Dropout.iloc[-1โ€ฆ, then the text "percentage points" on the screen
12
print("Correlation (Attendance vs Dropout):", round(df.Attendance.corr(df.Dropout), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Correlation (Attendance vs Dropouโ€ฆ", then the value of round(df.Attendance.corr(df.Dropout), 3) on the screen
14
fig, ax1 = plt.subplots(figsize=(8, 4.5))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax1
15
ax1.plot(df.Year, df.Dropout, 'r-o', label='Dropout rate (%)')
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Year, df.Dropout, 'r-o'
16
ax1.plot(df.Year, df.Attendance, 'g-s', label='Attendance (%)')
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Year, df.Attendance, 'g-s'
17
ax1.axvline(1995, color='grey', linestyle='--'); ax1.text(1995.3, 45, 'MDMS launched (1995)')
๐Ÿงฎ Store / Calculate Draws a vertical reference line
17
ax1.axvline(1995, color='grey', linestyle='--'); ax1.text(1995.3, 45, 'MDMS launched (1995)')
๐Ÿงฎ Store / Calculate Writes text on the chart
18
ax1.axvline(2004, color='grey', linestyle=':'); ax1.text(2004.3, 52, 'Cooked-meal\nscheme (2004)')
๐Ÿงฎ Store / Calculate Draws a vertical reference line
18
ax1.axvline(2004, color='grey', linestyle=':'); ax1.text(2004.3, 52, 'Cooked-meal\nscheme (2004)')
๐Ÿงฎ Store / Calculate Writes text on the chart
19
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc='upper left')
๐Ÿ“ฆ Library / Data Calls ax1.set_xticks(df.Year)
19
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc='upper left')
๐Ÿ“ฆ Library / Data Sets the X-axis label
19
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc='upper left')
๐Ÿ“ฆ Library / Data Sets the Y-axis label
19
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc='upper left')
๐Ÿ“ฆ Library / Data Shows the legend (which colour means what)
20
ax1.set_title('Mid-Day Meals and Dropout Rate (illustrative data)')
๐Ÿงฎ Store / Calculate Sets the title of this chart
21
plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
โ‘ก Dry-run table (for your practical file)
StepLineLine being runVariables changedOn screen
13
import pandas as pd
24
import matplotlib.pyplot as plt
35
df = pd.DataFrame({
46
'Year':        [1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012],
57
'Enrolment_L': [42.0, 44.5, 46.8, 48.2, 50.1, 53.6, 55.0, 56.2, 57.1, 57.8],
68
'Attendance':  [61, 64, 67, 69, 71, 76, 79, 81, 83, 84],
79
'Dropout':     [38.0, 36.1, 33.9, 32.0, 30.4, 26.2, 23.5, 21.0, 18.6, 17.1]})
85
df = pd.DataFrame({
df = DataFrame (10 rows ร— 4 columns)
910
print(df.to_string(index=False))
 Year  Enrolment_L  Attendance  Dropout
 1994         42.0          61     38.0
 1996         44.5          64     36.1
 1998         46.8          67     33.9
 2000         48.2          69     32.0
 2002         50.1          71     30.4
 2004         53.6          76     26.2
 2006         55.โ€ฆ
1011
print("\nDropout fell by", round(df.Dropout.iloc[0] - df.Dropout.iloc[-1], 1), "percentage
Dropout fell by 20.9 percentage points
1112
print("Correlation (Attendance vs Dropout):", round(df.Attendance.corr(df.Dropout), 3))
Correlation (Attendance vs Dropout): -0.996
1214
fig, ax1 = plt.subplots(figsize=(8, 4.5))
fig = chart object, ax1 = chart object
1315
ax1.plot(df.Year, df.Dropout, 'r-o', label='Dropout rate (%)')
1416
ax1.plot(df.Year, df.Attendance, 'g-s', label='Attendance (%)')
1517
ax1.axvline(1995, color='grey', linestyle='--'); ax1.text(1995.3, 45, 'MDMS launched (1995
1618
ax1.axvline(2004, color='grey', linestyle=':'); ax1.text(2004.3, 52, 'Cooked-meal\nscheme 
1719
ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc
1820
ax1.set_title('Mid-Day Meals and Dropout Rate (illustrative data)')
1921
plt.show()

๐Ÿ“ Project Work Reference (CBSE 843)

CAPSTONE PROJECT GUIDELINES (25 marks = Project 15 + Documentation 6 + Video 4)
  * Group of minimum 3 and maximum 5 students.
  * Project must be aligned with any of the SDGs.
  * Complete the Capstone Project in Class XII along with the project documentation
    (process as per page 2 of the CBSE-IBM AI Project Cookbook).
  * Video of EXACTLY 3 minutes covering: (a) problem statement (b) SDG aligned to
    (c) AI concept / domains / algorithms used (d) working of the project (e) conclusion
    (f) acknowledgement to the teacher.
  * Python or no-code / low-code platforms like Orange Data Mining can be used.

OPTIONAL PROGRAMS for the practical file: train-test split in Linear Regression, chatbot using
Google Gemini API, Orange for data analytics, TensorFlow Playground classification and
regression (attach snapshots). Advanced-learner portions are not evaluated in exams.

๐Ÿš€ Live / Real-World Projects โ€” Code, Output & 25+ Page Documentation

80 menu-driven projects (CS, IP and AI for Classes IXโ€“XII). Every program was run โ€” the output is real. Each card has tabs for overview, code, a replay of the run, flow chart, testing and viva; the report (cover, certificate, 21 colourful chapters, Cambria 14 pt) downloads as PDF or Word with one click.

๐Ÿ“˜ View Syllabus 2026-27 0%๐Ÿ“˜ View Syllabus 2026-27 0%๐Ÿ“˜ View Syllabus 2026-27 0%๐Ÿ“˜ View Syllabus 2026-27 0%

๐Ÿ“˜ Class XI Computer Science (083) โ€” 10 Projects 10 projects

01

Personal Expense Tracker (Console)

PYTHONListsDictionariesFunctionsFile-writing basics
๐Ÿ“ 204 lines of codeโ˜ฐ 11 menu options๐Ÿ–ฅ๏ธ 202 output lines๐Ÿ“„ 25+ page report

Students record daily expenses (category + amount) in a dictionary, calculate category-wise totals, and display a monthly summary with highest/lowest spending category.

โœจ Features
  • Records every expense with date, category, amount and note (list of dictionaries)
  • Monthly budget with warning when spending crosses 80 % and 100 % of the budget
  • Category-wise summary with percentage share and a text bar chart
  • Search, edit and delete expenses; sort by amount or date
  • Saving tips generated from the spending pattern
  • Save to and load from a text file (expenses.txt) so data is not lost
โ˜ฐ Main menu
1Add ExpenseReads date, category, amount and note; validates amount; appends to the list
2View All ExpensesShows every record in a formatted table with serial numbers
3Category SummaryTotals, percentage share and bar chart of each category
4Search ExpenseFinds records by category or a word in the note
5Edit / DeleteChanges the amount of a record or removes it
6Sort ExpensesSorts the records by amount (high to low) or by date
7Budget StatusCompares total spending with the monthly budget and warns
8Saving TipsSuggests tips for the highest-spending category
9Save to FileWrites all records to expenses.txt
10Load from FileReads records back from expenses.txt
0ExitSaves data and closes the program
๐ŸŽฏ Objectives
  • Record expenses category-wise using a dictionary
  • Generate a summary with total, highest and lowest spending
  • Practise menu-driven programming with functions and loops
๐Ÿ“š Data dictionary
NameTypePurpose
expenseslist of dictEach dict holds date, category, amount and note of one expense
budgetfloatMonthly budget set by the user
CATEGORIEStupleAllowed categories: Food, Travel, Study, Health, Fun, Other
FILEstrName of the data file - expenses.txt
summarydictCategory -> total amount (built from the list)
Why it matters: Real-life money-management tool; extendable to Class XII with binary file storage.
# =====================================================================
#   PERSONAL EXPENSE TRACKER  (Console Application)
#   Concepts : lists, dictionaries, tuples, functions, loops, strings,
#              text file handling, try-except
# =====================================================================

CATEGORIES = ("Food", "Travel", "Study", "Health", "Fun", "Other")
FILE = "expenses.txt"
expenses = []          # list of dictionaries - one dictionary per expense
budget = 0.0


def line(ch="-", n=60):
    """Prints a separator line."""
    print(ch * n)


def banner():
    """Shows the title of the application."""
    line("=")
    print("        PERSONAL EXPENSE TRACKER  -  KV Student Edition")
    line("=")


def read_amount(prompt):
    """Reads a positive amount; returns None for invalid input."""
    try:
        amt = float(input(prompt))
        if amt <= 0:
            print("Amount must be greater than zero.")
            return None
        return amt
    except ValueError:
        print("Invalid amount! Please enter digits only.")
        return None


def add_expense():
    """Adds one expense record to the list."""
    date = input("Date (dd-mm-yyyy)       : ")
    cat = input("Category " + str(CATEGORIES) + ": ").strip().title()
    if cat not in CATEGORIES:
        print("Unknown category - saved under 'Other'.")
        cat = "Other"
    amt = read_amount("Amount (Rs.)            : ")
    if amt is None:
        return
    note = input("Note                    : ")
    expenses.append({"date": date, "category": cat, "amount": amt, "note": note})
    print("Expense added. Total records:", len(expenses))


def show_all(data=None):
    """Displays the records in a table."""
    data = expenses if data is None else data
    if not data:
        print("No expenses recorded yet.")
        return
    print(f"{'No':<4}{'Date':<12}{'Category':<10}{'Amount':>9}  Note")
    line()
    for i, e in enumerate(data, start=1):
        print(f"{i:<4}{e['date']:<12}{e['category']:<10}{e['amount']:>9.2f}  {e['note']}")
    line()
    print(f"{'TOTAL':<26}{sum(e['amount'] for e in data):>9.2f}")


def category_summary():
    """Shows total, share and a text bar chart for every category."""
    if not expenses:
        print("No expenses recorded yet.")
        return
    summary = {}
    for e in expenses:
        summary[e["category"]] = summary.get(e["category"], 0) + e["amount"]
    total = sum(summary.values())
    print("\n----- CATEGORY SUMMARY -----")
    for cat, amt in sorted(summary.items(), key=lambda x: x[1], reverse=True):
        share = amt / total * 100
        print(f"{cat:<8} Rs.{amt:>8.2f}  {share:5.1f}%  " + "#" * int(share // 4))
    top = max(summary, key=summary.get)
    low = min(summary, key=summary.get)
    print("Highest spending category:", top, "( Rs.", summary[top], ")")
    print("Lowest  spending category:", low, "( Rs.", summary[low], ")")


def search_expense():
    """Searches by category or by a word present in the note."""
    key = input("Enter category or word to search: ").strip().lower()
    found = [e for e in expenses if key in e["category"].lower() or key in e["note"].lower()]
    print(len(found), "matching record(s)")
    show_all(found) if found else None


def edit_delete():
    """Edits the amount of a record or deletes it."""
    show_all()
    if not expenses:
        return
    ch = input("E = Edit amount, D = Delete : ").upper()
    try:
        n = int(input("Record number: "))
        rec = expenses[n - 1]
    except (ValueError, IndexError):
        print("Invalid record number.")
        return
    if ch == "E":
        amt = read_amount("New amount: ")
        if amt:
            rec["amount"] = amt
            print("Record", n, "updated.")
    elif ch == "D":
        expenses.pop(n - 1)
        print("Record", n, "deleted. Records left:", len(expenses))
    else:
        print("Invalid option.")


def sort_expenses():
    """Sorts by amount (high to low) or by date."""
    ch = input("Sort by A = Amount, D = Date : ").upper()
    if ch == "A":
        show_all(sorted(expenses, key=lambda e: e["amount"], reverse=True))
    else:
        show_all(sorted(expenses, key=lambda e: e["date"][6:] + e["date"][3:5] + e["date"][:2]))


def budget_status():
    """Compares spending with the budget."""
    spent = sum(e["amount"] for e in expenses)
    used = spent / budget * 100 if budget else 0
    print(f"Budget Rs.{budget:.2f} | Spent Rs.{spent:.2f} | Used {used:.1f}%")
    print("[" + "=" * int(min(used, 100) // 5) + " " * (20 - int(min(used, 100) // 5)) + "]")
    if used >= 100:
        print("ALERT: Budget exceeded by Rs.", round(spent - budget, 2))
    elif used >= 80:
        print("WARNING: More than 80% of the budget is used!")
    else:
        print("Good! Remaining budget: Rs.", round(budget - spent, 2))


def saving_tips():
    """Gives tips for the category where most money is spent."""
    if not expenses:
        print("Add some expenses first.")
        return
    summary = {}
    for e in expenses:
        summary[e["category"]] = summary.get(e["category"], 0) + e["amount"]
    top = max(summary, key=summary.get)
    tips = {"Food": "Carry lunch from home and limit eating out to weekends.",
            "Travel": "Use a monthly bus pass or walk / cycle short distances.",
            "Study": "Buy second-hand books or use the school library.",
            "Health": "Regular exercise and good sleep reduce health costs.",
            "Fun": "Set a fixed monthly limit for games and movies.",
            "Other": "Write down why you buy 'other' items before buying."}
    print("Most money goes to:", top)
    print("Tip:", tips[top])


def save_file():
    """Saves all records to the text file."""
    with open(FILE, "w") as f:
        f.write(str(budget) + "\n")
        for e in expenses:
            f.write(f"{e['date']},{e['category']},{e['amount']},{e['note']}\n")
    print(len(expenses), "record(s) saved to", FILE)


def load_file():
    """Loads records from the text file."""
    global budget
    try:
        with open(FILE) as f:
            lines = f.read().splitlines()
    except FileNotFoundError:
        print("No saved file found.")
        return
    budget = float(lines[0])
    expenses.clear()
    for ln in lines[1:]:
        d, c, a, n = ln.split(",", 3)
        expenses.append({"date": d, "category": c, "amount": float(a), "note": n})
    print(len(expenses), "record(s) loaded from", FILE)


# ----------------------------- main program -----------------------------
banner()
budget = read_amount("Enter your monthly budget (Rs.): ") or 3000.0
menu = {"1": add_expense, "2": show_all, "3": category_summary, "4": search_expense,
        "5": edit_delete, "6": sort_expenses, "7": budget_status, "8": saving_tips,
        "9": save_file, "10": load_file}
while True:
    print("\n1.Add  2.View  3.Summary  4.Search  5.Edit/Delete  6.Sort")
    print("7.Budget  8.Tips  9.Save  10.Load  0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        save_file()
        print("Thank you for using Expense Tracker!")
        break
    elif ch in menu:
        menu[ch]()
    else:
        print("Invalid choice, try again.")

        
  1. Start
  2. Read monthly budget
  3. Display main menu and read choice
  4. Choice is 1 (Add)? → No: go to the matching menu option
  5. Read date, category, amount, note and append record
  6. Summary - total per category, share % and bar chart
  7. Search / edit / delete / sort records as selected
  8. Total > budget? → No: show remaining budget
  9. Show budget warning and saving tips
  10. Save records to expenses.txt
  11. Choice is 0 (Exit)? → No: show menu again
  12. Stop
#Test case / inputExpected resultStatus
1Budget 5000; add Food 450Record stored, confirmation printedPASS
2Amount entered as 'abc''Invalid amount' message, record not addedPASS
3Category 'games'Stored under 'Other' categoryPASS
4Category summaryTotals and % share add up to 100 %PASS
5Search 'bus'Matching travel record shownPASS
6Edit record 2 to 300Amount updated and shown in listPASS
7Delete record 4Record removed; count reduces by 1PASS
8Spending above 80 % of budgetWarning message printedPASS
9Save then LoadSame number of records read back from expenses.txtPASS
10Choice 15'Invalid choice' and menu repeatsPASS
โš  Limitations
  • Data is stored in a plain text file - anyone with access can read it
  • Only one user and one month are handled at a time
  • Dates are accepted as text; no calendar validation
  • No graphical user interface
๐Ÿš€ Future scope
  • Store data in a MySQL table and generate month-wise reports
  • Add a graphical interface using Tkinter
  • Plot pie and bar charts with Matplotlib
  • Export the monthly statement as a PDF / CSV for parents

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: CATEGORIES, FILE, expenses, budget.
  2. 13 functions are defined (lines 13โ€“183) - Python stores them but does NOT run them yet.
  3. Main program starts at line 187: banner() - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
line(ch, n)13โ€“15Prints a separator line.banner(), show_all()
banner()18โ€“22Shows the title of the application.main program
read_amount(prompt)25โ€“35Reads a positive amount; returns None for invalid input.add_expense(), edit_delete(), main program
add_expense()38โ€“50Adds one expense record to the list.main program (menu)
show_all(data)53โ€“64Displays the records in a table.search_expense(), edit_delete(), sort_expenses(), main program (menu)
category_summary()67โ€“83Shows total, share and a text bar chart for every category.main program (menu)
search_expense()86โ€“91Searches by category or by a word present in the note.main program (menu)
edit_delete()94โ€“115Edits the amount of a record or deletes it.main program (menu)
sort_expenses()118โ€“124Sorts by amount (high to low) or by date.main program (menu)
budget_status()127โ€“138Compares spending with the budget.main program (menu)
saving_tips()141โ€“157Gives tips for the category where most money is spent.main program (menu)
save_file()160โ€“166Saves all records to the text file.main program (menu), main program
load_file()169โ€“183Loads records from the text file.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
187
banner()
๐Ÿงฎ Store / Calculate Calls our own function banner() - shows the title of the application
188
budget = read_amount("Enter your monthly budget (Rs.): ") or 3000.0
๐Ÿงฎ Store / Calculate Stores the value of read_amount("Enter your monthly budget (Rs.):โ€ฆ, or 3000.0 if the first one is empty / None / 0 in variable budget
189
menu = {"1": add_expense, "2": show_all, "3": category_summary, "4": search_expense,
        "5": edit_delete, "6": sort_expenses, "7": budget_status, "8": sโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_expense, "2": show_all, "3": categoโ€ฆ in variable menu
192
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
193
print("\n1.Add  2.View  3.Summary  4.Search  5.Edit/Delete  6.Sort")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.View 3.Summary 4.Search 5โ€ฆ" on the screen
194
print("7.Budget  8.Tips  9.Save  10.Load  0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "7.Budget 8.Tips 9.Save 10.Load 0.โ€ฆ" on the screen
195
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
196
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
197
save_file()
๐Ÿงฎ Store / Calculate Calls our own function save_file() - saves all records to the text file
198
print("Thank you for using Expense Tracker!")
๐Ÿ–ฅ๏ธ Output Displays the text "Thank you for using Expense Trackโ€ฆ" on the screen
199
break
๐Ÿ” Loop BREAK - leaves the loop immediately
200
elif ch in menu:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is present in menu
201
menu[ch]()
๐Ÿงฎ Store / Calculate Calls menu[ch]()
202
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
203
print("Invalid choice, try again.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice, try again." on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: banner() โ†’ line() ร—2 โ†’ read_amount()
    shows: PERSONAL EXPENSE TRACKER - KV Student Edition
  2. You type 5000 at Enter your monthly budget (Rs.):
    shows: 1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort (+1 more lines)
  3. You type 1 at Enter choice:
    runs: add_expense()
  4. You type 01-07-2026 at Date (dd-mm-yyyy) :
  5. You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  6. You type 450 at Amount (Rs.) :
  7. You type Lunch with friends at Note :
    shows: Expense added. Total records: 1 (+2 more lines)
  8. You type 1 at Enter choice:
    runs: add_expense()
  9. You type 02-07-2026 at Date (dd-mm-yyyy) :
  10. You type Travel at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  11. You type 120 at Amount (Rs.) :
  12. You type Bus pass top-up at Note :
    shows: Expense added. Total records: 2 (+2 more lines)
  13. You type 1 at Enter choice:
    runs: add_expense()
  14. You type 03-07-2026 at Date (dd-mm-yyyy) :
  15. You type Study at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  16. You type 650 at Amount (Rs.) :
  17. You type Reference books at Note :
    shows: Expense added. Total records: 3 (+2 more lines)
  18. You type 1 at Enter choice:
    runs: add_expense()
  19. You type 04-07-2026 at Date (dd-mm-yyyy) :
  20. You type games at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
    shows: Unknown category - saved under 'Other'.
  21. You type 300 at Amount (Rs.) :
  22. You type Mobile game coins at Note :
    shows: Expense added. Total records: 4 (+2 more lines)
  23. You type 1 at Enter choice:
    runs: add_expense()
  24. You type 05-07-2026 at Date (dd-mm-yyyy) :
  25. You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  26. You type abc at Amount (Rs.) :
    shows: Invalid amount! Please enter digits only. (+2 more lines)
  27. You type 1 at Enter choice:
    runs: add_expense()
  28. You type 06-07-2026 at Date (dd-mm-yyyy) :
  29. You type Health at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  30. You type 800 at Amount (Rs.) :
  31. You type Doctor fees at Note :
    shows: Expense added. Total records: 5 (+2 more lines)
  32. You type 1 at Enter choice:
    runs: add_expense()
  33. You type 07-07-2026 at Date (dd-mm-yyyy) :
  34. You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other
    runs: read_amount()
  35. You type 1200 at Amount (Rs.) :
  36. You type Birthday party at Note :
    shows: Expense added. Total records: 6 (+2 more lines)
  37. You type 2 at Enter choice:
    runs: show_all() โ†’ line() ร—2
    shows: No Date Category Amount Note (+9 more lines)
  38. You type 3 at Enter choice:
    runs: category_summary()
    shows: ----- CATEGORY SUMMARY ----- (+9 more lines)
  39. You type 4 at Enter choice:
    runs: search_expense()
  40. You type bus at Enter category or word to search:
    runs: show_all() โ†’ line() ร—2
    shows: 1 matching record(s) (+5 more lines)

โ€ฆ and 17 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
line() - lines 13โ€“15
LineCodeWhat it does
13
def line(ch="-", n=60):
๐Ÿงฉ Function DEFINES a function line(ch, n). Python only remembers it here - its body runs later, each time line() is called.
15
print(ch * n)
๐Ÿ–ฅ๏ธ Output Displays the value of ch * n on the screen
banner() - lines 18โ€“22
LineCodeWhat it does
18
def banner():
๐Ÿงฉ Function DEFINES a function banner(). Python only remembers it here - its body runs later, each time banner() is called.
20
line("=")
๐Ÿงฎ Store / Calculate Calls our own function line("=") - prints a separator line
21
print("        PERSONAL EXPENSE TRACKER  -  KV Student Edition")
๐Ÿ–ฅ๏ธ Output Displays the text "PERSONAL EXPENSE TRACKER - KV Stuโ€ฆ" on the screen
22
line("=")
๐Ÿงฎ Store / Calculate Calls our own function line("=") - prints a separator line
read_amount() - lines 25โ€“35
LineCodeWhat it does
25
def read_amount(prompt):
๐Ÿงฉ Function DEFINES a function read_amount(prompt). Python only remembers it here - its body runs later, each time read_amount() is called.
27
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
28
amt = float(input(prompt))
โŒจ๏ธ Input Shows prompt, reads what the user types, and float() converts that text into a decimal number; the number is stored in variable amt
29
if amt <= 0:
๐Ÿ”€ Decision CHECKS whether amt is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
30
print("Amount must be greater than zero.")
๐Ÿ–ฅ๏ธ Output Displays the text "Amount must be greater than zero." on the screen
31
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
32
return amt
๐Ÿงฉ Function Sends back (returns) the value of amt to the line that called the function
33
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
34
print("Invalid amount! Please enter digits only.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid amount! Please enter digiโ€ฆ" on the screen
35
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
add_expense() - lines 38โ€“50
LineCodeWhat it does
38
def add_expense():
๐Ÿงฉ Function DEFINES a function add_expense(). Python only remembers it here - its body runs later, each time add_expense() is called.
40
date = input("Date (dd-mm-yyyy)       : ")
โŒจ๏ธ Input Shows the message "Date (dd-mm-yyyy) : " and waits; whatever the user types comes back as TEXT (string); it is stored in variable date
41
cat = input("Category " + str(CATEGORIES) + ": ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cat
42
if cat not in CATEGORIES:
๐Ÿ”€ Decision CHECKS whether cat is not present in CATEGORIES. If True, the indented lines below run; otherwise they are skipped
43
print("Unknown category - saved under 'Other'.")
๐Ÿ–ฅ๏ธ Output Displays the text "Unknown category - saved under 'Oโ€ฆ" on the screen
44
cat = "Other"
๐Ÿงฎ Store / Calculate Stores the text "Other" in variable cat
45
amt = read_amount("Amount (Rs.)            : ")
๐Ÿงฎ Store / Calculate Calls our own function read_amount("Amount (Rs.) : ") - reads a positive amount; returns none for invalid input; the result is stored in variable amt
46
if amt is None:
๐Ÿ”€ Decision CHECKS whether amt is None. If True, the indented lines below run; otherwise they are skipped
47
return
๐Ÿงฉ Function Ends the function and goes back to the caller
48
note = input("Note                    : ")
โŒจ๏ธ Input Shows the message "Note : " and waits; whatever the user types comes back as TEXT (string); it is stored in variable note
49
expenses.append({"date": date, "category": cat, "amount": amt, "note": note})
๐Ÿงฎ Store / Calculate Adds {"date": date, "category": cat, "amount": amtโ€ฆ at the end of list expenses
50
print("Expense added. Total records:", len(expenses))
๐Ÿ–ฅ๏ธ Output Displays the text "Expense added. Total records:", then the value of len(expenses) on the screen
show_all() - lines 53โ€“64
LineCodeWhat it does
53
def show_all(data=None):
๐Ÿงฉ Function DEFINES a function show_all(data). Python only remembers it here - its body runs later, each time show_all() is called.
55
data = expenses if data is None else data
๐Ÿงฎ Store / Calculate Stores either expenses or data depending on data is None in variable data
56
if not data:
๐Ÿ”€ Decision CHECKS whether data is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
57
print("No expenses recorded yet.")
๐Ÿ–ฅ๏ธ Output Displays the text "No expenses recorded yet." on the screen
58
return
๐Ÿงฉ Function Ends the function and goes back to the caller
59
print(f"{'No':<4}{'Date':<12}{'Category':<10}{'Amount':>9}  Note")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'No':<4}{'Date':<12}{'Category':<10}{'Amouโ€ฆ with the values filled into { } on the screen
60
line()
๐Ÿงฎ Store / Calculate Calls our own function line() - prints a separator line
61
for i, e in enumerate(data, start=1):
๐Ÿ” Loop LOOP over data with position: in each round i, e get (position, item)
62
print(f"{i:<4}{e['date']:<12}{e['category']:<10}{e['amount']:>9.2f}  {e['note']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i:<4}{e['date']:<12}{e['category']:<10}{e[โ€ฆ with the values filled into { } on the screen
63
line()
๐Ÿงฎ Store / Calculate Calls our own function line() - prints a separator line
64
print(f"{'TOTAL':<26}{sum(e['amount'] for e in data):>9.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'TOTAL':<26}{sum(e['amount'] for e in dataโ€ฆ with the values filled into { } on the screen
category_summary() - lines 67โ€“83
LineCodeWhat it does
67
def category_summary():
๐Ÿงฉ Function DEFINES a function category_summary(). Python only remembers it here - its body runs later, each time category_summary() is called.
69
if not expenses:
๐Ÿ”€ Decision CHECKS whether expenses is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
70
print("No expenses recorded yet.")
๐Ÿ–ฅ๏ธ Output Displays the text "No expenses recorded yet." on the screen
71
return
๐Ÿงฉ Function Ends the function and goes back to the caller
72
summary = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable summary
73
for e in expenses:
๐Ÿ” Loop LOOP: takes each item of expenses one-by-one into e and runs the indented block for it
74
summary[e["category"]] = summary.get(e["category"], 0) + e["amount"]
๐Ÿงฎ Store / Calculate Puts the value of summary.get(e["category"], 0) + e["amount"] (calculated using +) into summary[e["category"]] (item e["category"] of summary)
75
total = sum(summary.values())
๐Ÿงฎ Store / Calculate Adds up all the values in summary.values(); the result is stored in variable total
76
print("\n----- CATEGORY SUMMARY -----")
๐Ÿ–ฅ๏ธ Output Displays the text "----- CATEGORY SUMMARY -----" on the screen
77
for cat, amt in sorted(summary.items(), key=lambda x: x[1], reverse=True):
๐Ÿ” Loop LOOP: takes each item of sorted(summary.items(), key=lambda x: x[1], rโ€ฆ one-by-one into cat, amt and runs the indented block for it
78
share = amt / total * 100
๐Ÿงฎ Store / Calculate Stores the value of amt / total * 100 (calculated using ร—) in variable share
79
print(f"{cat:<8} Rs.{amt:>8.2f}  {share:5.1f}%  " + "#" * int(share // 4))
๐Ÿ–ฅ๏ธ Output Displays the value of f"{cat:<8} Rs.{amt:>8.2f} {share:5.1f}% " + "โ€ฆ on the screen
80
top = max(summary, key=summary.get)
๐Ÿงฎ Store / Calculate Finds the largest value among summary; the result is stored in variable top
81
low = min(summary, key=summary.get)
๐Ÿงฎ Store / Calculate Finds the smallest value among summary; the result is stored in variable low
82
print("Highest spending category:", top, "( Rs.", summary[top], ")")
๐Ÿ–ฅ๏ธ Output Displays the text "Highest spending category:", then the value of top, then the text "( Rs.", then the value of summary[top], then the text ")" on the screen
83
print("Lowest  spending category:", low, "( Rs.", summary[low], ")")
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest spending category:", then the value of low, then the text "( Rs.", then the value of summary[low], then the text ")" on the screen
search_expense() - lines 86โ€“91
LineCodeWhat it does
86
def search_expense():
๐Ÿงฉ Function DEFINES a function search_expense(). Python only remembers it here - its body runs later, each time search_expense() is called.
88
key = input("Enter category or word to search: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
89
found = [e for e in expenses if key in e["category"].lower() or key in e["note"].lower()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [e for e in expenses if key in e["category"].โ€ฆ in variable found
90
print(len(found), "matching record(s)")
๐Ÿ–ฅ๏ธ Output Displays the value of len(found), then the text "matching record(s)" on the screen
91
show_all(found) if found else None
๐Ÿงฎ Store / Calculate Evaluates show_all(found) if found else None
edit_delete() - lines 94โ€“115
LineCodeWhat it does
94
def edit_delete():
๐Ÿงฉ Function DEFINES a function edit_delete(). Python only remembers it here - its body runs later, each time edit_delete() is called.
96
show_all()
๐Ÿงฎ Store / Calculate Calls our own function show_all() - displays the records in a table
97
if not expenses:
๐Ÿ”€ Decision CHECKS whether expenses is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
98
return
๐Ÿงฉ Function Ends the function and goes back to the caller
99
ch = input("E = Edit amount, D = Delete : ").upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable ch
100
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
101
n = int(input("Record number: "))
โŒจ๏ธ Input Shows "Record number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
102
rec = expenses[n - 1]
๐Ÿงฎ Store / Calculate Stores the item expenses[n - 1] in variable rec
103
except (ValueError, IndexError):
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, IndexError) occurs - that error
104
print("Invalid record number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid record number." on the screen
105
return
๐Ÿงฉ Function Ends the function and goes back to the caller
106
if ch == "E":
๐Ÿ”€ Decision CHECKS whether ch is equal to "E". If True, the indented lines below run; otherwise Python jumps to the elif/else part
107
amt = read_amount("New amount: ")
๐Ÿงฎ Store / Calculate Calls our own function read_amount("New amount: ") - reads a positive amount; returns none for invalid input; the result is stored in variable amt
108
if amt:
๐Ÿ”€ Decision CHECKS whether amt is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
109
rec["amount"] = amt
๐Ÿงฎ Store / Calculate Puts the value of amt into rec["amount"] (item "amount" of rec)
110
print("Record", n, "updated.")
๐Ÿ–ฅ๏ธ Output Displays the text "Record", then the value of n, then the text "updated." on the screen
111
elif ch == "D":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "D"
112
expenses.pop(n - 1)
๐Ÿงฎ Store / Calculate Removes and returns an item at position n - 1 from expenses
113
print("Record", n, "deleted. Records left:", len(expenses))
๐Ÿ–ฅ๏ธ Output Displays the text "Record", then the value of n, then the text "deleted. Records left:", then the value of len(expenses) on the screen
114
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
115
print("Invalid option.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid option." on the screen
sort_expenses() - lines 118โ€“124
LineCodeWhat it does
118
def sort_expenses():
๐Ÿงฉ Function DEFINES a function sort_expenses(). Python only remembers it here - its body runs later, each time sort_expenses() is called.
120
ch = input("Sort by A = Amount, D = Date : ").upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable ch
121
if ch == "A":
๐Ÿ”€ Decision CHECKS whether ch is equal to "A". If True, the indented lines below run; otherwise Python jumps to the elif/else part
122
show_all(sorted(expenses, key=lambda e: e["amount"], reverse=True))
๐Ÿงฎ Store / Calculate Calls our own function show_all(sorted(expenses, keโ€ฆ) - displays the records in a table
123
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
124
show_all(sorted(expenses, key=lambda e: e["date"][6:] + e["date"][3:5] + e["date"][:2]))
๐Ÿงฎ Store / Calculate Calls our own function show_all(sorted(expenses, keโ€ฆ) - displays the records in a table
budget_status() - lines 127โ€“138
LineCodeWhat it does
127
def budget_status():
๐Ÿงฉ Function DEFINES a function budget_status(). Python only remembers it here - its body runs later, each time budget_status() is called.
129
spent = sum(e["amount"] for e in expenses)
๐Ÿงฎ Store / Calculate Adds up all the values in (e["amount"] for e in expenses); the result is stored in variable spent
130
used = spent / budget * 100 if budget else 0
๐Ÿงฎ Store / Calculate Stores either spent / budget * 100 or 0 depending on budget in variable used
131
print(f"Budget Rs.{budget:.2f} | Spent Rs.{spent:.2f} | Used {used:.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Budget Rs.{budget:.2f} | Spent Rs.{spent:.2โ€ฆ with the values filled into { } on the screen
132
print("[" + "=" * int(min(used, 100) // 5) + " " * (20 - int(min(used, 100) // 5)) + "]")
๐Ÿ–ฅ๏ธ Output Displays the value of "[" + "=" * int(min(used, 100) // 5) + " " * โ€ฆ on the screen
133
if used >= 100:
๐Ÿ”€ Decision CHECKS whether used is greater than or equal to 100. If True, the indented lines below run; otherwise Python jumps to the elif/else part
134
print("ALERT: Budget exceeded by Rs.", round(spent - budget, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "ALERT: Budget exceeded by Rs.", then the value of round(spent - budget, 2) on the screen
135
elif used >= 80:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether used is greater than or equal to 80
136
print("WARNING: More than 80% of the budget is used!")
๐Ÿ–ฅ๏ธ Output Displays the text "WARNING: More than 80% of the budโ€ฆ" on the screen
137
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
138
print("Good! Remaining budget: Rs.", round(budget - spent, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Good! Remaining budget: Rs.", then the value of round(budget - spent, 2) on the screen
saving_tips() - lines 141โ€“157
LineCodeWhat it does
141
def saving_tips():
๐Ÿงฉ Function DEFINES a function saving_tips(). Python only remembers it here - its body runs later, each time saving_tips() is called.
143
if not expenses:
๐Ÿ”€ Decision CHECKS whether expenses is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
144
print("Add some expenses first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Add some expenses first." on the screen
145
return
๐Ÿงฉ Function Ends the function and goes back to the caller
146
summary = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable summary
147
for e in expenses:
๐Ÿ” Loop LOOP: takes each item of expenses one-by-one into e and runs the indented block for it
148
summary[e["category"]] = summary.get(e["category"], 0) + e["amount"]
๐Ÿงฎ Store / Calculate Puts the value of summary.get(e["category"], 0) + e["amount"] (calculated using +) into summary[e["category"]] (item e["category"] of summary)
149
top = max(summary, key=summary.get)
๐Ÿงฎ Store / Calculate Finds the largest value among summary; the result is stored in variable top
150
tips = {"Food": "Carry lunch from home and limit eating out to weekends.",
        "Travel": "Use a monthly bus pass or walk / cycle short distances.",
     โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Food": "Carry lunch from home and limit eatโ€ฆ in variable tips
156
print("Most money goes to:", top)
๐Ÿ–ฅ๏ธ Output Displays the text "Most money goes to:", then the value of top on the screen
157
print("Tip:", tips[top])
๐Ÿ–ฅ๏ธ Output Displays the text "Tip:", then the value of tips[top] on the screen
save_file() - lines 160โ€“166
LineCodeWhat it does
160
def save_file():
๐Ÿงฉ Function DEFINES a function save_file(). Python only remembers it here - its body runs later, each time save_file() is called.
162
with open(FILE, "w") as f:
๐Ÿ“ File Opens the file FILE in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
163
f.write(str(budget) + "\n")
๐Ÿ“ File Writes str(budget) + "\n" into file f
164
for e in expenses:
๐Ÿ” Loop LOOP: takes each item of expenses one-by-one into e and runs the indented block for it
165
f.write(f"{e['date']},{e['category']},{e['amount']},{e['note']}\n")
๐Ÿ“ File Writes f"{e['date']},{e['category']},{e['amount']},{โ€ฆ into file f
166
print(len(expenses), "record(s) saved to", FILE)
๐Ÿ–ฅ๏ธ Output Displays the value of len(expenses), then the text "record(s) saved to", then the value of FILE on the screen
load_file() - lines 169โ€“183
LineCodeWhat it does
169
def load_file():
๐Ÿงฉ Function DEFINES a function load_file(). Python only remembers it here - its body runs later, each time load_file() is called.
171
global budget
๐Ÿงฉ Function Tells Python that budget means the GLOBAL variable (outside the function)
172
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
173
with open(FILE) as f:
๐Ÿ“ File Opens the file FILE in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
174
lines = f.read().splitlines()
๐Ÿ“ File Splits f.read() into a list of lines; the result is stored in variable lines
175
except FileNotFoundError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if FileNotFoundError occurs - the file does not exist
176
print("No saved file found.")
๐Ÿ–ฅ๏ธ Output Displays the text "No saved file found." on the screen
177
return
๐Ÿงฉ Function Ends the function and goes back to the caller
178
budget = float(lines[0])
๐Ÿงฎ Store / Calculate Converts lines[0] into a decimal number (float); the result is stored in variable budget
179
expenses.clear()
๐Ÿงฎ Store / Calculate Removes all items from expenses
180
for ln in lines[1:]:
๐Ÿ” Loop LOOP: takes each item of lines[1:] one-by-one into ln and runs the indented block for it
181
d, c, a, n = ln.split(",", 3)
๐Ÿงฎ Store / Calculate Breaks ln into a list of words wherever "," occurs; the result is stored in variables d, c, a, n
182
expenses.append({"date": d, "category": c, "amount": float(a), "note": n})
๐Ÿงฎ Store / Calculate Adds {"date": d, "category": c, "amount": float(a)โ€ฆ at the end of list expenses
183
print(len(expenses), "record(s) loaded from", FILE)
๐Ÿ–ฅ๏ธ Output Displays the value of len(expenses), then the text "record(s) loaded from", then the value of FILE on the screen
Q1. Why is a list of dictionaries used to store expenses?

Each expense has several fields (date, category, amount, note). A dictionary groups the fields of one record and the list keeps many records in order.

Q2. What does the get() method of a dictionary do in the summary?

summary.get(cat, 0) returns the current total of a category or 0 if the category is new, so totals can be added without a KeyError.

Q3. How is invalid amount input handled?

The input is converted inside try-except; a ValueError prints 'Invalid amount' and the record is not added.

Q4. Which function sorts the expenses by amount?

sorted(expenses, key=lambda e: e['amount'], reverse=True) returns a new list ordered from highest to lowest amount.

Q5. How is the data saved permanently?

Each record is written as one comma-separated line into expenses.txt using open() in write mode; it is read back with split(',').

Q6. What is the use of the bar chart printed with '#'?

String replication ('#' * n) gives a quick text-based visualisation of which category takes the biggest share.

02

School Grade Calculator

PYTHONFunctionsif-elifDictionariesloops
๐Ÿ“ 165 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 156 output lines๐Ÿ“„ 25+ page report

Input marks of 5 subjects for n students, compute percentage and grade using functions, store results in a dictionary, and display class topper and subject-wise average.

โœจ Features
  • Stores marks of 5 subjects for any number of students in a dictionary of dictionaries
  • Calculates total, percentage, grade (CBSE-style A1 to E) and pass / compartment / fail status
  • Class topper, subject toppers and subject-wise average, highest and lowest marks
  • Search, update marks and delete a student; rank list sorted by percentage
  • Grade distribution with a text bar chart
  • Report card of a single student with remarks
โ˜ฐ Main menu
1Add StudentReads name and marks of 5 subjects with validation (0-100)
2Result SheetShows total, percentage, grade and status of every student
3Report CardDetailed report card of one student with remarks
4Rank ListStudents sorted by percentage with rank numbers
5Subject AnalysisAverage, highest, lowest and topper of every subject
6Grade DistributionNumber of students in each grade with bar chart
7Update MarksChanges the marks of one subject of a student
8Delete StudentRemoves a student from the records
0ExitCloses the program
๐ŸŽฏ Objectives
  • Calculate percentage and grade with a function
  • Store student records in a nested dictionary
  • Find the topper and subject-wise averages using loops and max()
๐Ÿ“š Data dictionary
NameTypePurpose
resultsdict of dictStudent name -> {'marks': list of 5, 'total', 'pct', 'grade'}
SUBJECTStupleNames of the five subjects
markslist of floatMarks of one student in the five subjects
GRADESlist of tuple(minimum %, grade) pairs used by get_grade()
Why it matters: Mirrors an actual school result-preparation workflow.
# =====================================================================
#   SCHOOL GRADE CALCULATOR & RESULT ANALYSER
#   Concepts : nested dictionaries, lists, tuples, functions, loops,
#              sorting with key, string formatting
# =====================================================================

SUBJECTS = ("English", "Maths", "Physics", "Chemistry", "CS")
GRADES = [(91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"),
          (41, "C2"), (33, "D"), (0, "E")]
results = {}


def line(n=62):
    """Prints a separator line."""
    print("-" * n)


def get_grade(pct):
    """Returns the CBSE-style grade for a percentage."""
    for minimum, grade in GRADES:
        if pct >= minimum:
            return grade
    return "E"


def status_of(marks):
    """PASS, COMPARTMENT (one subject < 33) or FAIL (more than one)."""
    below = sum(1 for m in marks if m < 33)
    return "PASS" if below == 0 else ("COMPARTMENT" if below == 1 else "FAIL")


def read_marks(subject):
    """Reads marks between 0 and 100 (asks again if invalid)."""
    while True:
        try:
            m = float(input(f"  Marks in {subject:<10}: "))
            if 0 <= m <= 100:
                return m
            print("  Marks must be 0-100. Try again.")
        except ValueError:
            print("  Enter a number.")


def calculate(name):
    """Recalculates total, percentage and grade of a student."""
    r = results[name]
    r["total"] = sum(r["marks"])
    r["pct"] = r["total"] / len(SUBJECTS)
    r["grade"] = get_grade(r["pct"])
    r["status"] = status_of(r["marks"])


def add_student():
    """Adds a new student with marks of five subjects."""
    name = input("Student name: ").strip().title()
    if name in results:
        print("Student already exists.")
        return
    marks = [read_marks(s) for s in SUBJECTS]
    results[name] = {"marks": marks}
    calculate(name)
    print(f"Saved {name}: {results[name]['pct']:.2f}%  Grade {results[name]['grade']}")


def result_sheet():
    """Displays the result of all students."""
    if not results:
        print("No records.")
        return
    print(f"{'Name':<10}" + "".join(f"{s[:5]:>7}" for s in SUBJECTS) + f"{'Total':>7}{'%':>7}  Gr  Status")
    line(90)
    for name, r in results.items():
        print(f"{name:<10}" + "".join(f"{m:>7.0f}" for m in r["marks"]) +
              f"{r['total']:>7.0f}{r['pct']:>7.2f}  {r['grade']:<3} {r['status']}")
    line(90)
    print("Students:", len(results), "| Passed:", sum(1 for r in results.values() if r["status"] == "PASS"))


def report_card():
    """Prints the report card of one student."""
    name = input("Enter name: ").strip().title()
    if name not in results:
        print("Student not found.")
        return
    r = results[name]
    line(); print(f"REPORT CARD : {name}".center(62)); line()
    for s, m in zip(SUBJECTS, r["marks"]):
        print(f"{s:<12}{m:>6.0f}   Grade {get_grade(m)}")
    line()
    print(f"Total {r['total']:.0f}/500   Percentage {r['pct']:.2f}%   Grade {r['grade']}   {r['status']}")
    best = SUBJECTS[r["marks"].index(max(r["marks"]))]
    weak = SUBJECTS[r["marks"].index(min(r["marks"]))]
    print("Best subject:", best, "| Needs attention:", weak)
    remark = ("Outstanding performance!" if r["pct"] >= 90 else "Very good, keep it up." if r["pct"] >= 75
              else "Good, can do better." if r["pct"] >= 50 else "Needs regular practice and guidance.")
    print("Remarks:", remark)


def rank_list():
    """Shows students sorted by percentage."""
    order = sorted(results, key=lambda n: results[n]["pct"], reverse=True)
    for rank, name in enumerate(order, start=1):
        print(f"{rank:>2}. {name:<10} {results[name]['pct']:6.2f}%  {results[name]['grade']}")
    if order:
        print("Class topper:", order[0])


def subject_analysis():
    """Average, highest, lowest and topper of each subject."""
    if not results:
        print("No records.")
        return
    print(f"{'Subject':<11}{'Average':>8}{'High':>6}{'Low':>6}  Topper")
    for i, s in enumerate(SUBJECTS):
        col = [r["marks"][i] for r in results.values()]
        top = max(results, key=lambda n: results[n]["marks"][i])
        print(f"{s:<11}{sum(col) / len(col):>8.2f}{max(col):>6.0f}{min(col):>6.0f}  {top}")


def grade_distribution():
    """Counts students in each grade and draws a text bar chart."""
    for _, g in GRADES:
        n = sum(1 for r in results.values() if r["grade"] == g)
        if n:
            print(f"{g:<3} {'#' * (n * 4)} {n}")


def update_marks():
    """Updates marks of one subject."""
    name = input("Enter name: ").strip().title()
    if name not in results:
        print("Student not found.")
        return
    for i, s in enumerate(SUBJECTS, start=1):
        print(f"{i}. {s}", end="  ")
    print()
    k = int(input("Subject number: ")) - 1
    results[name]["marks"][k] = read_marks(SUBJECTS[k])
    calculate(name)
    print("Updated:", name, f"{results[name]['pct']:.2f}%", results[name]["grade"])


def delete_student():
    """Deletes a student record."""
    name = input("Enter name to delete: ").strip().title()
    if results.pop(name, None):
        print(name, "deleted. Students left:", len(results))
    else:
        print("Student not found.")


menu = {"1": add_student, "2": result_sheet, "3": report_card, "4": rank_list,
        "5": subject_analysis, "6": grade_distribution, "7": update_marks, "8": delete_student}
print("=" * 62)
print("SCHOOL GRADE CALCULATOR & RESULT ANALYSER".center(62))
print("=" * 62)
while True:
    print("\n1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades")
    print("7.Update 8.Delete 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Good luck for the exams!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is 1 (Add)? → No: go to the selected option
  4. Read name and 5 marks (0-100)
  5. total, percentage = total / 5, grade and status
  6. Store in the results dictionary
  7. Reports - result sheet, rank list, subject analysis, grade chart
  8. Update / delete records when chosen
  9. Choice is 0? → No: show menu again
  10. Stop
#Test case / inputExpected resultStatus
1Marks 95, 92, 88, 97, 90Total 462, 92.4 %, grade A1, PASSPASS
2Mark 120 entered'Marks must be 0-100' and asked againPASS
3One subject below 33Status 'COMPARTMENT'PASS
4Rank listStudents in descending order of %PASS
5Subject analysisAverage/highest/lowest per subject printedPASS
6Report card of 'Rahul'Full card with remarks shownPASS
7Update Maths of Sara to 85New total and grade recalculatedPASS
8Delete 'Vikas'Student removed; count reducedPASS
9Report card of unknown name'Student not found'PASS
โš  Limitations
  • Data is lost when the program is closed (no file storage)
  • Number of subjects is fixed at five
  • Names must be unique
  • Grading rules are fixed in the code
๐Ÿš€ Future scope
  • Save results in a CSV file / MySQL table
  • Print report cards as PDF
  • Add co-scholastic grades and attendance
  • Draw subject-wise charts with Matplotlib

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: SUBJECTS, GRADES, results.
  2. 13 functions are defined (lines 13โ€“149) - Python stores them but does NOT run them yet.
  3. Main program starts at line 152: menu = {"1": add_student, "2": result_sheet, "3": report_card, "4": ra - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
line(n)13โ€“15Prints a separator line.result_sheet(), report_card()
get_grade(pct)18โ€“23Returns the CBSE-style grade for a percentage.calculate(), report_card()
status_of(marks)26โ€“29PASS, COMPARTMENT (one subject < 33) or FAIL (more than one).calculate()
read_marks(subject)32โ€“41Reads marks between 0 and 100 (asks again if invalid).add_student(), update_marks()
calculate(name)44โ€“50Recalculates total, percentage and grade of a student.add_student(), update_marks()
add_student()53โ€“62Adds a new student with marks of five subjects.main program (menu)
result_sheet()65โ€“76Displays the result of all students.main program (menu)
report_card()79โ€“96Prints the report card of one student.main program (menu)
rank_list()99โ€“105Shows students sorted by percentage.main program (menu)
subject_analysis()108โ€“117Average, highest, lowest and topper of each subject.main program (menu)
grade_distribution()120โ€“125Counts students in each grade and draws a text bar chart.main program (menu)
update_marks()128โ€“140Updates marks of one subject.main program (menu)
delete_student()143โ€“149Deletes a student record.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
152
menu = {"1": add_student, "2": result_sheet, "3": report_card, "4": rank_list,
        "5": subject_analysis, "6": grade_distribution, "7": update_marks, "8"โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_student, "2": result_sheet, "3": reโ€ฆ in variable menu
154
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
155
print("SCHOOL GRADE CALCULATOR & RESULT ANALYSER".center(62))
๐Ÿ–ฅ๏ธ Output Displays the value of "SCHOOL GRADE CALCULATOR & RESULT ANALYSER".cโ€ฆ on the screen
156
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
157
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
158
print("\n1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Result 3.Report Card 4.Raโ€ฆ" on the screen
159
print("7.Update 8.Delete 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "7.Update 8.Delete 0.Exit" on the screen
160
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
161
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
162
print("Good luck for the exams!")
๐Ÿ–ฅ๏ธ Output Displays the text "Good luck for the exams!" on the screen
163
break
๐Ÿ” Loop BREAK - leaves the loop immediately
164
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: SCHOOL GRADE CALCULATOR & RESULT ANALYSER (+2 more lines)
  2. You type 1 at Enter choice:
    runs: add_student()
  3. You type Sara at Student name:
    runs: read_marks()
  4. You type 95 at Marks in English :
    runs: read_marks()
  5. You type 92 at Marks in Maths :
    runs: read_marks()
  6. You type 88 at Marks in Physics :
    runs: read_marks()
  7. You type 97 at Marks in Chemistry :
    runs: read_marks()
  8. You type 90 at Marks in CS :
    runs: calculate() โ†’ get_grade() โ†’ status_of()
    shows: Saved Sara: 92.40% Grade A1 (+2 more lines)
  9. You type 1 at Enter choice:
    runs: add_student()
  10. You type Rahul at Student name:
    runs: read_marks()
  11. You type 78 at Marks in English :
    runs: read_marks()
  12. You type 120 at Marks in Maths :
    shows: Marks must be 0-100. Try again.
  13. You type 82 at Marks in Maths :
    runs: read_marks()
  14. You type 69 at Marks in Physics :
    runs: read_marks()
  15. You type 74 at Marks in Chemistry :
    runs: read_marks()
  16. You type 80 at Marks in CS :
    runs: calculate() โ†’ get_grade() โ†’ status_of()
    shows: Saved Rahul: 76.60% Grade B1 (+2 more lines)
  17. You type 1 at Enter choice:
    runs: add_student()
  18. You type Vikas at Student name:
    runs: read_marks()
  19. You type 45 at Marks in English :
    runs: read_marks()
  20. You type 28 at Marks in Maths :
    runs: read_marks()
  21. You type 51 at Marks in Physics :
    runs: read_marks()
  22. You type 40 at Marks in Chemistry :
    runs: read_marks()
  23. You type 38 at Marks in CS :
    runs: calculate() โ†’ get_grade() โ†’ status_of()
    shows: Saved Vikas: 40.40% Grade D (+2 more lines)
  24. You type 1 at Enter choice:
    runs: add_student()
  25. You type Meena at Student name:
    runs: read_marks()
  26. You type 88 at Marks in English :
    runs: read_marks()
  27. You type 91 at Marks in Maths :
    runs: read_marks()
  28. You type 79 at Marks in Physics :
    runs: read_marks()
  29. You type 85 at Marks in Chemistry :
    runs: read_marks()
  30. You type 93 at Marks in CS :
    runs: calculate() โ†’ get_grade() โ†’ status_of()
    shows: Saved Meena: 87.20% Grade A2 (+2 more lines)
  31. You type 2 at Enter choice:
    runs: result_sheet() โ†’ line() ร—2
    shows: Name Engli Maths Physi Chemi CS Total % Gr Status (+7 more lines)
  32. You type 3 at Enter choice:
    runs: report_card()
  33. You type Rahul at Enter name:
    runs: line() ร—2 โ†’ get_grade() ร—5 โ†’ line()
    shows: REPORT CARD : Rahul (+10 more lines)
  34. You type 4 at Enter choice:
    runs: rank_list()
    shows: 1. Sara 92.40% A1 (+6 more lines)
  35. You type 5 at Enter choice:
    runs: subject_analysis()
    shows: Subject Average High Low Topper (+7 more lines)
  36. You type 6 at Enter choice:
    runs: grade_distribution()
    shows: A1 #### 1 (+5 more lines)
  37. You type 7 at Enter choice:
    runs: update_marks()
  38. You type Sara at Enter name:
    shows: 1. English 2. Maths 3. Physics 4. Chemistry 5. CS
  39. You type 2 at Subject number:
    runs: read_marks()
  40. You type 85 at Marks in Maths :
    runs: calculate() โ†’ get_grade() โ†’ status_of()
    shows: Updated: Sara 91.00% A1 (+2 more lines)

โ€ฆ and 8 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
line() - lines 13โ€“15
LineCodeWhat it does
13
def line(n=62):
๐Ÿงฉ Function DEFINES a function line(n). Python only remembers it here - its body runs later, each time line() is called.
15
print("-" * n)
๐Ÿ–ฅ๏ธ Output Displays the value of "-" * n on the screen
get_grade() - lines 18โ€“23
LineCodeWhat it does
18
def get_grade(pct):
๐Ÿงฉ Function DEFINES a function get_grade(pct). Python only remembers it here - its body runs later, each time get_grade() is called.
20
for minimum, grade in GRADES:
๐Ÿ” Loop LOOP: takes each item of GRADES one-by-one into minimum, grade and runs the indented block for it
21
if pct >= minimum:
๐Ÿ”€ Decision CHECKS whether pct is greater than or equal to minimum. If True, the indented lines below run; otherwise they are skipped
22
return grade
๐Ÿงฉ Function Sends back (returns) the value of grade to the line that called the function
23
return "E"
๐Ÿงฉ Function Sends back (returns) the text "E" to the line that called the function
status_of() - lines 26โ€“29
LineCodeWhat it does
26
def status_of(marks):
๐Ÿงฉ Function DEFINES a function status_of(marks). Python only remembers it here - its body runs later, each time status_of() is called.
28
below = sum(1 for m in marks if m < 33)
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for m in marks if m < 33); the result is stored in variable below
29
return "PASS" if below == 0 else ("COMPARTMENT" if below == 1 else "FAIL")
๐Ÿงฉ Function Sends back (returns) either "PASS" or "COMPARTMENT" if below == 1 else "FAIL" depending on below == 0 to the line that called the function
read_marks() - lines 32โ€“41
LineCodeWhat it does
32
def read_marks(subject):
๐Ÿงฉ Function DEFINES a function read_marks(subject). Python only remembers it here - its body runs later, each time read_marks() is called.
34
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
35
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
36
m = float(input(f"  Marks in {subject:<10}: "))
โŒจ๏ธ Input Shows f" Marks in {subject:<10}: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable m
37
if 0 <= m <= 100:
๐Ÿ”€ Decision CHECKS whether 0 <= m <= 100 is True. If True, the indented lines below run; otherwise they are skipped
38
return m
๐Ÿงฉ Function Sends back (returns) the value of m to the line that called the function
39
print("  Marks must be 0-100. Try again.")
๐Ÿ–ฅ๏ธ Output Displays the text "Marks must be 0-100. Try again." on the screen
40
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
41
print("  Enter a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a number." on the screen
calculate() - lines 44โ€“50
LineCodeWhat it does
44
def calculate(name):
๐Ÿงฉ Function DEFINES a function calculate(name). Python only remembers it here - its body runs later, each time calculate() is called.
46
r = results[name]
๐Ÿงฎ Store / Calculate Stores the item results[name] in variable r
47
r["total"] = sum(r["marks"])
๐Ÿงฎ Store / Calculate Adds up all the values in r["marks"]; the result is put into r["total"] (item "total" of r)
48
r["pct"] = r["total"] / len(SUBJECTS)
๐Ÿงฎ Store / Calculate Puts the value of r["total"] / len(SUBJECTS) (calculated using รท) into r["pct"] (item "pct" of r)
49
r["grade"] = get_grade(r["pct"])
๐Ÿงฎ Store / Calculate Calls our own function get_grade(r["pct"]) - returns the cbse-style grade for a percentage; the result is put into r["grade"] (item "grade" of r)
50
r["status"] = status_of(r["marks"])
๐Ÿงฎ Store / Calculate Calls our own function status_of(r["marks"]) - pass, compartment (one subject < 33) or fail (more than one); the result is put into r["status"] (item "status" of r)
add_student() - lines 53โ€“62
LineCodeWhat it does
53
def add_student():
๐Ÿงฉ Function DEFINES a function add_student(). Python only remembers it here - its body runs later, each time add_student() is called.
55
name = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
56
if name in results:
๐Ÿ”€ Decision CHECKS whether name is present in results. If True, the indented lines below run; otherwise they are skipped
57
print("Student already exists.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student already exists." on the screen
58
return
๐Ÿงฉ Function Ends the function and goes back to the caller
59
marks = [read_marks(s) for s in SUBJECTS]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [read_marks(s) for s in SUBJECTS] in variable marks
60
results[name] = {"marks": marks}
๐Ÿงฎ Store / Calculate Puts a dictionary {"marks": marks} into results[name] (item name of results)
61
calculate(name)
๐Ÿงฎ Store / Calculate Calls our own function calculate(name) - recalculates total, percentage and grade of a student
62
print(f"Saved {name}: {results[name]['pct']:.2f}%  Grade {results[name]['grade']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Saved {name}: {results[name]['pct']:.2f}% Gโ€ฆ with the values filled into { } on the screen
result_sheet() - lines 65โ€“76
LineCodeWhat it does
65
def result_sheet():
๐Ÿงฉ Function DEFINES a function result_sheet(). Python only remembers it here - its body runs later, each time result_sheet() is called.
67
if not results:
๐Ÿ”€ Decision CHECKS whether results is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
68
print("No records.")
๐Ÿ–ฅ๏ธ Output Displays the text "No records." on the screen
69
return
๐Ÿงฉ Function Ends the function and goes back to the caller
70
print(f"{'Name':<10}" + "".join(f"{s[:5]:>7}" for s in SUBJECTS) + f"{'Total':>7}{'%':>7}  Gr  Status")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{'Name':<10}" + "".join(f"{s[:5]:>7}" for sโ€ฆ on the screen
71
line(90)
๐Ÿงฎ Store / Calculate Calls our own function line(90) - prints a separator line
72
for name, r in results.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary results; name, r get one pair each round
73
print(f"{name:<10}" + "".join(f"{m:>7.0f}" for m in r["marks"]) +
      f"{r['total']:>7.0f}{r['pct']:>7.2f}  {r['grade']:<3} {r['status']}")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{name:<10}" + "".join(f"{m:>7.0f}" for m inโ€ฆ on the screen
75
line(90)
๐Ÿงฎ Store / Calculate Calls our own function line(90) - prints a separator line
76
print("Students:", len(results), "| Passed:", sum(1 for r in results.values() if r["status"] == "PASS"))
๐Ÿ–ฅ๏ธ Output Displays the text "Students:", then the value of len(results), then the text "| Passed:", then the value of sum(1 for r in results.values() if r["status"โ€ฆ on the screen
report_card() - lines 79โ€“96
LineCodeWhat it does
79
def report_card():
๐Ÿงฉ Function DEFINES a function report_card(). Python only remembers it here - its body runs later, each time report_card() is called.
81
name = input("Enter name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
82
if name not in results:
๐Ÿ”€ Decision CHECKS whether name is not present in results. If True, the indented lines below run; otherwise they are skipped
83
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
84
return
๐Ÿงฉ Function Ends the function and goes back to the caller
85
r = results[name]
๐Ÿงฎ Store / Calculate Stores the item results[name] in variable r
86
line(); print(f"REPORT CARD : {name}".center(62)); line()
๐Ÿ–ฅ๏ธ Output Calls our own function line() - prints a separator line
86
line(); print(f"REPORT CARD : {name}".center(62)); line()
๐Ÿ–ฅ๏ธ Output Displays the value of f"REPORT CARD : {name}".center(62) on the screen
86
line(); print(f"REPORT CARD : {name}".center(62)); line()
๐Ÿ–ฅ๏ธ Output Calls our own function line() - prints a separator line
87
for s, m in zip(SUBJECTS, r["marks"]):
๐Ÿ” Loop LOOP that walks through SUBJECTS, r["marks"] together; s, m get one item from each
88
print(f"{s:<12}{m:>6.0f}   Grade {get_grade(m)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s:<12}{m:>6.0f} Grade {get_grade(m)}" with the values filled into { } on the screen
89
line()
๐Ÿงฎ Store / Calculate Calls our own function line() - prints a separator line
90
print(f"Total {r['total']:.0f}/500   Percentage {r['pct']:.2f}%   Grade {r['grade']}   {r['status']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Total {r['total']:.0f}/500 Percentage {r['pโ€ฆ with the values filled into { } on the screen
91
best = SUBJECTS[r["marks"].index(max(r["marks"]))]
๐Ÿงฎ Store / Calculate Stores the item SUBJECTS[r["marks"].index(max(r["marks"]))] in variable best
92
weak = SUBJECTS[r["marks"].index(min(r["marks"]))]
๐Ÿงฎ Store / Calculate Stores the item SUBJECTS[r["marks"].index(min(r["marks"]))] in variable weak
93
print("Best subject:", best, "| Needs attention:", weak)
๐Ÿ–ฅ๏ธ Output Displays the text "Best subject:", then the value of best, then the text "| Needs attention:", then the value of weak on the screen
94
remark = ("Outstanding performance!" if r["pct"] >= 90 else "Very good, keep it up." if r["pct"] >= 75
          else "Good, can do better." if r["pct"] >= 5โ€ฆ
๐Ÿงฎ Store / Calculate Stores either "Outstanding performance!" or "Very good, keep it up." if r["pct"] >= 75 elโ€ฆ depending on r["pct"] >= 90 in variable remark
96
print("Remarks:", remark)
๐Ÿ–ฅ๏ธ Output Displays the text "Remarks:", then the value of remark on the screen
rank_list() - lines 99โ€“105
LineCodeWhat it does
99
def rank_list():
๐Ÿงฉ Function DEFINES a function rank_list(). Python only remembers it here - its body runs later, each time rank_list() is called.
101
order = sorted(results, key=lambda n: results[n]["pct"], reverse=True)
๐Ÿงฎ Store / Calculate Makes a new sorted list from results; the result is stored in variable order
102
for rank, name in enumerate(order, start=1):
๐Ÿ” Loop LOOP over order with position: in each round rank, name get (position, item)
103
print(f"{rank:>2}. {name:<10} {results[name]['pct']:6.2f}%  {results[name]['grade']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{rank:>2}. {name:<10} {results[name]['pct']โ€ฆ with the values filled into { } on the screen
104
if order:
๐Ÿ”€ Decision CHECKS whether order is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
105
print("Class topper:", order[0])
๐Ÿ–ฅ๏ธ Output Displays the text "Class topper:", then the value of order[0] on the screen
subject_analysis() - lines 108โ€“117
LineCodeWhat it does
108
def subject_analysis():
๐Ÿงฉ Function DEFINES a function subject_analysis(). Python only remembers it here - its body runs later, each time subject_analysis() is called.
110
if not results:
๐Ÿ”€ Decision CHECKS whether results is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
111
print("No records.")
๐Ÿ–ฅ๏ธ Output Displays the text "No records." on the screen
112
return
๐Ÿงฉ Function Ends the function and goes back to the caller
113
print(f"{'Subject':<11}{'Average':>8}{'High':>6}{'Low':>6}  Topper")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Subject':<11}{'Average':>8}{'High':>6}{'Lโ€ฆ with the values filled into { } on the screen
114
for i, s in enumerate(SUBJECTS):
๐Ÿ” Loop LOOP over SUBJECTS with position: in each round i, s get (position, item)
115
col = [r["marks"][i] for r in results.values()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [r["marks"][i] for r in results.values()] in variable col
116
top = max(results, key=lambda n: results[n]["marks"][i])
๐Ÿงฎ Store / Calculate Finds the largest value among results; the result is stored in variable top
117
print(f"{s:<11}{sum(col) / len(col):>8.2f}{max(col):>6.0f}{min(col):>6.0f}  {top}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s:<11}{sum(col) / len(col):>8.2f}{max(col)โ€ฆ with the values filled into { } on the screen
grade_distribution() - lines 120โ€“125
LineCodeWhat it does
120
def grade_distribution():
๐Ÿงฉ Function DEFINES a function grade_distribution(). Python only remembers it here - its body runs later, each time grade_distribution() is called.
122
for _, g in GRADES:
๐Ÿ” Loop LOOP: takes each item of GRADES one-by-one into _, g and runs the indented block for it
123
n = sum(1 for r in results.values() if r["grade"] == g)
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for r in results.values() if r["grade"] ==โ€ฆ; the result is stored in variable n
124
if n:
๐Ÿ”€ Decision CHECKS whether n is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
125
print(f"{g:<3} {'#' * (n * 4)} {n}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{g:<3} {'#' * (n * 4)} {n}" with the values filled into { } on the screen
update_marks() - lines 128โ€“140
LineCodeWhat it does
128
def update_marks():
๐Ÿงฉ Function DEFINES a function update_marks(). Python only remembers it here - its body runs later, each time update_marks() is called.
130
name = input("Enter name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
131
if name not in results:
๐Ÿ”€ Decision CHECKS whether name is not present in results. If True, the indented lines below run; otherwise they are skipped
132
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
133
return
๐Ÿงฉ Function Ends the function and goes back to the caller
134
for i, s in enumerate(SUBJECTS, start=1):
๐Ÿ” Loop LOOP over SUBJECTS with position: in each round i, s get (position, item)
135
print(f"{i}. {s}", end="  ")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i}. {s}" with the values filled into { } on the screen (ends with " " instead of a new line)
136
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
137
k = int(input("Subject number: ")) - 1
โŒจ๏ธ Input Stores the value of int(input("Subject number: ")) - 1 (calculated using -) in variable k
138
results[name]["marks"][k] = read_marks(SUBJECTS[k])
๐Ÿงฎ Store / Calculate Calls our own function read_marks(SUBJECTS[k]) - reads marks between 0 and 100 (asks again if invalid); the result is put into results[name]["marks"][k] (item k of results[name]["marks"])
139
calculate(name)
๐Ÿงฎ Store / Calculate Calls our own function calculate(name) - recalculates total, percentage and grade of a student
140
print("Updated:", name, f"{results[name]['pct']:.2f}%", results[name]["grade"])
๐Ÿ–ฅ๏ธ Output Displays the text "Updated:", then the value of name, then the f-string f"{results[name]['pct']:.2f}%" with the values filled into { }, then the value of results[name]["grade"] on the screen
delete_student() - lines 143โ€“149
LineCodeWhat it does
143
def delete_student():
๐Ÿงฉ Function DEFINES a function delete_student(). Python only remembers it here - its body runs later, each time delete_student() is called.
145
name = input("Enter name to delete: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
146
if results.pop(name, None):
๐Ÿ”€ Decision CHECKS whether results.pop(name, None) is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
147
print(name, "deleted. Students left:", len(results))
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "deleted. Students left:", then the value of len(results) on the screen
148
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
149
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
Q1. Why is a nested dictionary used?

The outer key is the student name; the inner dictionary keeps marks, total, percentage and grade of that student together.

Q2. How is the grade decided?

get_grade() checks the percentage against a list of (minimum %, grade) pairs from highest to lowest and returns the first matching grade.

Q3. How do you find the class topper?

max(results, key=lambda n: results[n]['pct']) returns the name whose percentage is highest.

Q4. How is the rank list prepared?

sorted() with key=percentage and reverse=True gives students from highest to lowest; enumerate() adds rank numbers.

Q5. What is the role of the read_marks() function?

It keeps asking until a valid number from 0 to 100 is entered, so wrong data never enters the records.

03

Number Pattern & Math Puzzle Generator

PYTHONNested loopsmath modulerandom module
๐Ÿ“ 158 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 126 output lines๐Ÿ“„ 25+ page report

A menu-driven tool that generates star/number patterns, checks Armstrong/Prime/Palindrome numbers, and creates simple math quizzes using random numbers (like a mini Sudoku/puzzle generator).

โœจ Features
  • Eight number and pattern tools in one menu
  • Armstrong, prime, perfect, palindrome, even/odd checks in one go
  • Star, number, pyramid and Floyd's triangle patterns
  • Fibonacci series, factorial and digit operations
  • Prime numbers in a range and HCF/LCM
  • Timed maths quiz with score card and accuracy %
โ˜ฐ Main menu
1Star PatternsRight triangle, inverted triangle and pyramid of stars
2Number PatternsNumber triangle and Floyd's triangle
3Number CheckerArmstrong, prime, perfect, palindrome and even/odd tests
4Fibonacci & FactorialFirst n Fibonacci terms and n!
5Primes in RangeAll prime numbers between two limits with count
6HCF and LCMEuclid's method for two numbers
7Digit OperationsSum, product, reverse and count of digits
8Maths QuizRandom questions, score and accuracy
0ExitShows the session summary and ends
๐ŸŽฏ Objectives
  • Print patterns using loops
  • Test Armstrong, prime and palindrome numbers
  • Generate random questions with the random module and keep a score
๐Ÿ“š Data dictionary
NameTypePurpose
nintNumber entered by the user
scoreintCorrect answers in the quiz
historylistNames of tools used in the session
opstupleOperators used in the quiz: + - *
Why it matters: Strengthens looping logic while producing a genuinely playable console mini-game.
# =====================================================================
#   NUMBER PATTERN & MATH PUZZLE GENERATOR
#   Concepts : loops (nested), conditions, functions, strings, lists,
#              random module
# =====================================================================
import random

history = []


def read_int(msg):
    """Reads an integer safely."""
    while True:
        try:
            return int(input(msg))
        except ValueError:
            print("Please enter a whole number.")


def star_patterns():
    """Prints three star patterns."""
    n = read_int("Enter rows: ")
    print("Right triangle:")
    for i in range(1, n + 1):
        print("*" * i)
    print("Inverted triangle:")
    for i in range(n, 0, -1):
        print("*" * i)
    print("Pyramid:")
    for i in range(1, n + 1):
        print(" " * (n - i) + "* " * i)


def number_patterns():
    """Number triangle and Floyd's triangle."""
    n = read_int("Enter rows: ")
    print("Number triangle:")
    for i in range(1, n + 1):
        print(" ".join(str(j) for j in range(1, i + 1)))
    print("Floyd's triangle:")
    k = 1
    for i in range(1, n + 1):
        row = []
        for j in range(i):
            row.append(f"{k:>3}")
            k += 1
        print("".join(row))


def is_prime(n):
    """Returns True if n is prime."""
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            return False
    return True


def number_checker():
    """Runs five checks on a number."""
    n = read_int("Enter number: ")
    s = str(abs(n))
    arm = sum(int(d) ** len(s) for d in s) == n
    perfect = n > 1 and sum(d for d in range(1, n) if n % d == 0) == n
    print(f"{n} is {'' if arm else 'NOT '}an Armstrong number")
    print(f"{n} is {'' if is_prime(n) else 'NOT '}a Prime number")
    print(f"{n} is {'' if perfect else 'NOT '}a Perfect number")
    print(f"{n} is {'' if s == s[::-1] else 'NOT '}a Palindrome")
    print(f"{n} is {'EVEN' if n % 2 == 0 else 'ODD'}")


def fibo_fact():
    """Fibonacci series and factorial."""
    n = read_int("How many terms / factorial of: ")
    a, b, terms = 0, 1, []
    for _ in range(n):
        terms.append(a)
        a, b = b, a + b
    print("Fibonacci:", *terms)
    f = 1
    for i in range(2, n + 1):
        f *= i
    print(f"{n}! = {f}")


def primes_in_range():
    """Lists primes between two numbers."""
    lo = read_int("Lower limit: ")
    hi = read_int("Upper limit: ")
    pr = [x for x in range(lo, hi + 1) if is_prime(x)]
    print("Primes:", *pr)
    print("Count :", len(pr), "| Sum:", sum(pr))


def hcf_lcm():
    """HCF using Euclid's algorithm and LCM."""
    a = read_int("First number : ")
    b = read_int("Second number: ")
    x, y = a, b
    while y:
        print(f"  ({x}, {y}) -> ({y}, {x % y})")
        x, y = y, x % y
    print("HCF =", x, "| LCM =", a * b // x)


def digit_ops():
    """Sum, product, reverse and count of digits."""
    n = abs(read_int("Enter number: "))
    total, prod, rev, cnt, t = 0, 1, 0, 0, n
    while t > 0:
        d = t % 10
        total += d; prod *= d; rev = rev * 10 + d; cnt += 1
        t //= 10
    print("Sum of digits    :", total)
    print("Product of digits:", prod)
    print("Reverse          :", rev)
    print("Number of digits :", cnt)


def math_quiz():
    """Random arithmetic quiz with score."""
    rounds = read_int("Number of questions: ")
    score = 0
    for i in range(1, rounds + 1):
        a, b = random.randint(2, 20), random.randint(2, 20)
        op = random.choice(("+", "-", "*"))
        ans = a + b if op == "+" else a - b if op == "-" else a * b
        user = read_int(f"Q{i}: {a} {op} {b} = ")
        if user == ans:
            score += 1
            print("Correct!")
        else:
            print("Wrong! Answer:", ans)
    print(f"Score {score}/{rounds}  Accuracy {score / rounds * 100:.1f}%")


tools = {"1": ("Star patterns", star_patterns), "2": ("Number patterns", number_patterns),
         "3": ("Number checker", number_checker), "4": ("Fibonacci & factorial", fibo_fact),
         "5": ("Primes in range", primes_in_range), "6": ("HCF & LCM", hcf_lcm),
         "7": ("Digit operations", digit_ops), "8": ("Maths quiz", math_quiz)}
print("=" * 56)
print("NUMBER PATTERN & MATH PUZZLE GENERATOR".center(56))
print("=" * 56)
while True:
    print()
    for k, (name, _) in tools.items():
        print(f"{k}.{name}", end="  " if int(k) % 4 else "\n")
    ch = input("0.Exit   Enter choice: ").strip()
    if ch == "0":
        print("Tools used this session:", ", ".join(history) or "none")
        break
    if ch in tools:
        tools[ch][1]()
        history.append(tools[ch][0])
    else:
        print("Invalid choice")

        
  1. Start
  2. Display menu and read choice
  3. Valid choice? → No: print 'Invalid choice'
  4. Read number / rows / range
  5. Run the selected tool (pattern, check, series, quiz)
  6. Display result
  7. Add tool name to history
  8. Choice is 0? → No: show menu
  9. Print session summary
  10. Stop
#Test case / inputExpected resultStatus
1Star pattern with 4 rowsThree patterns of 4 rowsPASS
2Number 153Armstrong, not prime, not perfect, not palindrome, oddPASS
3Number 28Perfect numberPASS
4Number 97PrimePASS
5Fibonacci 10 terms0 1 1 2 3 5 8 13 21 34PASS
6Primes 10-5011 primes listedPASS
7HCF/LCM of 12, 18HCF 6, LCM 36PASS
8Digit ops on 4096Sum 19, product 0, reverse 6904, 4 digitsPASS
9Quiz 3 roundsScore and accuracy printedPASS
โš  Limitations
  • Only integers are handled
  • Very large numbers make prime checking slow
  • Quiz questions are random but limited to + - *
  • No graphical display
๐Ÿš€ Future scope
  • Add more series (squares, triangular numbers)
  • Save quiz scores to a file and show a leader board
  • Use turtle graphics for patterns
  • Add difficulty levels to the quiz

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): random - random number functions are loaded.
  2. Global variables / constants are created: history.
  3. 10 functions are defined (lines 11โ€“135) - Python stores them but does NOT run them yet.
  4. Main program starts at line 138: tools = {"1": ("Star patterns", star_patterns), "2": ("Number patterns - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_int(msg)11โ€“17Reads an integer safely.star_patterns(), number_patterns(), number_checker(), fibo_fact()
star_patterns()20โ€“31Prints three star patterns.main program (menu)
number_patterns()34โ€“47Number triangle and Floyd's triangle.main program (menu)
is_prime(n)50โ€“57Returns True if n is prime.number_checker(), primes_in_range()
number_checker()60โ€“70Runs five checks on a number.main program (menu)
fibo_fact()73โ€“84Fibonacci series and factorial.main program (menu)
primes_in_range()87โ€“93Lists primes between two numbers.main program (menu)
hcf_lcm()96โ€“104HCF using Euclid's algorithm and LCM.main program (menu)
digit_ops()107โ€“118Sum, product, reverse and count of digits.main program (menu)
math_quiz()121โ€“135Random arithmetic quiz with score.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
138
tools = {"1": ("Star patterns", star_patterns), "2": ("Number patterns", number_patterns),
         "3": ("Number checker", number_checker), "4": ("Fibonacciโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": ("Star patterns", star_patterns), "2": โ€ฆ in variable tools
142
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
143
print("NUMBER PATTERN & MATH PUZZLE GENERATOR".center(56))
๐Ÿ–ฅ๏ธ Output Displays the value of "NUMBER PATTERN & MATH PUZZLE GENERATOR".centโ€ฆ on the screen
144
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
145
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
146
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
147
for k, (name, _) in tools.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary tools; k, (name, _) get one pair each round
148
print(f"{k}.{name}", end="  " if int(k) % 4 else "\n")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{k}.{name}" with the values filled into { } on the screen (ends with " " if int(k) % 4 else "\n" instead of a new line)
149
ch = input("0.Exit   Enter choice: ").strip()
โŒจ๏ธ Input Shows "0.Exit Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
150
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
151
print("Tools used this session:", ", ".join(history) or "none")
๐Ÿ–ฅ๏ธ Output Displays the text "Tools used this session:", then the value of ", ".join(history) or "none" on the screen
152
break
๐Ÿ” Loop BREAK - leaves the loop immediately
153
if ch in tools:
๐Ÿ”€ Decision CHECKS whether ch is present in tools. If True, the indented lines below run; otherwise Python jumps to the elif/else part
154
tools[ch][1]()
๐Ÿงฎ Store / Calculate Calls tools[ch][1]()
155
history.append(tools[ch][0])
๐Ÿงฎ Store / Calculate Adds tools[ch][0] at the end of list history
156
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
157
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: NUMBER PATTERN & MATH PUZZLE GENERATOR (+2 more lines)
  2. You type 1 at 0.Exit Enter choice:
    runs: star_patterns() โ†’ read_int()
  3. You type 4 at Enter rows:
    shows: Right triangle: (+4 more lines)
  4. You type 2 at 0.Exit Enter choice:
    runs: number_patterns() โ†’ read_int()
  5. You type 5 at Enter rows:
    shows: Number triangle: (+13 more lines)
  6. You type 3 at 0.Exit Enter choice:
    runs: number_checker() โ†’ read_int()
  7. You type 153 at Enter number:
    runs: is_prime()
    shows: 153 is an Armstrong number (+6 more lines)
  8. You type 3 at 0.Exit Enter choice:
    runs: number_checker() โ†’ read_int()
  9. You type 28 at Enter number:
    runs: is_prime()
    shows: 28 is NOT an Armstrong number (+6 more lines)
  10. You type 3 at 0.Exit Enter choice:
    runs: number_checker() โ†’ read_int()
  11. You type 97 at Enter number:
    runs: is_prime()
    shows: 97 is NOT an Armstrong number (+6 more lines)
  12. You type 4 at 0.Exit Enter choice:
    runs: fibo_fact() โ†’ read_int()
  13. You type 10 at How many terms / factorial of:
    shows: Fibonacci: 0 1 1 2 3 5 8 13 21 34 (+3 more lines)
  14. You type 5 at 0.Exit Enter choice:
    runs: primes_in_range() โ†’ read_int()
  15. You type 10 at Lower limit:
    runs: read_int()
  16. You type 50 at Upper limit:
    runs: is_prime() ร—41
    shows: Primes: 11 13 17 19 23 29 31 37 41 43 47 (+3 more lines)
  17. You type 6 at 0.Exit Enter choice:
    runs: hcf_lcm() โ†’ read_int()
  18. You type 12 at First number :
    runs: read_int()
  19. You type 18 at Second number:
    shows: (12, 18) -> (18, 12) (+5 more lines)
  20. You type 7 at 0.Exit Enter choice:
    runs: digit_ops() โ†’ read_int()
  21. You type 4096 at Enter number:
    shows: Sum of digits : 19 (+5 more lines)
  22. You type 8 at 0.Exit Enter choice:
    runs: math_quiz() โ†’ read_int()
  23. You type 3 at Number of questions:
    runs: read_int()
  24. You type 60 at Q1: 5 * 12 =
    runs: read_int()
    shows: Correct!
  25. You type 23 at Q2: 18 + 5 =
    runs: read_int()
    shows: Correct!
  26. You type 200 at Q3: 19 * 15 =
    shows: Wrong! Answer: 285 (+3 more lines)
  27. You type 9 at 0.Exit Enter choice:
    shows: Invalid choice (+2 more lines)
  28. You type 0 at 0.Exit Enter choice:
    shows: Tools used this session: Star patterns, Number patterns, Number checker, Number checker, N
โ‘ค Inside each function - line by line
read_int() - lines 11โ€“17
LineCodeWhat it does
11
def read_int(msg):
๐Ÿงฉ Function DEFINES a function read_int(msg). Python only remembers it here - its body runs later, each time read_int() is called.
13
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
14
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
15
return int(input(msg))
๐Ÿงฉ Function Sends back (returns) the result of: shows msg, reads what the user types, and int() converts that text into a whole number to the line that called the function
16
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
17
print("Please enter a whole number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Please enter a whole number." on the screen
star_patterns() - lines 20โ€“31
LineCodeWhat it does
20
def star_patterns():
๐Ÿงฉ Function DEFINES a function star_patterns(). Python only remembers it here - its body runs later, each time star_patterns() is called.
22
n = read_int("Enter rows: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Enter rows: ") - reads an integer safely; the result is stored in variable n
23
print("Right triangle:")
๐Ÿ–ฅ๏ธ Output Displays the text "Right triangle:" on the screen
24
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
25
print("*" * i)
๐Ÿ–ฅ๏ธ Output Displays the value of "*" * i on the screen
26
print("Inverted triangle:")
๐Ÿ–ฅ๏ธ Output Displays the text "Inverted triangle:" on the screen
27
for i in range(n, 0, -1):
๐Ÿ” Loop LOOP: gives the numbers from n up to (not including) 0, jumping by -1; for each number, i takes that value and the indented block runs once
28
print("*" * i)
๐Ÿ–ฅ๏ธ Output Displays the value of "*" * i on the screen
29
print("Pyramid:")
๐Ÿ–ฅ๏ธ Output Displays the text "Pyramid:" on the screen
30
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
31
print(" " * (n - i) + "* " * i)
๐Ÿ–ฅ๏ธ Output Displays the value of " " * (n - i) + "* " * i on the screen
number_patterns() - lines 34โ€“47
LineCodeWhat it does
34
def number_patterns():
๐Ÿงฉ Function DEFINES a function number_patterns(). Python only remembers it here - its body runs later, each time number_patterns() is called.
36
n = read_int("Enter rows: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Enter rows: ") - reads an integer safely; the result is stored in variable n
37
print("Number triangle:")
๐Ÿ–ฅ๏ธ Output Displays the text "Number triangle:" on the screen
38
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
39
print(" ".join(str(j) for j in range(1, i + 1)))
๐Ÿ–ฅ๏ธ Output Displays the value of " ".join(str(j) for j in range(1, i + 1)) on the screen
40
print("Floyd's triangle:")
๐Ÿ–ฅ๏ธ Output Displays the text "Floyd's triangle:" on the screen
41
k = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable k
42
for i in range(1, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
43
row = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable row
44
for j in range(i):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to i - 1; for each number, j takes that value and the indented block runs once
45
row.append(f"{k:>3}")
๐Ÿงฎ Store / Calculate Adds f"{k:>3}" at the end of list row
46
k += 1
๐Ÿงฎ Store / Calculate Adds 1 to k (same as k = k + 1)
47
print("".join(row))
๐Ÿ–ฅ๏ธ Output Displays the value of "".join(row) on the screen
is_prime() - lines 50โ€“57
LineCodeWhat it does
50
def is_prime(n):
๐Ÿงฉ Function DEFINES a function is_prime(n). Python only remembers it here - its body runs later, each time is_prime() is called.
52
if n < 2:
๐Ÿ”€ Decision CHECKS whether n is less than 2. If True, the indented lines below run; otherwise they are skipped
53
return False
๐Ÿงฉ Function Sends back (returns) False to the line that called the function
54
for d in range(2, int(n ** 0.5) + 1):
๐Ÿ” Loop LOOP: gives the numbers from 2 up to int(n ** 0.5) + 1 - 1; for each number, d takes that value and the indented block runs once
55
if n % d == 0:
๐Ÿ”€ Decision CHECKS whether n % d is equal to 0. If True, the indented lines below run; otherwise they are skipped
56
return False
๐Ÿงฉ Function Sends back (returns) False to the line that called the function
57
return True
๐Ÿงฉ Function Sends back (returns) True to the line that called the function
number_checker() - lines 60โ€“70
LineCodeWhat it does
60
def number_checker():
๐Ÿงฉ Function DEFINES a function number_checker(). Python only remembers it here - its body runs later, each time number_checker() is called.
62
n = read_int("Enter number: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Enter number: ") - reads an integer safely; the result is stored in variable n
63
s = str(abs(n))
๐Ÿงฎ Store / Calculate Converts abs(n) into text (string); the result is stored in variable s
64
arm = sum(int(d) ** len(s) for d in s) == n
๐Ÿงฎ Store / Calculate Stores True/False for sum(int(d) ** len(s) for d in s) is equal to n in variable arm
65
perfect = n > 1 and sum(d for d in range(1, n) if n % d == 0) == n
๐Ÿงฎ Store / Calculate Stores True/False for (n is greater than 1 AND sum(d for d in range(1, n) if n % d == 0) is equal to n) in variable perfect
66
print(f"{n} is {'' if arm else 'NOT '}an Armstrong number")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} is {'' if arm else 'NOT '}an Armstrong โ€ฆ with the values filled into { } on the screen
67
print(f"{n} is {'' if is_prime(n) else 'NOT '}a Prime number")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} is {'' if is_prime(n) else 'NOT '}a Priโ€ฆ with the values filled into { } on the screen
68
print(f"{n} is {'' if perfect else 'NOT '}a Perfect number")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} is {'' if perfect else 'NOT '}a Perfectโ€ฆ with the values filled into { } on the screen
69
print(f"{n} is {'' if s == s[::-1] else 'NOT '}a Palindrome")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} is {'' if s == s[::-1] else 'NOT '}a Paโ€ฆ with the values filled into { } on the screen
70
print(f"{n} is {'EVEN' if n % 2 == 0 else 'ODD'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n} is {'EVEN' if n % 2 == 0 else 'ODD'}" with the values filled into { } on the screen
fibo_fact() - lines 73โ€“84
LineCodeWhat it does
73
def fibo_fact():
๐Ÿงฉ Function DEFINES a function fibo_fact(). Python only remembers it here - its body runs later, each time fibo_fact() is called.
75
n = read_int("How many terms / factorial of: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("How many terms / fโ€ฆ) - reads an integer safely; the result is stored in variable n
76
a, b, terms = 0, 1, []
๐Ÿงฎ Store / Calculate Stores 0, 1, [] into a, b, terms respectively
77
for _ in range(n):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to n - 1; for each number, _ takes that value and the indented block runs once
78
terms.append(a)
๐Ÿงฎ Store / Calculate Adds a at the end of list terms
79
a, b = b, a + b
๐Ÿงฎ Store / Calculate Stores b, a + b into a, b respectively
80
print("Fibonacci:", *terms)
๐Ÿ–ฅ๏ธ Output Displays the text "Fibonacci:", then the value of *terms on the screen
81
f = 1
๐Ÿงฎ Store / Calculate Stores the number 1 in variable f
82
for i in range(2, n + 1):
๐Ÿ” Loop LOOP: gives the numbers from 2 up to n + 1 - 1; for each number, i takes that value and the indented block runs once
83
f *= i
๐Ÿงฎ Store / Calculate Multiplies f by i (same as f = f ร— i)
84
print(f"{n}! = {f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n}! = {f}" with the values filled into { } on the screen
primes_in_range() - lines 87โ€“93
LineCodeWhat it does
87
def primes_in_range():
๐Ÿงฉ Function DEFINES a function primes_in_range(). Python only remembers it here - its body runs later, each time primes_in_range() is called.
89
lo = read_int("Lower limit: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Lower limit: ") - reads an integer safely; the result is stored in variable lo
90
hi = read_int("Upper limit: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Upper limit: ") - reads an integer safely; the result is stored in variable hi
91
pr = [x for x in range(lo, hi + 1) if is_prime(x)]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [x for x in range(lo, hi + 1) if is_prime(x)] in variable pr
92
print("Primes:", *pr)
๐Ÿ–ฅ๏ธ Output Displays the text "Primes:", then the value of *pr on the screen
93
print("Count :", len(pr), "| Sum:", sum(pr))
๐Ÿ–ฅ๏ธ Output Displays the text "Count :", then the value of len(pr), then the text "| Sum:", then the value of sum(pr) on the screen
hcf_lcm() - lines 96โ€“104
LineCodeWhat it does
96
def hcf_lcm():
๐Ÿงฉ Function DEFINES a function hcf_lcm(). Python only remembers it here - its body runs later, each time hcf_lcm() is called.
98
a = read_int("First number : ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("First number : ") - reads an integer safely; the result is stored in variable a
99
b = read_int("Second number: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Second number: ") - reads an integer safely; the result is stored in variable b
100
x, y = a, b
๐Ÿงฎ Store / Calculate Stores a, b into x, y respectively
101
while y:
๐Ÿ” Loop LOOP: repeats the indented block as long as y is True (not empty / not zero); checks the condition before every round
102
print(f"  ({x}, {y}) -> ({y}, {x % y})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" ({x}, {y}) -> ({y}, {x % y})" with the values filled into { } on the screen
103
x, y = y, x % y
๐Ÿงฎ Store / Calculate Stores y, x % y into x, y respectively
104
print("HCF =", x, "| LCM =", a * b // x)
๐Ÿ–ฅ๏ธ Output Displays the text "HCF =", then the value of x, then the text "| LCM =", then the value of a * b // x on the screen
digit_ops() - lines 107โ€“118
LineCodeWhat it does
107
def digit_ops():
๐Ÿงฉ Function DEFINES a function digit_ops(). Python only remembers it here - its body runs later, each time digit_ops() is called.
109
n = abs(read_int("Enter number: "))
๐Ÿงฎ Store / Calculate Gives the absolute (positive) value of read_int("Enter number: "); the result is stored in variable n
110
total, prod, rev, cnt, t = 0, 1, 0, 0, n
๐Ÿงฎ Store / Calculate Stores 0, 1, 0, 0, n into total, prod, rev, cnt, t respectively
111
while t > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as t is greater than 0; checks the condition before every round
112
d = t % 10
๐Ÿงฎ Store / Calculate Stores the value of t % 10 (calculated using % (remainder)) in variable d
113
total += d; prod *= d; rev = rev * 10 + d; cnt += 1
๐Ÿงฎ Store / Calculate Adds d to total (same as total = total + d)
113
total += d; prod *= d; rev = rev * 10 + d; cnt += 1
๐Ÿงฎ Store / Calculate Multiplies prod by d (same as prod = prod ร— d)
113
total += d; prod *= d; rev = rev * 10 + d; cnt += 1
๐Ÿงฎ Store / Calculate Stores the value of rev * 10 + d (calculated using +) in variable rev
113
total += d; prod *= d; rev = rev * 10 + d; cnt += 1
๐Ÿงฎ Store / Calculate Adds 1 to cnt (same as cnt = cnt + 1)
114
t //= 10
๐Ÿงฎ Store / Calculate Updates t using t //= 10
115
print("Sum of digits    :", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Sum of digits :", then the value of total on the screen
116
print("Product of digits:", prod)
๐Ÿ–ฅ๏ธ Output Displays the text "Product of digits:", then the value of prod on the screen
117
print("Reverse          :", rev)
๐Ÿ–ฅ๏ธ Output Displays the text "Reverse :", then the value of rev on the screen
118
print("Number of digits :", cnt)
๐Ÿ–ฅ๏ธ Output Displays the text "Number of digits :", then the value of cnt on the screen
math_quiz() - lines 121โ€“135
LineCodeWhat it does
121
def math_quiz():
๐Ÿงฉ Function DEFINES a function math_quiz(). Python only remembers it here - its body runs later, each time math_quiz() is called.
123
rounds = read_int("Number of questions: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Number of questionโ€ฆ) - reads an integer safely; the result is stored in variable rounds
124
score = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable score
125
for i in range(1, rounds + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to rounds + 1 - 1; for each number, i takes that value and the indented block runs once
126
a, b = random.randint(2, 20), random.randint(2, 20)
๐Ÿงฎ Store / Calculate Stores random.randint(2, 20), random.randint(2, 20) into a, b respectively
127
op = random.choice(("+", "-", "*"))
๐Ÿงฎ Store / Calculate Picks one random item from ("+", "-", "*"); the result is stored in variable op
128
ans = a + b if op == "+" else a - b if op == "-" else a * b
๐Ÿงฎ Store / Calculate Stores either a + b or a - b if op == "-" else a * b depending on op == "+" in variable ans
129
user = read_int(f"Q{i}: {a} {op} {b} = ")
๐Ÿงฎ Store / Calculate Calls our own function read_int(f"Q{i}: {a} {op} {bโ€ฆ) - reads an integer safely; the result is stored in variable user
130
if user == ans:
๐Ÿ”€ Decision CHECKS whether user is equal to ans. If True, the indented lines below run; otherwise Python jumps to the elif/else part
131
score += 1
๐Ÿงฎ Store / Calculate Adds 1 to score (same as score = score + 1)
132
print("Correct!")
๐Ÿ–ฅ๏ธ Output Displays the text "Correct!" on the screen
133
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
134
print("Wrong! Answer:", ans)
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong! Answer:", then the value of ans on the screen
135
print(f"Score {score}/{rounds}  Accuracy {score / rounds * 100:.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Score {score}/{rounds} Accuracy {score / roโ€ฆ with the values filled into { } on the screen
Q1. What is an Armstrong number?

A number equal to the sum of its digits each raised to the power of the number of digits, e.g. 153 = 1^3 + 5^3 + 3^3.

Q2. How is a prime number checked efficiently?

By trying divisors only from 2 up to the square root of the number; if none divides it, the number is prime.

Q3. What is a perfect number?

A number equal to the sum of its proper divisors, e.g. 28 = 1 + 2 + 4 + 7 + 14.

Q4. Which algorithm finds HCF?

Euclid's algorithm: replace (a, b) by (b, a % b) until b becomes 0; then a is the HCF. LCM = a x b / HCF.

Q5. Which module generates quiz questions?

The random module - randint() gives random numbers and choice() picks a random operator.

04

Simple Library Catalogue (In-Memory)

PYTHONDictionary of dictionariessearchdelete operations
๐Ÿ“ 148 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 123 output lines๐Ÿ“„ 25+ page report

Maintain a dictionary of books (id, name, author, availability). Add, search-by-name, issue/return (toggle availability) and delete book records.

โœจ Features
  • Book records with ID, title, author, category, copies available and total copies
  • Issue and return with member name and day-count; fine of Rs. 2 per late day after 14 days
  • Search by title, author or category (partial match)
  • Category-wise stock report and list of issued books
  • Most popular book (issue count) and member history
  • Input validation for IDs and copies
โ˜ฐ Main menu
1Add BookAdds a new book or more copies of an existing ID
2Show All BooksTable of all books with availability
3Search BookSearch by title, author or category
4Issue BookIssues a copy to a member if available
5Return BookReturns a book and calculates late fine
6Issued BooksList of books currently issued and to whom
7Category ReportTotal titles and copies in each category
8Delete BookRemoves a book that is not issued
9StatisticsMost issued book, total fine collected
0ExitCloses the library
๐ŸŽฏ Objectives
  • Store records in a dictionary of dictionaries
  • Search, update and delete records using the key
  • Toggle a status flag for issue and return
๐Ÿ“š Data dictionary
NameTypePurpose
librarydict of dictBook ID -> {title, author, category, total, available, issued_count}
issuedlist of dictCurrent issues: book id, member, day issued
fine_totalintTotal fine collected in the session
FINE_PER_DAYintRs. 2 for every day after 14 days
Why it matters: Builds the foundation for the Class XII 'Library Management System' project idea.
# =====================================================================
#   SIMPLE LIBRARY CATALOGUE  (Issue, Return, Fine, Reports)
#   Concepts : dictionaries, lists, functions, loops, string methods
# =====================================================================

FINE_PER_DAY = 2
library = {
    101: {"title": "Python Programming", "author": "Sumita Arora", "category": "Computer", "total": 3, "available": 3, "count": 0},
    102: {"title": "Learn Python Basics", "author": "Reema Thareja", "category": "Computer", "total": 2, "available": 2, "count": 0},
    103: {"title": "The Discovery of India", "author": "Jawaharlal Nehru", "category": "History", "total": 2, "available": 2, "count": 0},
    104: {"title": "Panchatantra", "author": "Vishnu Sharma", "category": "Stories", "total": 1, "available": 1, "count": 0}}
issued = []
fine_total = 0


def read_int(msg):
    """Reads an integer; returns None for invalid input."""
    try:
        return int(input(msg))
    except ValueError:
        print("Enter a valid number.")
        return None


def show(ids=None):
    """Displays books in a table."""
    ids = list(library) if ids is None else ids
    print(f"{'ID':<5}{'Title':<26}{'Author':<20}{'Category':<10}{'Avail':>6}")
    print("-" * 67)
    for b in ids:
        r = library[b]
        print(f"{b:<5}{r['title'][:25]:<26}{r['author'][:19]:<20}{r['category']:<10}{r['available']:>3}/{r['total']}")


def add_book():
    """Adds a new book or extra copies."""
    bid = read_int("Book ID: ")
    if bid is None:
        return
    if bid in library:
        n = read_int("Book exists. Extra copies to add: ") or 0
        library[bid]["total"] += n
        library[bid]["available"] += n
        print("Copies updated:", library[bid]["available"], "available")
        return
    title = input("Title   : ").strip()
    author = input("Author  : ").strip()
    cat = input("Category: ").strip().title()
    n = read_int("Copies  : ") or 1
    library[bid] = {"title": title, "author": author, "category": cat, "total": n, "available": n, "count": 0}
    print("Book added with", n, "copies.")


def search():
    """Partial search by title, author or category."""
    key = input("Search word: ").strip().lower()
    found = [b for b, r in library.items() if key in (r["title"] + r["author"] + r["category"]).lower()]
    print(len(found), "book(s) found")
    if found:
        show(found)


def issue_book():
    """Issues one copy of a book."""
    bid = read_int("Book ID to issue: ")
    if bid not in library:
        print("Book ID not found.")
        return
    member = input("Member name: ").strip().title()
    if library[bid]["available"] == 0:
        print("All copies are issued. Please try later.")
        return
    library[bid]["available"] -= 1
    library[bid]["count"] += 1
    issued.append({"id": bid, "member": member})
    print(f"'{library[bid]['title']}' issued to {member}. Return within 14 days.")


def return_book():
    """Returns a book and calculates fine."""
    global fine_total
    bid = read_int("Book ID to return: ")
    member = input("Member name: ").strip().title()
    for rec in issued:
        if rec["id"] == bid and rec["member"] == member:
            days = read_int("Days kept: ") or 0
            fine = max(0, days - 14) * FINE_PER_DAY
            fine_total += fine
            issued.remove(rec)
            library[bid]["available"] += 1
            print("Book returned.", f"Late by {days - 14} days. Fine Rs. {fine}" if fine else "No fine.")
            return
    print("No such issue record.")


def issued_list():
    """Shows currently issued books."""
    if not issued:
        print("No book is issued.")
    for i, rec in enumerate(issued, 1):
        print(f"{i}. {library[rec['id']]['title']:<26} -> {rec['member']}")


def category_report():
    """Titles and copies per category."""
    rep = {}
    for r in library.values():
        t = rep.setdefault(r["category"], [0, 0])
        t[0] += 1
        t[1] += r["total"]
    print(f"{'Category':<12}{'Titles':>7}{'Copies':>8}")
    for c, (t, n) in sorted(rep.items()):
        print(f"{c:<12}{t:>7}{n:>8}  " + "#" * n)


def delete_book():
    """Deletes a book if no copy is issued."""
    bid = read_int("Book ID to delete: ")
    if bid not in library:
        print("Book ID not found.")
    elif library[bid]["available"] < library[bid]["total"]:
        print("Cannot delete - copies are issued.")
    else:
        print("Deleted:", library.pop(bid)["title"])


def statistics():
    """Library statistics."""
    top = max(library, key=lambda b: library[b]["count"])
    print("Titles:", len(library), "| Copies:", sum(r["total"] for r in library.values()),
          "| Issued now:", len(issued))
    print("Most issued book:", library[top]["title"], f"({library[top]['count']} times)")
    print("Total fine collected: Rs.", fine_total)


menu = {"1": add_book, "2": show, "3": search, "4": issue_book, "5": return_book,
        "6": issued_list, "7": category_report, "8": delete_book, "9": statistics}
print("=" * 67)
print("KV LIBRARY CATALOGUE".center(67))
print("=" * 67)
while True:
    print("\n1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Library closed. Happy reading!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Load sample books into the library dictionary
  3. Display menu and read choice
  4. Choice is Issue? → No: go to the selected option
  5. Copies available > 0? → No: print 'not available'
  6. Reduce available copies, add to issued list
  7. Return - find issue, add copy, fine = (days - 14) x 2
  8. Show reports / search results
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Add book 105 'Wings of Fire'Book added with 2 copiesPASS
2Add ID 101 againCopies of existing book increasedPASS
3Search 'python'Both Python books listedPASS
4Issue 103 to RiyaAvailable copies reduce by 1PASS
5Issue 104 (0 copies left)'All copies are issued' messagePASS
6Return 103 after 20 daysFine Rs. 12 chargedPASS
7Delete issued book'Cannot delete - copies issued'PASS
8Book ID 'abc''Enter a valid number'PASS
9StatisticsMost issued book and total fine printedPASS
โš  Limitations
  • Records are kept only in memory
  • Days are entered manually, not taken from the system date
  • One copy per member per issue
  • No login for librarian
๐Ÿš€ Future scope
  • Store books and members in MySQL (Class XII)
  • Use the datetime module for issue / return dates
  • Barcode based issue and return
  • E-mail reminders for due books

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: FINE_PER_DAY, library, issued, fine_total.
  2. 10 functions are defined (lines 16โ€“133) - Python stores them but does NOT run them yet.
  3. Main program starts at line 136: menu = {"1": add_book, "2": show, "3": search, "4": issue_book, "5": r - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_int(msg)16โ€“22Reads an integer; returns None for invalid input.add_book(), issue_book(), return_book(), delete_book()
show(ids)25โ€“32Displays books in a table.search(), main program (menu)
add_book()35โ€“51Adds a new book or extra copies.main program (menu)
search()54โ€“60Partial search by title, author or category.main program (menu)
issue_book()63โ€“76Issues one copy of a book.main program (menu)
return_book()79โ€“93Returns a book and calculates fine.main program (menu)
issued_list()96โ€“101Shows currently issued books.main program (menu)
category_report()104โ€“113Titles and copies per category.main program (menu)
delete_book()116โ€“124Deletes a book if no copy is issued.main program (menu)
statistics()127โ€“133Library statistics.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
136
menu = {"1": add_book, "2": show, "3": search, "4": issue_book, "5": return_book,
        "6": issued_list, "7": category_report, "8": delete_book, "9": statโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_book, "2": show, "3": search, "4": โ€ฆ in variable menu
138
print("=" * 67)
๐Ÿ–ฅ๏ธ Output Displays a line of 67 "=" signs on the screen
139
print("KV LIBRARY CATALOGUE".center(67))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV LIBRARY CATALOGUE".center(67) on the screen
140
print("=" * 67)
๐Ÿ–ฅ๏ธ Output Displays a line of 67 "=" signs on the screen
141
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
142
print("\n1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Show 3.Search 4.Issue 5.Rโ€ฆ" on the screen
143
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
144
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
145
print("Library closed. Happy reading!")
๐Ÿ–ฅ๏ธ Output Displays the text "Library closed. Happy reading!" on the screen
146
break
๐Ÿ” Loop BREAK - leaves the loop immediately
147
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: KV LIBRARY CATALOGUE (+1 more lines)
  2. You type 2 at Enter choice:
    runs: show()
    shows: ID Title Author Category Avail (+5 more lines)
  3. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  4. You type 105 at Book ID:
  5. You type Wings of Fire at Title :
  6. You type A.P.J. Abdul Kalam at Author :
  7. You type Biography at Category:
    runs: read_int()
  8. You type 2 at Copies :
    shows: Book added with 2 copies. (+1 more lines)
  9. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  10. You type 101 at Book ID:
    runs: read_int()
  11. You type 1 at Book exists. Extra copies to add:
    shows: Copies updated: 4 available (+1 more lines)
  12. You type 3 at Enter choice:
    runs: search()
  13. You type python at Search word:
    runs: show()
    shows: 2 book(s) found (+4 more lines)
  14. You type 4 at Enter choice:
    runs: issue_book() โ†’ read_int()
  15. You type 103 at Book ID to issue:
  16. You type Riya at Member name:
    shows: 'The Discovery of India' issued to Riya. Return within 14 days. (+1 more lines)
  17. You type 4 at Enter choice:
    runs: issue_book() โ†’ read_int()
  18. You type 104 at Book ID to issue:
  19. You type Kabir at Member name:
    shows: 'Panchatantra' issued to Kabir. Return within 14 days. (+1 more lines)
  20. You type 4 at Enter choice:
    runs: issue_book() โ†’ read_int()
  21. You type 104 at Book ID to issue:
  22. You type Om at Member name:
    shows: All copies are issued. Please try later. (+1 more lines)
  23. You type 4 at Enter choice:
    runs: issue_book() โ†’ read_int()
  24. You type 101 at Book ID to issue:
  25. You type Kabir at Member name:
    shows: 'Python Programming' issued to Kabir. Return within 14 days. (+1 more lines)
  26. You type 6 at Enter choice:
    runs: issued_list()
    shows: 1. The Discovery of India -> Riya (+3 more lines)
  27. You type 5 at Enter choice:
    runs: return_book() โ†’ read_int()
  28. You type 103 at Book ID to return:
  29. You type Riya at Member name:
    runs: read_int()
  30. You type 20 at Days kept:
    shows: Book returned. Late by 6 days. Fine Rs. 12 (+1 more lines)
  31. You type 5 at Enter choice:
    runs: return_book() โ†’ read_int()
  32. You type 101 at Book ID to return:
  33. You type Kabir at Member name:
    runs: read_int()
  34. You type 7 at Days kept:
    shows: Book returned. No fine. (+1 more lines)
  35. You type 7 at Enter choice:
    runs: category_report()
    shows: Category Titles Copies (+5 more lines)
  36. You type 8 at Enter choice:
    runs: delete_book() โ†’ read_int()
  37. You type 102 at Book ID to delete:
    shows: Deleted: Learn Python Basics (+1 more lines)
  38. You type 8 at Enter choice:
    runs: delete_book() โ†’ read_int()
  39. You type 104 at Book ID to delete:
    shows: Cannot delete - copies are issued. (+1 more lines)
  40. You type 4 at Enter choice:
    runs: issue_book() โ†’ read_int()

โ€ฆ and 4 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
read_int() - lines 16โ€“22
LineCodeWhat it does
16
def read_int(msg):
๐Ÿงฉ Function DEFINES a function read_int(msg). Python only remembers it here - its body runs later, each time read_int() is called.
18
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
19
return int(input(msg))
๐Ÿงฉ Function Sends back (returns) the result of: shows msg, reads what the user types, and int() converts that text into a whole number to the line that called the function
20
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
21
print("Enter a valid number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a valid number." on the screen
22
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
show() - lines 25โ€“32
LineCodeWhat it does
25
def show(ids=None):
๐Ÿงฉ Function DEFINES a function show(ids). Python only remembers it here - its body runs later, each time show() is called.
27
ids = list(library) if ids is None else ids
๐Ÿงฎ Store / Calculate Stores either list(library) or ids depending on ids is None in variable ids
28
print(f"{'ID':<5}{'Title':<26}{'Author':<20}{'Category':<10}{'Avail':>6}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'ID':<5}{'Title':<26}{'Author':<20}{'Categโ€ฆ with the values filled into { } on the screen
29
print("-" * 67)
๐Ÿ–ฅ๏ธ Output Displays a line of 67 "-" signs on the screen
30
for b in ids:
๐Ÿ” Loop LOOP: takes each item of ids one-by-one into b and runs the indented block for it
31
r = library[b]
๐Ÿงฎ Store / Calculate Stores the item library[b] in variable r
32
print(f"{b:<5}{r['title'][:25]:<26}{r['author'][:19]:<20}{r['category']:<10}{r['available']:>3}/{r['total']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{b:<5}{r['title'][:25]:<26}{r['author'][:19โ€ฆ with the values filled into { } on the screen
add_book() - lines 35โ€“51
LineCodeWhat it does
35
def add_book():
๐Ÿงฉ Function DEFINES a function add_book(). Python only remembers it here - its body runs later, each time add_book() is called.
37
bid = read_int("Book ID: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID: ") - reads an integer; returns none for invalid input; the result is stored in variable bid
38
if bid is None:
๐Ÿ”€ Decision CHECKS whether bid is None. If True, the indented lines below run; otherwise they are skipped
39
return
๐Ÿงฉ Function Ends the function and goes back to the caller
40
if bid in library:
๐Ÿ”€ Decision CHECKS whether bid is present in library. If True, the indented lines below run; otherwise they are skipped
41
n = read_int("Book exists. Extra copies to add: ") or 0
๐Ÿงฎ Store / Calculate Stores the value of read_int("Book exists. Extra copies to add: "), or 0 if the first one is empty / None / 0 in variable n
42
library[bid]["total"] += n
๐Ÿงฎ Store / Calculate Adds n to library[bid]["total"] (same as library[bid]["total"] = library[bid]["total"] + n)
43
library[bid]["available"] += n
๐Ÿงฎ Store / Calculate Adds n to library[bid]["available"] (same as library[bid]["available"] = library[bid]["available"] + n)
44
print("Copies updated:", library[bid]["available"], "available")
๐Ÿ–ฅ๏ธ Output Displays the text "Copies updated:", then the value of library[bid]["available"], then the text "available" on the screen
45
return
๐Ÿงฉ Function Ends the function and goes back to the caller
46
title = input("Title   : ").strip()
โŒจ๏ธ Input Shows "Title : ", reads the typed text, removes extra spaces (strip) and stores it in variable title
47
author = input("Author  : ").strip()
โŒจ๏ธ Input Shows "Author : ", reads the typed text, removes extra spaces (strip) and stores it in variable author
48
cat = input("Category: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cat
49
n = read_int("Copies  : ") or 1
๐Ÿงฎ Store / Calculate Stores the value of read_int("Copies : "), or 1 if the first one is empty / None / 0 in variable n
50
library[bid] = {"title": title, "author": author, "category": cat, "total": n, "available": n, "count": 0}
๐Ÿงฎ Store / Calculate Puts a dictionary {"title": title, "author": author, "category"โ€ฆ into library[bid] (item bid of library)
51
print("Book added with", n, "copies.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book added with", then the value of n, then the text "copies." on the screen
search() - lines 54โ€“60
LineCodeWhat it does
54
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
56
key = input("Search word: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
57
found = [b for b, r in library.items() if key in (r["title"] + r["author"] + r["category"]).lower()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [b for b, r in library.items() if key in (r["โ€ฆ in variable found
58
print(len(found), "book(s) found")
๐Ÿ–ฅ๏ธ Output Displays the value of len(found), then the text "book(s) found" on the screen
59
if found:
๐Ÿ”€ Decision CHECKS whether found is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
60
show(found)
๐Ÿงฎ Store / Calculate Calls our own function show(found) - displays books in a table
issue_book() - lines 63โ€“76
LineCodeWhat it does
63
def issue_book():
๐Ÿงฉ Function DEFINES a function issue_book(). Python only remembers it here - its body runs later, each time issue_book() is called.
65
bid = read_int("Book ID to issue: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to issue: ") - reads an integer; returns none for invalid input; the result is stored in variable bid
66
if bid not in library:
๐Ÿ”€ Decision CHECKS whether bid is not present in library. If True, the indented lines below run; otherwise they are skipped
67
print("Book ID not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book ID not found." on the screen
68
return
๐Ÿงฉ Function Ends the function and goes back to the caller
69
member = input("Member name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable member
70
if library[bid]["available"] == 0:
๐Ÿ”€ Decision CHECKS whether library[bid]["available"] is equal to 0. If True, the indented lines below run; otherwise they are skipped
71
print("All copies are issued. Please try later.")
๐Ÿ–ฅ๏ธ Output Displays the text "All copies are issued. Please tryโ€ฆ" on the screen
72
return
๐Ÿงฉ Function Ends the function and goes back to the caller
73
library[bid]["available"] -= 1
๐Ÿงฎ Store / Calculate Subtracts 1 from library[bid]["available"] (same as library[bid]["available"] = library[bid]["available"] - 1)
74
library[bid]["count"] += 1
๐Ÿงฎ Store / Calculate Adds 1 to library[bid]["count"] (same as library[bid]["count"] = library[bid]["count"] + 1)
75
issued.append({"id": bid, "member": member})
๐Ÿงฎ Store / Calculate Adds {"id": bid, "member": member} at the end of list issued
76
print(f"'{library[bid]['title']}' issued to {member}. Return within 14 days.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"'{library[bid]['title']}' issued to {memberโ€ฆ with the values filled into { } on the screen
return_book() - lines 79โ€“93
LineCodeWhat it does
79
def return_book():
๐Ÿงฉ Function DEFINES a function return_book(). Python only remembers it here - its body runs later, each time return_book() is called.
81
global fine_total
๐Ÿงฉ Function Tells Python that fine_total means the GLOBAL variable (outside the function)
82
bid = read_int("Book ID to return: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to return:โ€ฆ) - reads an integer; returns none for invalid input; the result is stored in variable bid
83
member = input("Member name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable member
84
for rec in issued:
๐Ÿ” Loop LOOP: takes each item of issued one-by-one into rec and runs the indented block for it
85
if rec["id"] == bid and rec["member"] == member:
๐Ÿ”€ Decision CHECKS whether (rec["id"] is equal to bid AND rec["member"] is equal to member). If True, the indented lines below run; otherwise they are skipped
86
days = read_int("Days kept: ") or 0
๐Ÿงฎ Store / Calculate Stores the value of read_int("Days kept: "), or 0 if the first one is empty / None / 0 in variable days
87
fine = max(0, days - 14) * FINE_PER_DAY
๐Ÿงฎ Store / Calculate Stores the value of max(0, days - 14) * FINE_PER_DAY (calculated using ร—) in variable fine
88
fine_total += fine
๐Ÿงฎ Store / Calculate Adds fine to fine_total (same as fine_total = fine_total + fine)
89
issued.remove(rec)
๐Ÿงฎ Store / Calculate Removes the first rec from issued
90
library[bid]["available"] += 1
๐Ÿงฎ Store / Calculate Adds 1 to library[bid]["available"] (same as library[bid]["available"] = library[bid]["available"] + 1)
91
print("Book returned.", f"Late by {days - 14} days. Fine Rs. {fine}" if fine else "No fine.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book returned.", then the value of f"Late by {days - 14} days. Fine Rs. {fine}" โ€ฆ on the screen
92
return
๐Ÿงฉ Function Ends the function and goes back to the caller
93
print("No such issue record.")
๐Ÿ–ฅ๏ธ Output Displays the text "No such issue record." on the screen
issued_list() - lines 96โ€“101
LineCodeWhat it does
96
def issued_list():
๐Ÿงฉ Function DEFINES a function issued_list(). Python only remembers it here - its body runs later, each time issued_list() is called.
98
if not issued:
๐Ÿ”€ Decision CHECKS whether issued is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
99
print("No book is issued.")
๐Ÿ–ฅ๏ธ Output Displays the text "No book is issued." on the screen
100
for i, rec in enumerate(issued, 1):
๐Ÿ” Loop LOOP over issued with position: in each round i, rec get (position, item)
101
print(f"{i}. {library[rec['id']]['title']:<26} -> {rec['member']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i}. {library[rec['id']]['title']:<26} -> {โ€ฆ with the values filled into { } on the screen
category_report() - lines 104โ€“113
LineCodeWhat it does
104
def category_report():
๐Ÿงฉ Function DEFINES a function category_report(). Python only remembers it here - its body runs later, each time category_report() is called.
106
rep = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable rep
107
for r in library.values():
๐Ÿ” Loop LOOP: takes each item of library.values() one-by-one into r and runs the indented block for it
108
t = rep.setdefault(r["category"], [0, 0])
๐Ÿงฎ Store / Calculate Gets r["category"] from rep, adding it with [0, 0] if missing; the result is stored in variable t
109
t[0] += 1
๐Ÿงฎ Store / Calculate Adds 1 to t[0] (same as t[0] = t[0] + 1)
110
t[1] += r["total"]
๐Ÿงฎ Store / Calculate Adds r["total"] to t[1] (same as t[1] = t[1] + r["total"])
111
print(f"{'Category':<12}{'Titles':>7}{'Copies':>8}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Category':<12}{'Titles':>7}{'Copies':>8}" with the values filled into { } on the screen
112
for c, (t, n) in sorted(rep.items()):
๐Ÿ” Loop LOOP: takes each item of sorted(rep.items()) one-by-one into c, (t, n) and runs the indented block for it
113
print(f"{c:<12}{t:>7}{n:>8}  " + "#" * n)
๐Ÿ–ฅ๏ธ Output Displays the value of f"{c:<12}{t:>7}{n:>8} " + "#" * n on the screen
delete_book() - lines 116โ€“124
LineCodeWhat it does
116
def delete_book():
๐Ÿงฉ Function DEFINES a function delete_book(). Python only remembers it here - its body runs later, each time delete_book() is called.
118
bid = read_int("Book ID to delete: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to delete:โ€ฆ) - reads an integer; returns none for invalid input; the result is stored in variable bid
119
if bid not in library:
๐Ÿ”€ Decision CHECKS whether bid is not present in library. If True, the indented lines below run; otherwise Python jumps to the elif/else part
120
print("Book ID not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book ID not found." on the screen
121
elif library[bid]["available"] < library[bid]["total"]:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether library[bid]["available"] is less than library[bid]["total"]
122
print("Cannot delete - copies are issued.")
๐Ÿ–ฅ๏ธ Output Displays the text "Cannot delete - copies are issued." on the screen
123
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
124
print("Deleted:", library.pop(bid)["title"])
๐Ÿ–ฅ๏ธ Output Displays the text "Deleted:", then the value of library.pop(bid)["title"] on the screen
statistics() - lines 127โ€“133
LineCodeWhat it does
127
def statistics():
๐Ÿงฉ Function DEFINES a function statistics(). Python only remembers it here - its body runs later, each time statistics() is called.
129
top = max(library, key=lambda b: library[b]["count"])
๐Ÿงฎ Store / Calculate Finds the largest value among library; the result is stored in variable top
130
print("Titles:", len(library), "| Copies:", sum(r["total"] for r in library.values()),
      "| Issued now:", len(issued))
๐Ÿ–ฅ๏ธ Output Displays the text "Titles:", then the value of len(library), then the text "| Copies:", then the value of sum(r["total"] for r in library.values()), then the text "| Issued now:", then the value of len(issued) on the screen
132
print("Most issued book:", library[top]["title"], f"({library[top]['count']} times)")
๐Ÿ–ฅ๏ธ Output Displays the text "Most issued book:", then the value of library[top]["title"], then the f-string f"({library[top]['count']} times)" with the values filled into { } on the screen
133
print("Total fine collected: Rs.", fine_total)
๐Ÿ–ฅ๏ธ Output Displays the text "Total fine collected: Rs.", then the value of fine_total on the screen
Q1. Why is the book ID used as the dictionary key?

Each ID is unique, so it gives direct (fast) access to a book's record without searching the whole list.

Q2. How is the late fine calculated?

fine = (days kept - 14) x 2 when days are more than 14, otherwise 0.

Q3. Why can't an issued book be deleted?

If available copies are less than total copies, some copies are with members; deleting would lose their record.

Q4. How does partial search work?

The search word is converted to lower case and checked with 'in' against the lower-case title, author and category.

Q5. Which data structure stores the current issues?

A list of dictionaries; each dictionary has the book ID, member name and issue day.

05

Word & Text Analyzer Tool

PYTHONString functionsloopsdictionaries
๐Ÿ“ 122 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 101 output lines๐Ÿ“„ 25+ page report

Accept a paragraph, then report word count, vowel/consonant count, most frequent word, and longest word โ€” useful for a school's creative-writing club to check essay length/quality.

โœจ Features
  • Analyses any paragraph typed by the user or a built-in sample
  • Counts characters, letters, vowels, consonants, digits, spaces, words and sentences
  • Word frequency table with top-5 words and a text bar chart (stop words ignored)
  • Longest / shortest word, average word length and reading time
  • Palindrome words, capitalised words and a word search with positions
  • Text tools: title case, reverse words, remove vowels, word replace, character frequency
โ˜ฐ Main menu
1Enter TextReads a new paragraph (or uses the sample text)
2Basic StatisticsCharacters, letters, vowels, digits, words, sentences
3Word FrequencyTop words with bar chart (stop words removed)
4Word InsightsLongest, shortest, average length, palindromes, capitalised words
5Search WordCounts a word and shows its positions
6Replace WordReplaces every occurrence of a word
7Text ToolsTitle case, reverse order, remove vowels
8Character FrequencyFrequency of each letter
0ExitEnds the program
๐ŸŽฏ Objectives
  • Use split(), strip() and lower() string methods
  • Count word frequency with a dictionary
  • Find the maximum with max() and a key function
๐Ÿ“š Data dictionary
NameTypePurpose
textstrParagraph being analysed
wordslistClean lower-case words of the text
freqdictWord -> number of times it appears
STOPsetCommon words ignored in frequency (the, is, a ...)
VOWELSstr'aeiou'
Why it matters: Combines nearly every string practical (13,14,16,17) into one useful console utility.
# =====================================================================
#   WORD & TEXT ANALYZER TOOL
#   Concepts : strings & string methods, lists, dictionaries, sets,
#              loops, functions, slicing
# =====================================================================

VOWELS = "aeiou"
STOP = {"the", "is", "a", "an", "and", "of", "to", "in", "it", "its", "for", "on", "with", "are", "was", "as", "at", "by", "has", "from"}
text = ("India is a land of diversity. India has many languages, festivals and foods. "
        "The people of India celebrate Diwali, Eid, Christmas and Guru Purab with joy! "
        "Is India a level playing field for every child? Education and technology are changing India.")


def words_of(t):
    """Returns clean lower-case words."""
    return [w.strip('.,!?;:"()').lower() for w in t.split() if w.strip('.,!?;:"()')]


def enter_text():
    """Reads a new paragraph."""
    global text
    t = input("Enter a paragraph (blank = keep sample):\n").strip()
    if not t:
        print("Text cannot be empty - sample text kept.")
        return
    text = t
    print("Text saved:", len(text), "characters")


def basic_stats():
    """Counts different kinds of characters, words and sentences."""
    letters = sum(c.isalpha() for c in text)
    vowels = sum(c.lower() in VOWELS for c in text)
    digits = sum(c.isdigit() for c in text)
    spaces = text.count(" ")
    upper = sum(c.isupper() for c in text)
    sentences = sum(text.count(p) for p in ".!?")
    w = words_of(text)
    print(f"Characters : {len(text)}")
    print(f"Letters    : {letters} (vowels {vowels}, consonants {letters - vowels})")
    print(f"Upper case : {upper} | Digits: {digits} | Spaces: {spaces}")
    print(f"Words      : {len(w)} | Unique words: {len(set(w))}")
    print(f"Sentences  : {sentences}")
    print(f"Reading time (200 words/min): {len(w) / 200 * 60:.0f} seconds")


def word_frequency():
    """Top words with a bar chart."""
    freq = {}
    for w in words_of(text):
        if w not in STOP:
            freq[w] = freq.get(w, 0) + 1
    top = sorted(freq.items(), key=lambda x: (-x[1], x[0]))[:5]
    print("Top words (stop words ignored):")
    for w, n in top:
        print(f"  {w:<12}{n:>3}  " + "#" * (n * 3))


def word_insights():
    """Longest, shortest, average length, palindromes, capitals."""
    w = words_of(text)
    print("Longest word  :", max(w, key=len))
    print("Shortest word :", min(w, key=len))
    print(f"Average length: {sum(len(x) for x in w) / len(w):.2f} letters")
    pal = sorted({x for x in w if len(x) > 2 and x == x[::-1]})
    print("Palindromes   :", pal if pal else "none")
    caps = sorted({x.strip('.,!?') for x in text.split() if x[0].isupper()})
    print("Capitalised   :", ", ".join(caps))


def search_word():
    """Finds positions of a word."""
    key = input("Word to search: ").strip().lower()
    pos = [i + 1 for i, w in enumerate(words_of(text)) if w == key]
    print(f"'{key}' found {len(pos)} time(s) at word positions {pos}")


def replace_word():
    """Replaces a word everywhere."""
    global text
    old = input("Replace word: ").strip()
    new = input("With        : ").strip()
    n = text.count(old)
    text = text.replace(old, new)
    print(n, "replacement(s) done.\n" + text)


def text_tools():
    """Title case, reverse words, remove vowels."""
    print("Title case   :", text.title()[:90] + "...")
    print("Reverse words:", " ".join(text.split()[::-1])[:90] + "...")
    print("No vowels    :", "".join(c for c in text if c.lower() not in VOWELS)[:90] + "...")


def char_frequency():
    """Frequency of each letter."""
    freq = {}
    for c in text.lower():
        if c.isalpha():
            freq[c] = freq.get(c, 0) + 1
    items = sorted(freq.items())
    for i in range(0, len(items), 6):
        print("   ".join(f"{c}:{n:<3}" for c, n in items[i:i + 6]))
    best = max(freq, key=freq.get)
    print("Most frequent letter:", best, f"({freq[best]} times)")


menu = {"1": enter_text, "2": basic_stats, "3": word_frequency, "4": word_insights,
        "5": search_word, "6": replace_word, "7": text_tools, "8": char_frequency}
print("=" * 60)
print("WORD & TEXT ANALYZER".center(60))
print("=" * 60)
print("Sample text loaded:", text[:55] + "...")
while True:
    print("\n1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace")
    print("7.Text Tools 8.Char Frequency 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Thank you for using Text Analyzer.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Load sample text
  3. Display menu and read choice
  4. Choice is 1? → No: run the selected analysis
  5. Read new paragraph
  6. Clean words - lower case, strip punctuation
  7. Count characters / build frequency dictionary
  8. Display statistics, charts or modified text
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Sample text statisticsCounts of letters, vowels, words, sentences printedPASS
2Word frequencyTop-5 words without stop wordsPASS
3Search 'india'Count and word positions shownPASS
4Replace 'India' by 'Bharat'All occurrences replacedPASS
5Word 'level' in textListed as palindromePASS
6Empty paragraph'Text cannot be empty' messagePASS
7Text toolsTitle case, reversed words and vowel-less text printedPASS
8Character frequencyLetters with counts in alphabetical orderPASS
โš  Limitations
  • Only English text is handled
  • Sentence count depends on . ! ? marks
  • Stop-word list is small
  • Text is not saved to a file
๐Ÿš€ Future scope
  • Read text from a .txt file (Class XII file handling)
  • Add sentiment analysis (positive / negative words)
  • Draw a word cloud
  • Support Hindi text

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: VOWELS, STOP, text.
  2. 9 functions are defined (lines 14โ€“105) - Python stores them but does NOT run them yet.
  3. Main program starts at line 108: menu = {"1": enter_text, "2": basic_stats, "3": word_frequency, "4": w - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
words_of(t)14โ€“16Returns clean lower-case words.basic_stats(), word_frequency(), word_insights(), search_word()
enter_text()19โ€“27Reads a new paragraph.main program (menu)
basic_stats()30โ€“44Counts different kinds of characters, words and sentences.main program (menu)
word_frequency()47โ€“56Top words with a bar chart.main program (menu)
word_insights()59โ€“68Longest, shortest, average length, palindromes, capitals.main program (menu)
search_word()71โ€“75Finds positions of a word.main program (menu)
replace_word()78โ€“85Replaces a word everywhere.main program (menu)
text_tools()88โ€“92Title case, reverse words, remove vowels.main program (menu)
char_frequency()95โ€“105Frequency of each letter.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
108
menu = {"1": enter_text, "2": basic_stats, "3": word_frequency, "4": word_insights,
        "5": search_word, "6": replace_word, "7": text_tools, "8": char_fโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": enter_text, "2": basic_stats, "3": wordโ€ฆ in variable menu
110
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
111
print("WORD & TEXT ANALYZER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "WORD & TEXT ANALYZER".center(60) on the screen
112
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
113
print("Sample text loaded:", text[:55] + "...")
๐Ÿ–ฅ๏ธ Output Displays the text "Sample text loaded:", then the value of text[:55] + "..." on the screen
114
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
115
print("\n1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Enter Text 2.Stats 3.Frequency โ€ฆ" on the screen
116
print("7.Text Tools 8.Char Frequency 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "7.Text Tools 8.Char Frequency 0.Eโ€ฆ" on the screen
117
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
118
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
119
print("Thank you for using Text Analyzer.")
๐Ÿ–ฅ๏ธ Output Displays the text "Thank you for using Text Analyzer." on the screen
120
break
๐Ÿ” Loop BREAK - leaves the loop immediately
121
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: WORD & TEXT ANALYZER (+3 more lines)
  2. You type 2 at Enter choice:
    runs: basic_stats() โ†’ words_of()
    shows: Characters : 247 (+7 more lines)
  3. You type 3 at Enter choice:
    runs: word_frequency() โ†’ words_of()
    shows: Top words (stop words ignored): (+7 more lines)
  4. You type 4 at Enter choice:
    runs: word_insights() โ†’ words_of()
    shows: Longest word : technology (+6 more lines)
  5. You type 5 at Enter choice:
    runs: search_word()
  6. You type india at Word to search:
    runs: words_of()
    shows: 'india' found 5 time(s) at word positions [1, 7, 17, 28, 41] (+2 more lines)
  7. You type 6 at Enter choice:
    runs: replace_word()
  8. You type India at Replace word:
  9. You type Bharat at With :
    shows: 5 replacement(s) done. (+3 more lines)
  10. You type 7 at Enter choice:
    runs: text_tools()
    shows: Title case : Bharat Is A Land Of Diversity. Bharat Has Many Languages, Festivals And Foo (+4 more lines)
  11. You type 8 at Enter choice:
    runs: char_frequency()
    shows: a:29 b:7 c:6 d:11 e:18 f:6 (+6 more lines)
  12. You type 1 at Enter choice:
    runs: enter_text()
  13. You type (Enter) at Enter a paragraph (blank = keep sample):
    shows: Text cannot be empty - sample text kept. (+2 more lines)
  14. You type 1 at Enter choice:
    runs: enter_text()
  15. You type Madam Anna saw a level racecar at noon. Wow! 2 kids, 3 dogs. at Enter a paragraph (blank = keep sample):
    shows: Text saved: 60 characters (+2 more lines)
  16. You type 2 at Enter choice:
    runs: basic_stats() โ†’ words_of()
    shows: Characters : 60 (+7 more lines)
  17. You type 4 at Enter choice:
    runs: word_insights() โ†’ words_of()
    shows: Longest word : racecar (+6 more lines)
  18. You type 0 at Enter choice:
    shows: Thank you for using Text Analyzer.
โ‘ค Inside each function - line by line
words_of() - lines 14โ€“16
LineCodeWhat it does
14
def words_of(t):
๐Ÿงฉ Function DEFINES a function words_of(t). Python only remembers it here - its body runs later, each time words_of() is called.
16
return [w.strip('.,!?;:"()').lower() for w in t.split() if w.strip('.,!?;:"()')]
๐Ÿงฉ Function Sends back (returns) a new list made by a list comprehension [w.strip('.,!?;:"()').lower() for w in t.spliโ€ฆ to the line that called the function
enter_text() - lines 19โ€“27
LineCodeWhat it does
19
def enter_text():
๐Ÿงฉ Function DEFINES a function enter_text(). Python only remembers it here - its body runs later, each time enter_text() is called.
21
global text
๐Ÿงฉ Function Tells Python that text means the GLOBAL variable (outside the function)
22
t = input("Enter a paragraph (blank = keep sample):\n").strip()
โŒจ๏ธ Input Shows "Enter a paragraph (blank = keep sample):\n", reads the typed text, removes extra spaces (strip) and stores it in variable t
23
if not t:
๐Ÿ”€ Decision CHECKS whether t is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
24
print("Text cannot be empty - sample text kept.")
๐Ÿ–ฅ๏ธ Output Displays the text "Text cannot be empty - sample texโ€ฆ" on the screen
25
return
๐Ÿงฉ Function Ends the function and goes back to the caller
26
text = t
๐Ÿงฎ Store / Calculate Stores the value of t in variable text
27
print("Text saved:", len(text), "characters")
๐Ÿ–ฅ๏ธ Output Displays the text "Text saved:", then the value of len(text), then the text "characters" on the screen
basic_stats() - lines 30โ€“44
LineCodeWhat it does
30
def basic_stats():
๐Ÿงฉ Function DEFINES a function basic_stats(). Python only remembers it here - its body runs later, each time basic_stats() is called.
32
letters = sum(c.isalpha() for c in text)
๐Ÿงฎ Store / Calculate Adds up all the values in (c.isalpha() for c in text); the result is stored in variable letters
33
vowels = sum(c.lower() in VOWELS for c in text)
๐Ÿงฎ Store / Calculate Adds up all the values in (c.lower() in VOWELS for c in text); the result is stored in variable vowels
34
digits = sum(c.isdigit() for c in text)
๐Ÿงฎ Store / Calculate Adds up all the values in (c.isdigit() for c in text); the result is stored in variable digits
35
spaces = text.count(" ")
๐Ÿงฎ Store / Calculate Counts how many times " " occurs in text; the result is stored in variable spaces
36
upper = sum(c.isupper() for c in text)
๐Ÿงฎ Store / Calculate Adds up all the values in (c.isupper() for c in text); the result is stored in variable upper
37
sentences = sum(text.count(p) for p in ".!?")
๐Ÿงฎ Store / Calculate Adds up all the values in (text.count(p) for p in ".!?"); the result is stored in variable sentences
38
w = words_of(text)
๐Ÿงฎ Store / Calculate Calls our own function words_of(text) - returns clean lower-case words; the result is stored in variable w
39
print(f"Characters : {len(text)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Characters : {len(text)}" with the values filled into { } on the screen
40
print(f"Letters    : {letters} (vowels {vowels}, consonants {letters - vowels})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Letters : {letters} (vowels {vowels}, consoโ€ฆ with the values filled into { } on the screen
41
print(f"Upper case : {upper} | Digits: {digits} | Spaces: {spaces}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Upper case : {upper} | Digits: {digits} | Sโ€ฆ with the values filled into { } on the screen
42
print(f"Words      : {len(w)} | Unique words: {len(set(w))}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Words : {len(w)} | Unique words: {len(set(wโ€ฆ with the values filled into { } on the screen
43
print(f"Sentences  : {sentences}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Sentences : {sentences}" with the values filled into { } on the screen
44
print(f"Reading time (200 words/min): {len(w) / 200 * 60:.0f} seconds")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Reading time (200 words/min): {len(w) / 200โ€ฆ with the values filled into { } on the screen
word_frequency() - lines 47โ€“56
LineCodeWhat it does
47
def word_frequency():
๐Ÿงฉ Function DEFINES a function word_frequency(). Python only remembers it here - its body runs later, each time word_frequency() is called.
49
freq = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable freq
50
for w in words_of(text):
๐Ÿ” Loop LOOP: takes each item of words_of(text) one-by-one into w and runs the indented block for it
51
if w not in STOP:
๐Ÿ”€ Decision CHECKS whether w is not present in STOP. If True, the indented lines below run; otherwise they are skipped
52
freq[w] = freq.get(w, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of freq.get(w, 0) + 1 (calculated using +) into freq[w] (item w of freq)
53
top = sorted(freq.items(), key=lambda x: (-x[1], x[0]))[:5]
๐Ÿงฎ Store / Calculate Stores a slice sorted(freq.items(), key=lambda x: (-x[1], x[โ€ฆ (part of sorted(freq.items(), key=lambda x: (-x[1], x[โ€ฆ) in variable top
54
print("Top words (stop words ignored):")
๐Ÿ–ฅ๏ธ Output Displays the text "Top words (stop words ignored):" on the screen
55
for w, n in top:
๐Ÿ” Loop LOOP: takes each item of top one-by-one into w, n and runs the indented block for it
56
print(f"  {w:<12}{n:>3}  " + "#" * (n * 3))
๐Ÿ–ฅ๏ธ Output Displays the value of f" {w:<12}{n:>3} " + "#" * (n * 3) on the screen
word_insights() - lines 59โ€“68
LineCodeWhat it does
59
def word_insights():
๐Ÿงฉ Function DEFINES a function word_insights(). Python only remembers it here - its body runs later, each time word_insights() is called.
61
w = words_of(text)
๐Ÿงฎ Store / Calculate Calls our own function words_of(text) - returns clean lower-case words; the result is stored in variable w
62
print("Longest word  :", max(w, key=len))
๐Ÿ–ฅ๏ธ Output Displays the text "Longest word :", then the value of max(w, key=len) on the screen
63
print("Shortest word :", min(w, key=len))
๐Ÿ–ฅ๏ธ Output Displays the text "Shortest word :", then the value of min(w, key=len) on the screen
64
print(f"Average length: {sum(len(x) for x in w) / len(w):.2f} letters")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Average length: {sum(len(x) for x in w) / lโ€ฆ with the values filled into { } on the screen
65
pal = sorted({x for x in w if len(x) > 2 and x == x[::-1]})
๐Ÿงฎ Store / Calculate Makes a new sorted list from {x for x in w if len(x) > 2 and x == x[::-1]}; the result is stored in variable pal
66
print("Palindromes   :", pal if pal else "none")
๐Ÿ–ฅ๏ธ Output Displays the text "Palindromes :", then the value of pal if pal else "none" on the screen
67
caps = sorted({x.strip('.,!?') for x in text.split() if x[0].isupper()})
๐Ÿงฎ Store / Calculate Makes a new sorted list from {x.strip('.,!?') for x in text.split() if x[0โ€ฆ; the result is stored in variable caps
68
print("Capitalised   :", ", ".join(caps))
๐Ÿ–ฅ๏ธ Output Displays the text "Capitalised :", then the value of ", ".join(caps) on the screen
search_word() - lines 71โ€“75
LineCodeWhat it does
71
def search_word():
๐Ÿงฉ Function DEFINES a function search_word(). Python only remembers it here - its body runs later, each time search_word() is called.
73
key = input("Word to search: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
74
pos = [i + 1 for i, w in enumerate(words_of(text)) if w == key]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [i + 1 for i, w in enumerate(words_of(text)) โ€ฆ in variable pos
75
print(f"'{key}' found {len(pos)} time(s) at word positions {pos}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"'{key}' found {len(pos)} time(s) at word poโ€ฆ with the values filled into { } on the screen
replace_word() - lines 78โ€“85
LineCodeWhat it does
78
def replace_word():
๐Ÿงฉ Function DEFINES a function replace_word(). Python only remembers it here - its body runs later, each time replace_word() is called.
80
global text
๐Ÿงฉ Function Tells Python that text means the GLOBAL variable (outside the function)
81
old = input("Replace word: ").strip()
โŒจ๏ธ Input Shows "Replace word: ", reads the typed text, removes extra spaces (strip) and stores it in variable old
82
new = input("With        : ").strip()
โŒจ๏ธ Input Shows "With : ", reads the typed text, removes extra spaces (strip) and stores it in variable new
83
n = text.count(old)
๐Ÿงฎ Store / Calculate Counts how many times old occurs in text; the result is stored in variable n
84
text = text.replace(old, new)
๐Ÿงฎ Store / Calculate Replaces old with new in text; the result is stored in variable text
85
print(n, "replacement(s) done.\n" + text)
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the value of "replacement(s) done.\n" + text on the screen
text_tools() - lines 88โ€“92
LineCodeWhat it does
88
def text_tools():
๐Ÿงฉ Function DEFINES a function text_tools(). Python only remembers it here - its body runs later, each time text_tools() is called.
90
print("Title case   :", text.title()[:90] + "...")
๐Ÿ–ฅ๏ธ Output Displays the text "Title case :", then the value of text.title()[:90] + "..." on the screen
91
print("Reverse words:", " ".join(text.split()[::-1])[:90] + "...")
๐Ÿ–ฅ๏ธ Output Displays the text "Reverse words:", then the value of " ".join(text.split()[::-1])[:90] + "..." on the screen
92
print("No vowels    :", "".join(c for c in text if c.lower() not in VOWELS)[:90] + "...")
๐Ÿ–ฅ๏ธ Output Displays the text "No vowels :", then the value of "".join(c for c in text if c.lower() not in Vโ€ฆ on the screen
char_frequency() - lines 95โ€“105
LineCodeWhat it does
95
def char_frequency():
๐Ÿงฉ Function DEFINES a function char_frequency(). Python only remembers it here - its body runs later, each time char_frequency() is called.
97
freq = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable freq
98
for c in text.lower():
๐Ÿ” Loop LOOP: takes each item of text.lower() one-by-one into c and runs the indented block for it
99
if c.isalpha():
๐Ÿ”€ Decision CHECKS whether c.isalpha() is True. If True, the indented lines below run; otherwise they are skipped
100
freq[c] = freq.get(c, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of freq.get(c, 0) + 1 (calculated using +) into freq[c] (item c of freq)
101
items = sorted(freq.items())
๐Ÿงฎ Store / Calculate Makes a new sorted list from freq.items(); the result is stored in variable items
102
for i in range(0, len(items), 6):
๐Ÿ” Loop LOOP: gives the numbers from 0 up to (not including) len(items), jumping by 6; for each number, i takes that value and the indented block runs once
103
print("   ".join(f"{c}:{n:<3}" for c, n in items[i:i + 6]))
๐Ÿ–ฅ๏ธ Output Displays the value of " ".join(f"{c}:{n:<3}" for c, n in items[i:i โ€ฆ on the screen
104
best = max(freq, key=freq.get)
๐Ÿงฎ Store / Calculate Finds the largest value among freq; the result is stored in variable best
105
print("Most frequent letter:", best, f"({freq[best]} times)")
๐Ÿ–ฅ๏ธ Output Displays the text "Most frequent letter:", then the value of best, then the f-string f"({freq[best]} times)" with the values filled into { } on the screen
Q1. How are punctuation marks removed from words?

Each word is passed through strip() with the punctuation characters, e.g. w.strip('.,!?;:"'), then converted to lower case.

Q2. How is the frequency dictionary built?

For each word, freq[w] = freq.get(w, 0) + 1 adds 1 to its count.

Q3. How do you find the top-5 words?

sorted(freq.items(), key=lambda x: x[1], reverse=True)[:5] gives the five most frequent words.

Q4. How is a palindrome word identified?

A word equal to its reverse (w == w[::-1]) with length more than 2.

Q5. What is the use of the set STOP?

Common words like 'the' and 'is' are ignored so that meaningful words appear in the frequency list; set membership checking is fast.

06

Contact Book Manager

PYTHONDictionary of dictionariesstring methodsfunctionssorted()menu-driven design
๐Ÿ“ 150 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 141 output lines๐Ÿ“„ 25+ page report

Add, search (partial name), update, delete and list phone contacts with 10-digit number validation and an A-Z sorted directory.

โœจ Features
  • Contacts with name, mobile, e-mail, city and group (Family / Friends / School / Work)
  • Validation of 10-digit mobile numbers (starting 6-9) and e-mail format
  • Duplicate-number check and favourites
  • Search by name, number or city; filter by group
  • Update any field, delete with confirmation, sort A-Z or by city
  • Birthday-style 'recently added' list and group-wise statistics
โ˜ฐ Main menu
1Add ContactAdds a contact after validating mobile and e-mail
2Show AllAll contacts sorted A-Z in a table
3SearchSearch by part of name, number or city
4Filter by GroupShows contacts of one group
5Update ContactChanges mobile, e-mail, city or group
6Delete ContactDeletes after Y/N confirmation
7FavouritesMarks / lists favourite contacts
8StatisticsGroup-wise and city-wise counts
0ExitCloses the contact book
๐ŸŽฏ Objectives
  • Validate input with isdigit() and len()
  • Use sorted() to display data in alphabetical order
  • Build CRUD operations around a dictionary
๐Ÿ“š Data dictionary
NameTypePurpose
contactsdict of dictName -> {mobile, email, city, group, fav}
GROUPStupleAllowed groups
valid_mobile()functionTrue for 10-digit numbers starting with 6-9
valid_email()functionChecks one '@' and a '.' after it
Why it matters: Shows how a dictionary can behave like a small database and how string functions (title, lower, isdigit) validate real input.
# =====================================================================
#   CONTACT BOOK MANAGER
#   Concepts : dictionaries, strings & validation, functions, loops,
#              sorting, list comprehension
# =====================================================================

GROUPS = ("Family", "Friends", "School", "Work")
contacts = {}


def valid_mobile(m):
    """10 digits starting with 6, 7, 8 or 9."""
    return len(m) == 10 and m.isdigit() and m[0] in "6789"


def valid_email(e):
    """Very simple e-mail check."""
    return e.count("@") == 1 and "." in e.split("@")[1] and not e.startswith("@")


def table(names):
    """Prints contacts as a table."""
    print(f"{'Name':<10}{'Mobile':<12}{'E-mail':<20}{'City':<10}{'Group':<8}Fav")
    print("-" * 64)
    for n in names:
        c = contacts[n]
        print(f"{n:<10}{c['mobile']:<12}{c['email']:<20}{c['city']:<10}{c['group']:<8}{'*' if c['fav'] else ''}")


def add_contact():
    """Adds a contact with validation."""
    name = input("Name   : ").strip().title()
    mobile = input("Mobile : ").strip()
    if not valid_mobile(mobile):
        print("Invalid mobile! 10 digits starting with 6-9 required.")
        return
    for n, c in contacts.items():
        if c["mobile"] == mobile:
            print("Number already saved for", n)
            return
    email = input("E-mail : ").strip().lower()
    if not valid_email(email):
        print("Invalid e-mail address.")
        return
    city = input("City   : ").strip().title()
    group = input("Group " + str(GROUPS) + ": ").strip().title()
    if group not in GROUPS:
        group = "Friends"
    contacts[name] = {"mobile": mobile, "email": email, "city": city, "group": group, "fav": False}
    print("Contact saved:", name)


def show_all():
    """All contacts A-Z."""
    if not contacts:
        print("Contact book is empty.")
        return
    table(sorted(contacts))
    print("Total contacts:", len(contacts))


def search():
    """Search by name, number or city."""
    key = input("Search (name / number / city): ").strip().lower()
    found = [n for n, c in contacts.items() if key in n.lower() or key in c["mobile"] or key in c["city"].lower()]
    if found:
        table(sorted(found))
    else:
        print("No matching contact.")


def by_group():
    """Contacts of one group."""
    g = input("Group: ").strip().title()
    found = [n for n in sorted(contacts) if contacts[n]["group"] == g]
    print(len(found), "contact(s) in", g)
    if found:
        table(found)


def update_contact():
    """Updates one field of a contact."""
    name = input("Name to update: ").strip().title()
    if name not in contacts:
        print("Contact not found.")
        return
    print("1.Mobile 2.E-mail 3.City 4.Group")
    f = input("Field: ").strip()
    keys = {"1": "mobile", "2": "email", "3": "city", "4": "group"}
    if f not in keys:
        print("Invalid field.")
        return
    val = input("New value: ").strip()
    if f == "1" and not valid_mobile(val):
        print("Invalid mobile.")
        return
    contacts[name][keys[f]] = val.title() if f in "34" else val
    print(name, "updated:", contacts[name][keys[f]])


def delete_contact():
    """Deletes after confirmation."""
    name = input("Name to delete: ").strip().title()
    if name not in contacts:
        print("Contact not found.")
        return
    if input(f"Delete {name}? (Y/N): ").strip().upper() == "Y":
        del contacts[name]
        print("Deleted.")
    else:
        print("Not deleted.")


def favourites():
    """Toggle a favourite or list favourites."""
    name = input("Name to mark (or L to list): ").strip().title()
    if name == "L":
        fav = [n for n in sorted(contacts) if contacts[n]["fav"]]
        print("Favourites:", ", ".join(fav) if fav else "none")
    elif name in contacts:
        contacts[name]["fav"] = not contacts[name]["fav"]
        print(name, "is now", "a favourite" if contacts[name]["fav"] else "not a favourite")
    else:
        print("Contact not found.")


def statistics():
    """Group-wise and city-wise counts."""
    for g in GROUPS:
        n = sum(1 for c in contacts.values() if c["group"] == g)
        print(f"{g:<8} {'#' * n} {n}")
    cities = {}
    for c in contacts.values():
        cities[c["city"]] = cities.get(c["city"], 0) + 1
    print("City-wise:", cities)


menu = {"1": add_contact, "2": show_all, "3": search, "4": by_group, "5": update_contact,
        "6": delete_contact, "7": favourites, "8": statistics}
print("=" * 64)
print("CONTACT BOOK MANAGER".center(64))
print("=" * 64)
while True:
    print("\n1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Contact book closed.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Add? → No: run selected option
  4. Read name, mobile, e-mail, city, group
  5. Mobile and e-mail valid? → No: show error and stop adding
  6. Mobile already saved? → No: save contact
  7. Search / filter / update / delete as chosen
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Add Asha 9876543210Contact savedPASS
2Mobile 12345'Invalid mobile' messagePASS
3Mobile starting with 5RejectedPASS
4E-mail 'ravi.gmail.com''Invalid e-mail' messagePASS
5Same mobile for another name'Number already saved for ...'PASS
6Search 'del'Contacts from Delhi listedPASS
7Filter group SchoolOnly School contactsPASS
8Update city of RaviCity changedPASS
9Delete with 'N'Contact keptPASS
10StatisticsGroup-wise and city-wise countsPASS
โš  Limitations
  • Contacts are not stored permanently
  • Only one mobile number per contact
  • Names are case-insensitive keys, two people cannot share a name
  • No import from phone
๐Ÿš€ Future scope
  • Save contacts in a CSV / binary file
  • Export as vCard (.vcf)
  • Add birthday reminders using datetime
  • GUI with Tkinter

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: GROUPS, contacts.
  2. 11 functions are defined (lines 11โ€“135) - Python stores them but does NOT run them yet.
  3. Main program starts at line 138: menu = {"1": add_contact, "2": show_all, "3": search, "4": by_group, " - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
valid_mobile(m)11โ€“1310 digits starting with 6, 7, 8 or 9.add_contact(), update_contact()
valid_email(e)16โ€“18Very simple e-mail check.add_contact()
table(names)21โ€“27Prints contacts as a table.show_all(), search(), by_group()
add_contact()30โ€“50Adds a contact with validation.main program (menu)
show_all()53โ€“59All contacts A-Z.main program (menu)
search()62โ€“69Search by name, number or city.main program (menu)
by_group()72โ€“78Contacts of one group.main program (menu)
update_contact()81โ€“98Updates one field of a contact.main program (menu)
delete_contact()101โ€“111Deletes after confirmation.main program (menu)
favourites()114โ€“124Toggle a favourite or list favourites.main program (menu)
statistics()127โ€“135Group-wise and city-wise counts.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
138
menu = {"1": add_contact, "2": show_all, "3": search, "4": by_group, "5": update_contact,
        "6": delete_contact, "7": favourites, "8": statistics}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_contact, "2": show_all, "3": searchโ€ฆ in variable menu
140
print("=" * 64)
๐Ÿ–ฅ๏ธ Output Displays a line of 64 "=" signs on the screen
141
print("CONTACT BOOK MANAGER".center(64))
๐Ÿ–ฅ๏ธ Output Displays the value of "CONTACT BOOK MANAGER".center(64) on the screen
142
print("=" * 64)
๐Ÿ–ฅ๏ธ Output Displays a line of 64 "=" signs on the screen
143
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
144
print("\n1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Show 3.Search 4.Group 5.Uโ€ฆ" on the screen
145
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
146
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
147
print("Contact book closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Contact book closed." on the screen
148
break
๐Ÿ” Loop BREAK - leaves the loop immediately
149
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CONTACT BOOK MANAGER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add_contact()
  3. You type Asha at Name :
  4. You type 9876543210 at Mobile :
    runs: valid_mobile()
  5. You type asha@kvs.in at E-mail :
    runs: valid_email()
  6. You type Delhi at City :
  7. You type Family at Group ('Family', 'Friends', 'School', 'Work'):
    shows: Contact saved: Asha (+1 more lines)
  8. You type 1 at Enter choice:
    runs: add_contact()
  9. You type Ravi at Name :
  10. You type 12345 at Mobile :
    runs: valid_mobile()
    shows: Invalid mobile! 10 digits starting with 6-9 required. (+1 more lines)
  11. You type 1 at Enter choice:
    runs: add_contact()
  12. You type Ravi at Name :
  13. You type 5876543210 at Mobile :
    runs: valid_mobile()
    shows: Invalid mobile! 10 digits starting with 6-9 required. (+1 more lines)
  14. You type 1 at Enter choice:
    runs: add_contact()
  15. You type Ravi at Name :
  16. You type 9123456780 at Mobile :
    runs: valid_mobile()
  17. You type ravi.gmail.com at E-mail :
    runs: valid_email()
    shows: Invalid e-mail address. (+1 more lines)
  18. You type 1 at Enter choice:
    runs: add_contact()
  19. You type Ravi at Name :
  20. You type 9123456780 at Mobile :
    runs: valid_mobile()
  21. You type ravi@gmail.com at E-mail :
    runs: valid_email()
  22. You type Noida at City :
  23. You type Friends at Group ('Family', 'Friends', 'School', 'Work'):
    shows: Contact saved: Ravi (+1 more lines)
  24. You type 1 at Enter choice:
    runs: add_contact()
  25. You type Neha at Name :
  26. You type 9876543210 at Mobile :
    runs: valid_mobile()
    shows: Number already saved for Asha (+1 more lines)
  27. You type 1 at Enter choice:
    runs: add_contact()
  28. You type Neha at Name :
  29. You type 8800112233 at Mobile :
    runs: valid_mobile()
  30. You type neha@school.org at E-mail :
    runs: valid_email()
  31. You type Delhi at City :
  32. You type School at Group ('Family', 'Friends', 'School', 'Work'):
    shows: Contact saved: Neha (+1 more lines)
  33. You type 1 at Enter choice:
    runs: add_contact()
  34. You type Tarun at Name :
  35. You type 7011223344 at Mobile :
    runs: valid_mobile()
  36. You type tarun@work.com at E-mail :
    runs: valid_email()
  37. You type Gurugram at City :
  38. You type Work at Group ('Family', 'Friends', 'School', 'Work'):
    shows: Contact saved: Tarun (+1 more lines)
  39. You type 2 at Enter choice:
    runs: show_all() โ†’ table()
    shows: Name Mobile E-mail City Group Fav (+6 more lines)
  40. You type 3 at Enter choice:
    runs: search()

โ€ฆ and 20 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
valid_mobile() - lines 11โ€“13
LineCodeWhat it does
11
def valid_mobile(m):
๐Ÿงฉ Function DEFINES a function valid_mobile(m). Python only remembers it here - its body runs later, each time valid_mobile() is called.
13
return len(m) == 10 and m.isdigit() and m[0] in "6789"
๐Ÿงฉ Function Sends back (returns) True/False for (len(m) is equal to 10 AND m.isdigit() is True AND m[0] is present in "6789") to the line that called the function
valid_email() - lines 16โ€“18
LineCodeWhat it does
16
def valid_email(e):
๐Ÿงฉ Function DEFINES a function valid_email(e). Python only remembers it here - its body runs later, each time valid_email() is called.
18
return e.count("@") == 1 and "." in e.split("@")[1] and not e.startswith("@")
๐Ÿงฉ Function Sends back (returns) True/False for (e.count("@") is equal to 1 AND "." is present in e.split("@")[1] AND NOT e.startswith("@") is True) to the line that called the function
table() - lines 21โ€“27
LineCodeWhat it does
21
def table(names):
๐Ÿงฉ Function DEFINES a function table(names). Python only remembers it here - its body runs later, each time table() is called.
23
print(f"{'Name':<10}{'Mobile':<12}{'E-mail':<20}{'City':<10}{'Group':<8}Fav")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Name':<10}{'Mobile':<12}{'E-mail':<20}{'Cโ€ฆ with the values filled into { } on the screen
24
print("-" * 64)
๐Ÿ–ฅ๏ธ Output Displays a line of 64 "-" signs on the screen
25
for n in names:
๐Ÿ” Loop LOOP: takes each item of names one-by-one into n and runs the indented block for it
26
c = contacts[n]
๐Ÿงฎ Store / Calculate Stores the item contacts[n] in variable c
27
print(f"{n:<10}{c['mobile']:<12}{c['email']:<20}{c['city']:<10}{c['group']:<8}{'*' if c['fav'] else ''}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<10}{c['mobile']:<12}{c['email']:<20}{c[โ€ฆ with the values filled into { } on the screen
add_contact() - lines 30โ€“50
LineCodeWhat it does
30
def add_contact():
๐Ÿงฉ Function DEFINES a function add_contact(). Python only remembers it here - its body runs later, each time add_contact() is called.
32
name = input("Name   : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
33
mobile = input("Mobile : ").strip()
โŒจ๏ธ Input Shows "Mobile : ", reads the typed text, removes extra spaces (strip) and stores it in variable mobile
34
if not valid_mobile(mobile):
๐Ÿ”€ Decision CHECKS whether NOT valid_mobile(mobile) is True. If True, the indented lines below run; otherwise they are skipped
35
print("Invalid mobile! 10 digits starting with 6-9 required.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid mobile! 10 digits startinโ€ฆ" on the screen
36
return
๐Ÿงฉ Function Ends the function and goes back to the caller
37
for n, c in contacts.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary contacts; n, c get one pair each round
38
if c["mobile"] == mobile:
๐Ÿ”€ Decision CHECKS whether c["mobile"] is equal to mobile. If True, the indented lines below run; otherwise they are skipped
39
print("Number already saved for", n)
๐Ÿ–ฅ๏ธ Output Displays the text "Number already saved for", then the value of n on the screen
40
return
๐Ÿงฉ Function Ends the function and goes back to the caller
41
email = input("E-mail : ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable email
42
if not valid_email(email):
๐Ÿ”€ Decision CHECKS whether NOT valid_email(email) is True. If True, the indented lines below run; otherwise they are skipped
43
print("Invalid e-mail address.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid e-mail address." on the screen
44
return
๐Ÿงฉ Function Ends the function and goes back to the caller
45
city = input("City   : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable city
46
group = input("Group " + str(GROUPS) + ": ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable group
47
if group not in GROUPS:
๐Ÿ”€ Decision CHECKS whether group is not present in GROUPS. If True, the indented lines below run; otherwise they are skipped
48
group = "Friends"
๐Ÿงฎ Store / Calculate Stores the text "Friends" in variable group
49
contacts[name] = {"mobile": mobile, "email": email, "city": city, "group": group, "fav": False}
๐Ÿงฎ Store / Calculate Puts a dictionary {"mobile": mobile, "email": email, "city": ciโ€ฆ into contacts[name] (item name of contacts)
50
print("Contact saved:", name)
๐Ÿ–ฅ๏ธ Output Displays the text "Contact saved:", then the value of name on the screen
show_all() - lines 53โ€“59
LineCodeWhat it does
53
def show_all():
๐Ÿงฉ Function DEFINES a function show_all(). Python only remembers it here - its body runs later, each time show_all() is called.
55
if not contacts:
๐Ÿ”€ Decision CHECKS whether contacts is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
56
print("Contact book is empty.")
๐Ÿ–ฅ๏ธ Output Displays the text "Contact book is empty." on the screen
57
return
๐Ÿงฉ Function Ends the function and goes back to the caller
58
table(sorted(contacts))
๐Ÿงฎ Store / Calculate Calls our own function table(sorted(contacts)) - prints contacts as a table
59
print("Total contacts:", len(contacts))
๐Ÿ–ฅ๏ธ Output Displays the text "Total contacts:", then the value of len(contacts) on the screen
search() - lines 62โ€“69
LineCodeWhat it does
62
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
64
key = input("Search (name / number / city): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
65
found = [n for n, c in contacts.items() if key in n.lower() or key in c["mobile"] or key in c["city"].lower()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [n for n, c in contacts.items() if key in n.lโ€ฆ in variable found
66
if found:
๐Ÿ”€ Decision CHECKS whether found is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
67
table(sorted(found))
๐Ÿงฎ Store / Calculate Calls our own function table(sorted(found)) - prints contacts as a table
68
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
69
print("No matching contact.")
๐Ÿ–ฅ๏ธ Output Displays the text "No matching contact." on the screen
by_group() - lines 72โ€“78
LineCodeWhat it does
72
def by_group():
๐Ÿงฉ Function DEFINES a function by_group(). Python only remembers it here - its body runs later, each time by_group() is called.
74
g = input("Group: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable g
75
found = [n for n in sorted(contacts) if contacts[n]["group"] == g]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [n for n in sorted(contacts) if contacts[n]["โ€ฆ in variable found
76
print(len(found), "contact(s) in", g)
๐Ÿ–ฅ๏ธ Output Displays the value of len(found), then the text "contact(s) in", then the value of g on the screen
77
if found:
๐Ÿ”€ Decision CHECKS whether found is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
78
table(found)
๐Ÿงฎ Store / Calculate Calls our own function table(found) - prints contacts as a table
update_contact() - lines 81โ€“98
LineCodeWhat it does
81
def update_contact():
๐Ÿงฉ Function DEFINES a function update_contact(). Python only remembers it here - its body runs later, each time update_contact() is called.
83
name = input("Name to update: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
84
if name not in contacts:
๐Ÿ”€ Decision CHECKS whether name is not present in contacts. If True, the indented lines below run; otherwise they are skipped
85
print("Contact not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Contact not found." on the screen
86
return
๐Ÿงฉ Function Ends the function and goes back to the caller
87
print("1.Mobile 2.E-mail 3.City 4.Group")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Mobile 2.E-mail 3.City 4.Group" on the screen
88
f = input("Field: ").strip()
โŒจ๏ธ Input Shows "Field: ", reads the typed text, removes extra spaces (strip) and stores it in variable f
89
keys = {"1": "mobile", "2": "email", "3": "city", "4": "group"}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": "mobile", "2": "email", "3": "city", "4โ€ฆ in variable keys
90
if f not in keys:
๐Ÿ”€ Decision CHECKS whether f is not present in keys. If True, the indented lines below run; otherwise they are skipped
91
print("Invalid field.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid field." on the screen
92
return
๐Ÿงฉ Function Ends the function and goes back to the caller
93
val = input("New value: ").strip()
โŒจ๏ธ Input Shows "New value: ", reads the typed text, removes extra spaces (strip) and stores it in variable val
94
if f == "1" and not valid_mobile(val):
๐Ÿ”€ Decision CHECKS whether (f is equal to "1" AND NOT valid_mobile(val) is True). If True, the indented lines below run; otherwise they are skipped
95
print("Invalid mobile.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid mobile." on the screen
96
return
๐Ÿงฉ Function Ends the function and goes back to the caller
97
contacts[name][keys[f]] = val.title() if f in "34" else val
๐Ÿงฎ Store / Calculate Puts either val.title() or val depending on f in "34" into contacts[name][keys[f]] (item keys[f] of contacts[name])
98
print(name, "updated:", contacts[name][keys[f]])
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "updated:", then the value of contacts[name][keys[f]] on the screen
delete_contact() - lines 101โ€“111
LineCodeWhat it does
101
def delete_contact():
๐Ÿงฉ Function DEFINES a function delete_contact(). Python only remembers it here - its body runs later, each time delete_contact() is called.
103
name = input("Name to delete: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
104
if name not in contacts:
๐Ÿ”€ Decision CHECKS whether name is not present in contacts. If True, the indented lines below run; otherwise they are skipped
105
print("Contact not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Contact not found." on the screen
106
return
๐Ÿงฉ Function Ends the function and goes back to the caller
107
if input(f"Delete {name}? (Y/N): ").strip().upper() == "Y":
๐Ÿ”€ Decision CHECKS whether input(f"Delete {name}? (Y/N): ").strip().uppeโ€ฆ is equal to "Y". If True, the indented lines below run; otherwise Python jumps to the elif/else part
108
del contacts[name]
๐Ÿงฎ Store / Calculate Deletes contacts[name]
109
print("Deleted.")
๐Ÿ–ฅ๏ธ Output Displays the text "Deleted." on the screen
110
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
111
print("Not deleted.")
๐Ÿ–ฅ๏ธ Output Displays the text "Not deleted." on the screen
favourites() - lines 114โ€“124
LineCodeWhat it does
114
def favourites():
๐Ÿงฉ Function DEFINES a function favourites(). Python only remembers it here - its body runs later, each time favourites() is called.
116
name = input("Name to mark (or L to list): ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
117
if name == "L":
๐Ÿ”€ Decision CHECKS whether name is equal to "L". If True, the indented lines below run; otherwise Python jumps to the elif/else part
118
fav = [n for n in sorted(contacts) if contacts[n]["fav"]]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [n for n in sorted(contacts) if contacts[n]["โ€ฆ in variable fav
119
print("Favourites:", ", ".join(fav) if fav else "none")
๐Ÿ–ฅ๏ธ Output Displays the text "Favourites:", then the value of ", ".join(fav) if fav else "none" on the screen
120
elif name in contacts:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether name is present in contacts
121
contacts[name]["fav"] = not contacts[name]["fav"]
๐Ÿงฎ Store / Calculate Puts not contacts[name]["fav"] into contacts[name]["fav"] (item "fav" of contacts[name])
122
print(name, "is now", "a favourite" if contacts[name]["fav"] else "not a favourite")
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "is now", then the value of "a favourite" if contacts[name]["fav"] else "โ€ฆ on the screen
123
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
124
print("Contact not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Contact not found." on the screen
statistics() - lines 127โ€“135
LineCodeWhat it does
127
def statistics():
๐Ÿงฉ Function DEFINES a function statistics(). Python only remembers it here - its body runs later, each time statistics() is called.
129
for g in GROUPS:
๐Ÿ” Loop LOOP: takes each item of GROUPS one-by-one into g and runs the indented block for it
130
n = sum(1 for c in contacts.values() if c["group"] == g)
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for c in contacts.values() if c["group"] =โ€ฆ; the result is stored in variable n
131
print(f"{g:<8} {'#' * n} {n}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{g:<8} {'#' * n} {n}" with the values filled into { } on the screen
132
cities = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable cities
133
for c in contacts.values():
๐Ÿ” Loop LOOP: takes each item of contacts.values() one-by-one into c and runs the indented block for it
134
cities[c["city"]] = cities.get(c["city"], 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of cities.get(c["city"], 0) + 1 (calculated using +) into cities[c["city"]] (item c["city"] of cities)
135
print("City-wise:", cities)
๐Ÿ–ฅ๏ธ Output Displays the text "City-wise:", then the value of cities on the screen
Q1. How is a mobile number validated?

It must have exactly 10 characters, all digits (isdigit()) and must start with 6, 7, 8 or 9.

Q2. How is a duplicate number detected?

By looping over contacts.values() and comparing each stored mobile with the new number.

Q3. Why is title() used on names?

So that 'asha', 'ASHA' and 'Asha' are stored the same way and searching becomes reliable.

Q4. How are contacts shown in A-Z order?

sorted(contacts) returns the keys (names) in alphabetical order.

Q5. How does group filtering work?

A list comprehension selects names whose 'group' field equals the chosen group.

07

Tic-Tac-Toe (Two Player Game)

PYTHONListsloopsfunctionsfor-elseany()
๐Ÿ“ 127 lines of codeโ˜ฐ 6 menu options๐Ÿ–ฅ๏ธ 245 output lines๐Ÿ“„ 25+ page report

A complete two-player Tic-Tac-Toe game: prints the board after every move, rejects occupied squares, detects the winning line and declares a draw.

โœจ Features
  • Two-player game and Player-vs-Computer mode
  • Computer uses a simple AI strategy: win if possible, block the opponent, else take centre/corner
  • Input validation for occupied or invalid cells
  • Score board across several rounds with draws
  • Players can enter their names and choose who starts
  • Move history of every round
โ˜ฐ Main menu
1Two PlayersTwo people play turn by turn on the same computer
2Vs ComputerPlay against the rule-based computer player
3Score BoardWins of each player and number of draws
4How to PlayRules and board numbering
5Reset ScoresClears the score board
0ExitShows the final scores and ends
๐ŸŽฏ Objectives
  • Represent a board with a list and print it neatly
  • Check winning conditions with tuples and any()
  • Use the for-else construct to detect a draw
๐Ÿ“š Data dictionary
NameTypePurpose
boardlist of 9 strCells of the board: 'X', 'O' or ' '
WINStuple of tuplesThe 8 winning lines (rows, columns, diagonals)
scoresdictPlayer name -> wins, plus 'Draw'
moveslistPositions played in the current round
Why it matters: Shows list indexing, nested decision logic and the loop-else construct in a game students enjoy.
# =====================================================================
#   TIC-TAC-TOE  (Two Players + Player vs Computer)
#   Concepts : lists, tuples, dictionaries, functions, loops,
#              conditions, simple game AI
# =====================================================================

WINS = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
scores = {"Draw": 0}


def show(board):
    """Draws the board."""
    print()
    for i in range(0, 9, 3):
        print("  " + " | ".join(board[i] if board[i] != " " else str(i + 1) for i in range(i, i + 3)))
        if i < 6:
            print(" ---+---+---")
    print()


def winner(board, mark):
    """True if mark has three in a line."""
    return any(board[a] == board[b] == board[c] == mark for a, b, c in WINS)


def read_move(board, name):
    """Reads a valid free cell."""
    while True:
        try:
            pos = int(input(f"{name}, choose cell (1-9): ")) - 1
        except ValueError:
            print("Enter a number.")
            continue
        if pos not in range(9):
            print("Enter 1-9.")
        elif board[pos] != " ":
            print("Cell already taken!")
        else:
            return pos


def computer_move(board, me, opp):
    """Win, else block, else centre, corners, sides."""
    for mark in (me, opp):
        for i in range(9):
            if board[i] == " ":
                board[i] = mark
                if winner(board, mark):
                    board[i] = " "
                    return i
                board[i] = " "
    for i in (4, 0, 2, 6, 8, 1, 3, 5, 7):
        if board[i] == " ":
            return i


def play(p1, p2, vs_computer=False):
    """Plays one round and returns the winner's name or 'Draw'."""
    board, moves = [" "] * 9, []
    players = [(p1, "X"), (p2, "O")]
    for turn in range(9):
        name, mark = players[turn % 2]
        show(board)
        if vs_computer and name == "Computer":
            pos = computer_move(board, "O", "X")
            print("Computer chooses", pos + 1)
        else:
            pos = read_move(board, f"{name} ({mark})")
        board[pos] = mark
        moves.append(pos + 1)
        if winner(board, mark):
            show(board)
            print(f"*** {name} wins in {len(moves)} moves! ***")
            print("Moves:", moves)
            return name
    show(board)
    print("Match drawn! Moves:", moves)
    return "Draw"


def record(result):
    """Updates the score board."""
    scores[result] = scores.get(result, 0) + 1


def score_board():
    """Displays scores."""
    print("SCORE BOARD")
    for name, n in sorted(scores.items(), key=lambda x: -x[1]):
        print(f"  {name:<10}{n:>3}  " + "*" * n)


def rules():
    """Shows how to play."""
    print("Get three of your marks in a row, column or diagonal.")
    print("Cells are numbered:")
    show([" "] * 9)


print("=" * 40)
print("TIC - TAC - TOE".center(40))
print("=" * 40)
while True:
    print("\n1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "1":
        a = input("Player X name: ").strip().title() or "Player X"
        b = input("Player O name: ").strip().title() or "Player O"
        record(play(a, b))
    elif ch == "2":
        a = input("Your name: ").strip().title() or "Player"
        record(play(a, "Computer", vs_computer=True))
    elif ch == "3":
        score_board()
    elif ch == "4":
        rules()
    elif ch == "5":
        scores.clear()
        scores["Draw"] = 0
        print("Scores reset.")
    elif ch == "0":
        score_board()
        print("Thanks for playing!")
        break
    else:
        print("Invalid choice")

        
  1. Start
  2. Display menu and read choice
  3. Choice is a game mode? → No: show scores / rules / exit
  4. Create empty board and set first player
  5. Read move (or computer chooses move)
  6. Cell free and valid? → No: ask again
  7. Place mark and check winning lines
  8. Winner or board full? → No: switch player
  9. Update score board
  10. Stop
#Test case / inputExpected resultStatus
1Rahul X: 1,2,3 vs Priya O: 5,9Rahul wins (top row)PASS
2Move on occupied cell'Cell already taken' and ask againPASS
3Move 10'Enter 1-9'PASS
4All 9 cells filled, no line'Match drawn'PASS
5Computer can win in one moveComputer completes its linePASS
6Player about to winComputer blocks the cellPASS
7Score board after 3 gamesWins and draws counted correctlyPASS
8Reset scoresAll scores 0PASS
โš  Limitations
  • Text-based board only
  • Computer strategy is simple, not unbeatable
  • Scores are lost on exit
  • Only 3 x 3 board
๐Ÿš€ Future scope
  • Minimax algorithm for an unbeatable computer
  • Graphical board using Tkinter / pygame
  • Save scores to a file
  • Online two-player mode

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: WINS, scores.
  2. 8 functions are defined (lines 11โ€“97) - Python stores them but does NOT run them yet.
  3. Main program starts at line 100: print("=" * 40) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
show(board)11โ€“18Draws the board.play(), rules()
winner(board, mark)21โ€“23True if mark has three in a line.computer_move(), play()
read_move(board, name)26โ€“39Reads a valid free cell.play()
computer_move(board, me, opp)42โ€“54Win, else block, else centre, corners, sides.play()
play(p1, p2, vs_computer)57โ€“78Plays one round and returns the winner's name or 'Draw'.main program
record(result)81โ€“83Updates the score board.main program
score_board()86โ€“90Displays scores.main program
rules()93โ€“97Shows how to play.main program
โ‘ข Main program - line by line
LineCodeWhat it does
100
print("=" * 40)
๐Ÿ–ฅ๏ธ Output Displays a line of 40 "=" signs on the screen
101
print("TIC - TAC - TOE".center(40))
๐Ÿ–ฅ๏ธ Output Displays the value of "TIC - TAC - TOE".center(40) on the screen
102
print("=" * 40)
๐Ÿ–ฅ๏ธ Output Displays a line of 40 "=" signs on the screen
103
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
104
print("\n1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Two Players 2.Vs Computer 3.Scoโ€ฆ" on the screen
105
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
106
if ch == "1":
๐Ÿ”€ Decision CHECKS whether ch is equal to "1". If True, the indented lines below run; otherwise Python jumps to the elif/else part
107
a = input("Player X name: ").strip().title() or "Player X"
โŒจ๏ธ Input Stores the value of input("Player X name: ").strip().title(), or "Player X" if the first one is empty / None / 0 in variable a
108
b = input("Player O name: ").strip().title() or "Player O"
โŒจ๏ธ Input Stores the value of input("Player O name: ").strip().title(), or "Player O" if the first one is empty / None / 0 in variable b
109
record(play(a, b))
๐Ÿงฎ Store / Calculate Calls our own function record(play(a, b)) - updates the score board
110
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
111
a = input("Your name: ").strip().title() or "Player"
โŒจ๏ธ Input Stores the value of input("Your name: ").strip().title(), or "Player" if the first one is empty / None / 0 in variable a
112
record(play(a, "Computer", vs_computer=True))
๐Ÿงฎ Store / Calculate Calls our own function record(play(a, "Computer",โ€ฆ) - updates the score board
113
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
114
score_board()
๐Ÿงฎ Store / Calculate Calls our own function score_board() - displays scores
115
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
116
rules()
๐Ÿงฎ Store / Calculate Calls our own function rules() - shows how to play
117
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
118
scores.clear()
๐Ÿงฎ Store / Calculate Removes all items from scores
119
scores["Draw"] = 0
๐Ÿงฎ Store / Calculate Puts the number 0 into scores["Draw"] (item "Draw" of scores)
120
print("Scores reset.")
๐Ÿ–ฅ๏ธ Output Displays the text "Scores reset." on the screen
121
elif ch == "0":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "0"
122
score_board()
๐Ÿงฎ Store / Calculate Calls our own function score_board() - displays scores
123
print("Thanks for playing!")
๐Ÿ–ฅ๏ธ Output Displays the text "Thanks for playing!" on the screen
124
break
๐Ÿ” Loop BREAK - leaves the loop immediately
125
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
126
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: TIC - TAC - TOE (+1 more lines)
  2. You type 4 at Enter choice:
    runs: rules() โ†’ show()
    shows: Get three of your marks in a row, column or diagonal. (+7 more lines)
  3. You type 1 at Enter choice:
  4. You type Rahul at Player X name:
  5. You type Priya at Player O name:
    runs: play() โ†’ show() โ†’ read_move()
    shows: 1 | 2 | 3 (+4 more lines)
  6. You type 1 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: X | 2 | 3 (+4 more lines)
  7. You type 5 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: X | 2 | 3 (+4 more lines)
  8. You type 2 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: X | X | 3 (+4 more lines)
  9. You type 5 at Priya (O), choose cell (1-9):
    shows: Cell already taken!
  10. You type 9 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: X | X | 3 (+4 more lines)
  11. You type 10 at Rahul (X), choose cell (1-9):
    shows: Enter 1-9.
  12. You type 3 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ record()
    shows: X | X | X (+7 more lines)
  13. You type 1 at Enter choice:
  14. You type Rahul at Player X name:
  15. You type Priya at Player O name:
    runs: play() โ†’ show() โ†’ read_move()
    shows: 1 | 2 | 3 (+4 more lines)
  16. You type 5 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: 1 | 2 | 3 (+4 more lines)
  17. You type 1 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | 2 | 3 (+4 more lines)
  18. You type 9 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | 2 | 3 (+4 more lines)
  19. You type 3 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | 2 | O (+4 more lines)
  20. You type 2 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | X | O (+4 more lines)
  21. You type 8 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | X | O (+4 more lines)
  22. You type 4 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | X | O (+4 more lines)
  23. You type 6 at Priya (O), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ read_move()
    shows: O | X | O (+4 more lines)
  24. You type 7 at Rahul (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ record()
    shows: O | X | O (+6 more lines)
  25. You type 2 at Enter choice:
  26. You type Anu at Your name:
    runs: play() โ†’ show() โ†’ read_move()
    shows: 1 | 2 | 3 (+4 more lines)
  27. You type 1 at Anu (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ computer_move() โ†’ winner() ร—17 โ†’ show() โ†’ read_move()
    shows: X | 2 | 3 (+10 more lines)
  28. You type 2 at Anu (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ computer_move() โ†’ winner() ร—8 โ†’ show() โ†’ read_move()
    shows: X | X | 3 (+10 more lines)
  29. You type 6 at Anu (X), choose cell (1-9):
    runs: winner() โ†’ show() โ†’ computer_move() โ†’ winner() ร—3 โ†’ show() โ†’ record()
    shows: X | X | O (+13 more lines)
  30. You type 7 at Enter choice:
    shows: Invalid choice (+1 more lines)
  31. You type 3 at Enter choice:
    runs: score_board()
    shows: SCORE BOARD (+4 more lines)
  32. You type 5 at Enter choice:
    shows: Scores reset. (+1 more lines)
  33. You type 3 at Enter choice:
    runs: score_board()
    shows: SCORE BOARD (+2 more lines)
  34. You type 0 at Enter choice:
    runs: score_board()
    shows: SCORE BOARD (+2 more lines)
โ‘ค Inside each function - line by line
show() - lines 11โ€“18
LineCodeWhat it does
11
def show(board):
๐Ÿงฉ Function DEFINES a function show(board). Python only remembers it here - its body runs later, each time show() is called.
13
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
14
for i in range(0, 9, 3):
๐Ÿ” Loop LOOP: gives the numbers from 0 up to (not including) 9, jumping by 3; for each number, i takes that value and the indented block runs once
15
print("  " + " | ".join(board[i] if board[i] != " " else str(i + 1) for i in range(i, i + 3)))
๐Ÿ–ฅ๏ธ Output Displays the value of " " + " | ".join(board[i] if board[i] != " " โ€ฆ on the screen
16
if i < 6:
๐Ÿ”€ Decision CHECKS whether i is less than 6. If True, the indented lines below run; otherwise they are skipped
17
print(" ---+---+---")
๐Ÿ–ฅ๏ธ Output Displays the text "---+---+---" on the screen
18
print()
๐Ÿ–ฅ๏ธ Output Prints an empty line
winner() - lines 21โ€“23
LineCodeWhat it does
21
def winner(board, mark):
๐Ÿงฉ Function DEFINES a function winner(board, mark). Python only remembers it here - its body runs later, each time winner() is called.
23
return any(board[a] == board[b] == board[c] == mark for a, b, c in WINS)
๐Ÿงฉ Function Sends back (returns) the result of: is True if at least one value in (board[a] == board[b] == board[c] == mark forโ€ฆ is True to the line that called the function
read_move() - lines 26โ€“39
LineCodeWhat it does
26
def read_move(board, name):
๐Ÿงฉ Function DEFINES a function read_move(board, name). Python only remembers it here - its body runs later, each time read_move() is called.
28
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
29
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
30
pos = int(input(f"{name}, choose cell (1-9): ")) - 1
โŒจ๏ธ Input Stores the value of int(input(f"{name}, choose cell (1-9): ")) - 1 (calculated using -) in variable pos
31
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
32
print("Enter a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a number." on the screen
33
continue
๐Ÿ” Loop CONTINUE - skips the rest of this round and goes to the next round of the loop
34
if pos not in range(9):
๐Ÿ”€ Decision CHECKS whether pos is not present in range(9). If True, the indented lines below run; otherwise Python jumps to the elif/else part
35
print("Enter 1-9.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter 1-9." on the screen
36
elif board[pos] != " ":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether board[pos] is not equal to " "
37
print("Cell already taken!")
๐Ÿ–ฅ๏ธ Output Displays the text "Cell already taken!" on the screen
38
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
39
return pos
๐Ÿงฉ Function Sends back (returns) the value of pos to the line that called the function
computer_move() - lines 42โ€“54
LineCodeWhat it does
42
def computer_move(board, me, opp):
๐Ÿงฉ Function DEFINES a function computer_move(board, me, opp). Python only remembers it here - its body runs later, each time computer_move() is called.
44
for mark in (me, opp):
๐Ÿ” Loop LOOP: takes each item of (me, opp) one-by-one into mark and runs the indented block for it
45
for i in range(9):
๐Ÿ” Loop LOOP: gives the numbers 0 to 8 (9 numbers); for each number, i takes that value and the indented block runs once
46
if board[i] == " ":
๐Ÿ”€ Decision CHECKS whether board[i] is equal to " ". If True, the indented lines below run; otherwise they are skipped
47
board[i] = mark
๐Ÿงฎ Store / Calculate Puts the value of mark into board[i] (item i of board)
48
if winner(board, mark):
๐Ÿ”€ Decision CHECKS whether winner(board, mark) is True. If True, the indented lines below run; otherwise they are skipped
49
board[i] = " "
๐Ÿงฎ Store / Calculate Puts the text " " into board[i] (item i of board)
50
return i
๐Ÿงฉ Function Sends back (returns) the value of i to the line that called the function
51
board[i] = " "
๐Ÿงฎ Store / Calculate Puts the text " " into board[i] (item i of board)
52
for i in (4, 0, 2, 6, 8, 1, 3, 5, 7):
๐Ÿ” Loop LOOP: takes each item of (4, 0, 2, 6, 8, 1, 3, 5, 7) one-by-one into i and runs the indented block for it
53
if board[i] == " ":
๐Ÿ”€ Decision CHECKS whether board[i] is equal to " ". If True, the indented lines below run; otherwise they are skipped
54
return i
๐Ÿงฉ Function Sends back (returns) the value of i to the line that called the function
play() - lines 57โ€“78
LineCodeWhat it does
57
def play(p1, p2, vs_computer=False):
๐Ÿงฉ Function DEFINES a function play(p1, p2, vs_computer). Python only remembers it here - its body runs later, each time play() is called.
59
board, moves = [" "] * 9, []
๐Ÿงฎ Store / Calculate Stores [" "] * 9, [] into board, moves respectively
60
players = [(p1, "X"), (p2, "O")]
๐Ÿงฎ Store / Calculate Stores a list [(p1, "X"), (p2, "O")] in variable players
61
for turn in range(9):
๐Ÿ” Loop LOOP: gives the numbers 0 to 8 (9 numbers); for each number, turn takes that value and the indented block runs once
62
name, mark = players[turn % 2]
๐Ÿงฎ Store / Calculate Stores the item players[turn % 2] in variables name, mark
63
show(board)
๐Ÿงฎ Store / Calculate Calls our own function show(board) - draws the board
64
if vs_computer and name == "Computer":
๐Ÿ”€ Decision CHECKS whether (vs_computer is True (not empty / not zero) AND name is equal to "Computer"). If True, the indented lines below run; otherwise Python jumps to the elif/else part
65
pos = computer_move(board, "O", "X")
๐Ÿงฎ Store / Calculate Calls our own function computer_move(board, "O", "X") - win, else block, else centre, corners, sides; the result is stored in variable pos
66
print("Computer chooses", pos + 1)
๐Ÿ–ฅ๏ธ Output Displays the text "Computer chooses", then the value of pos + 1 on the screen
67
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
68
pos = read_move(board, f"{name} ({mark})")
๐Ÿงฎ Store / Calculate Calls our own function read_move(board, f"{name} ({mark})") - reads a valid free cell; the result is stored in variable pos
69
board[pos] = mark
๐Ÿงฎ Store / Calculate Puts the value of mark into board[pos] (item pos of board)
70
moves.append(pos + 1)
๐Ÿงฎ Store / Calculate Adds pos + 1 at the end of list moves
71
if winner(board, mark):
๐Ÿ”€ Decision CHECKS whether winner(board, mark) is True. If True, the indented lines below run; otherwise they are skipped
72
show(board)
๐Ÿงฎ Store / Calculate Calls our own function show(board) - draws the board
73
print(f"*** {name} wins in {len(moves)} moves! ***")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"*** {name} wins in {len(moves)} moves! ***" with the values filled into { } on the screen
74
print("Moves:", moves)
๐Ÿ–ฅ๏ธ Output Displays the text "Moves:", then the value of moves on the screen
75
return name
๐Ÿงฉ Function Sends back (returns) the value of name to the line that called the function
76
show(board)
๐Ÿงฎ Store / Calculate Calls our own function show(board) - draws the board
77
print("Match drawn! Moves:", moves)
๐Ÿ–ฅ๏ธ Output Displays the text "Match drawn! Moves:", then the value of moves on the screen
78
return "Draw"
๐Ÿงฉ Function Sends back (returns) the text "Draw" to the line that called the function
record() - lines 81โ€“83
LineCodeWhat it does
81
def record(result):
๐Ÿงฉ Function DEFINES a function record(result). Python only remembers it here - its body runs later, each time record() is called.
83
scores[result] = scores.get(result, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of scores.get(result, 0) + 1 (calculated using +) into scores[result] (item result of scores)
score_board() - lines 86โ€“90
LineCodeWhat it does
86
def score_board():
๐Ÿงฉ Function DEFINES a function score_board(). Python only remembers it here - its body runs later, each time score_board() is called.
88
print("SCORE BOARD")
๐Ÿ–ฅ๏ธ Output Displays the text "SCORE BOARD" on the screen
89
for name, n in sorted(scores.items(), key=lambda x: -x[1]):
๐Ÿ” Loop LOOP: takes each item of sorted(scores.items(), key=lambda x: -x[1]) one-by-one into name, n and runs the indented block for it
90
print(f"  {name:<10}{n:>3}  " + "*" * n)
๐Ÿ–ฅ๏ธ Output Displays the value of f" {name:<10}{n:>3} " + "*" * n on the screen
rules() - lines 93โ€“97
LineCodeWhat it does
93
def rules():
๐Ÿงฉ Function DEFINES a function rules(). Python only remembers it here - its body runs later, each time rules() is called.
95
print("Get three of your marks in a row, column or diagonal.")
๐Ÿ–ฅ๏ธ Output Displays the text "Get three of your marks in a row,โ€ฆ" on the screen
96
print("Cells are numbered:")
๐Ÿ–ฅ๏ธ Output Displays the text "Cells are numbered:" on the screen
97
show([" "] * 9)
๐Ÿงฎ Store / Calculate Calls our own function show([" "] * 9) - draws the board
Q1. How are winning combinations stored?

As a tuple of eight tuples of cell indexes, e.g. (0,1,2) for the top row; the program checks if all three cells hold the same mark.

Q2. How does the computer choose a move?

First it tries every empty cell to see if it can win, then checks if the opponent could win there (to block), else it prefers the centre, corners and sides.

Q3. How is a draw detected?

If no player has won and there is no ' ' left in the board list.

Q4. Why is the board a list and not a string?

Lists are mutable, so a cell can be changed with board[i] = 'X'; strings cannot be changed.

Q5. How does the program switch players?

With a conditional expression: player = 'O' if player == 'X' else 'X'.

08

Hangman Word Game

PYTHONStringslistsrandom modulewhile-elseinput validation
๐Ÿ“ 108 lines of codeโ˜ฐ 6 menu options๐Ÿ–ฅ๏ธ 155 output lines๐Ÿ“„ 25+ page report

Guess the hidden computer-science word letter by letter with 6 lives; handles repeated letters, wrong input and shows progress after every guess.

โœจ Features
  • Three categories of words - Computer, Science and Geography - with hints
  • Lives shown with a growing hangman drawing (7 stages)
  • Guess a letter or the whole word; repeated and invalid guesses are not penalised
  • Hint costs one life
  • Score = remaining lives x 10 + word length bonus; best score and history kept
  • Statistics of games won / lost and win percentage
โ˜ฐ Main menu
1Play GameChoose a category and guess the hidden word
2StatisticsGames played, won, lost, win % and best score
3Game HistoryWord, result and score of each game
4Add WordAdds a new word with a hint to a category
5How to PlayRules of the game
0ExitEnds the game
๐ŸŽฏ Objectives
  • Traverse strings and lists to reveal letters
  • Choose a random word using the random module
  • Validate input and manage lives with while-else
๐Ÿ“š Data dictionary
NameTypePurpose
WORDSdict of listCategory -> list of (word, hint) tuples
STAGESlist of strHangman drawings for 0 to 6 wrong guesses
guessedsetLetters guessed in the current game
historylist of tuple(word, result, score) of each game
livesintRemaining lives (starts at 6)
Why it matters: Combines string traversal, list membership tests and the random module in a fun, easily extensible program.
# =====================================================================
#   HANGMAN WORD GAME  (categories, hints, scores, statistics)
#   Concepts : strings, lists, tuples, sets, dictionaries, functions,
#              loops, random module
# =====================================================================
import random

WORDS = {"Computer": [("keyboard", "Input device with keys"), ("python", "Language used in CBSE"),
                      ("monitor", "Output device"), ("compiler", "Translates the whole program")],
         "Science": [("oxygen", "Gas we breathe in"), ("gravity", "Force that pulls objects down"),
                     ("neutron", "Particle with no charge")],
         "Geography": [("himalaya", "Highest mountain range"), ("ganga", "Holy river of India"),
                       ("deccan", "Plateau of southern India")]}
STAGES = ["", "  O", "  O\n  |", "  O\n /|", "  O\n /|\\", "  O\n /|\\\n /", "  O\n /|\\\n / \\"]
history = []


def play():
    """Plays one game and stores the result."""
    cats = list(WORDS)
    for i, c in enumerate(cats, 1):
        print(f"{i}.{c}", end="  ")
    try:
        cat = cats[int(input("\nCategory: ")) - 1]
    except (ValueError, IndexError):
        cat = random.choice(cats)
    word, hint = random.choice(WORDS[cat])
    guessed, lives, wrong = set(), 6, []
    print(f"Category: {cat} | The word has {len(word)} letters.")
    while lives > 0:
        print(STAGES[6 - lives])
        print("Word :", " ".join(c if c in guessed else "_" for c in word))
        print("Lives:", "<3 " * lives, "| Wrong:", " ".join(wrong) or "-")
        g = input("Guess a letter / the word / 'hint': ").strip().lower()
        if g == "hint":
            lives -= 1
            print("Hint:", hint, "(1 life used)")
        elif g == word:
            guessed.update(word)
        elif len(g) != 1 or not g.isalpha():
            print("Enter one letter or the full word.")
        elif g in guessed or g in wrong:
            print("Already guessed", g)
        elif g in word:
            guessed.add(g)
            print("Good guess!", g, "appears", word.count(g), "time(s)")
        else:
            wrong.append(g)
            lives -= 1
            print("Wrong guess!")
        if all(c in guessed for c in word):
            score = lives * 10 + len(word)
            print("Word:", word.upper(), "- YOU WIN! Score:", score)
            history.append((word, "Won", score))
            return
    print(STAGES[6])
    print("GAME OVER! The word was:", word.upper())
    history.append((word, "Lost", 0))


def statistics():
    """Games played, won, lost and best score."""
    won = sum(1 for h in history if h[1] == "Won")
    n = len(history)
    print("Games played:", n, "| Won:", won, "| Lost:", n - won)
    if n:
        print(f"Win percentage: {won / n * 100:.1f}% | Best score: {max(h[2] for h in history)}")


def show_history():
    """Shows every game played."""
    for i, (w, r, s) in enumerate(history, 1):
        print(f"{i}. {w:<10}{r:<6}{s:>4}")
    if not history:
        print("No games yet.")


def add_word():
    """Adds a new word and hint."""
    cat = input("Category: ").strip().title()
    w = input("New word: ").strip().lower()
    if not w.isalpha():
        print("Word must have letters only.")
        return
    h = input("Hint    : ").strip()
    WORDS.setdefault(cat, []).append((w, h))
    print("Added to", cat, "- words now:", len(WORDS[cat]))


def rules():
    """How to play."""
    print("Guess the hidden word one letter at a time. You have 6 lives.")
    print("Each wrong letter or hint costs a life. Type the full word to win at once.")


print("=" * 50)
print("H A N G M A N".center(50))
print("=" * 50)
menu = {"1": play, "2": statistics, "3": show_history, "4": add_word, "5": rules}
while True:
    print("\n1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        statistics()
        print("Bye! Keep learning new words.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Play? → No: show stats / history / add word
  4. Choose category; computer picks a random word
  5. Show drawing, masked word and read guess
  6. Guess correct? → No: lose a life
  7. Word complete or lives = 0? → No: read next guess
  8. Calculate score and save history
  9. Stop
#Test case / inputExpected resultStatus
1Correct letterLetter revealed in the wordPASS
2Wrong letterLife reduced and drawing growsPASS
3Same letter twice'Already guessed' - no life lostPASS
4Input '7' or 'ab''Enter one letter or the full word'PASS
5Ask hintHint shown, one life deductedPASS
6Whole word typed correctlyGame won immediatelyPASS
7Lives become 0Game over and word revealedPASS
8StatisticsWin % and best score correctPASS
โš  Limitations
  • Word lists are small and stored in the program
  • Single player only
  • Statistics are lost when the program closes
  • Text drawing only
๐Ÿš€ Future scope
  • Load thousands of words from a text file
  • Two-player mode where one player sets the word
  • Graphical version with turtle / pygame
  • Difficulty levels by word length

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): random - random number functions are loaded.
  2. Global variables / constants are created: WORDS, STAGES, history.
  3. 5 functions are defined (lines 18โ€“93) - Python stores them but does NOT run them yet.
  4. Main program starts at line 96: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
play()18โ€“58Plays one game and stores the result.main program (menu)
statistics()61โ€“67Games played, won, lost and best score.main program (menu), main program
show_history()70โ€“75Shows every game played.main program (menu)
add_word()78โ€“87Adds a new word and hint.main program (menu)
rules()90โ€“93How to play.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
96
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
97
print("H A N G M A N".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "H A N G M A N".center(50) on the screen
98
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
99
menu = {"1": play, "2": statistics, "3": show_history, "4": add_word, "5": rules}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": play, "2": statistics, "3": show_historโ€ฆ in variable menu
100
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
101
print("\n1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Play 2.Statistics 3.History 4.Aโ€ฆ" on the screen
102
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
103
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
104
statistics()
๐Ÿงฎ Store / Calculate Calls our own function statistics() - games played, won, lost and best score
105
print("Bye! Keep learning new words.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye! Keep learning new words." on the screen
106
break
๐Ÿ” Loop BREAK - leaves the loop immediately
107
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: H A N G M A N (+1 more lines)
  2. You type 5 at Enter choice:
    runs: rules()
    shows: Guess the hidden word one letter at a time. You have 6 lives. (+2 more lines)
  3. You type 1 at Enter choice:
    runs: play()
    shows: 1.Computer 2.Science 3.Geography
  4. You type 1 at Category:
    shows: Category: Computer | The word has 8 letters. (+2 more lines)
  5. You type e at Guess a letter / the word / 'hint':
    shows: Good guess! e appears 1 time(s) (+2 more lines)
  6. You type a at Guess a letter / the word / 'hint':
    shows: Good guess! a appears 1 time(s) (+2 more lines)
  7. You type ab at Guess a letter / the word / 'hint':
    shows: Enter one letter or the full word. (+2 more lines)
  8. You type o at Guess a letter / the word / 'hint':
    shows: Good guess! o appears 1 time(s) (+2 more lines)
  9. You type e at Guess a letter / the word / 'hint':
    shows: Already guessed e (+2 more lines)
  10. You type r at Guess a letter / the word / 'hint':
    shows: Good guess! r appears 1 time(s) (+2 more lines)
  11. You type k at Guess a letter / the word / 'hint':
    shows: Good guess! k appears 1 time(s) (+2 more lines)
  12. You type y at Guess a letter / the word / 'hint':
    shows: Good guess! y appears 1 time(s) (+2 more lines)
  13. You type b at Guess a letter / the word / 'hint':
    shows: Good guess! b appears 1 time(s) (+2 more lines)
  14. You type d at Guess a letter / the word / 'hint':
    shows: Good guess! d appears 1 time(s) (+2 more lines)
  15. You type 1 at Enter choice:
    runs: play()
    shows: 1.Computer 2.Science 3.Geography
  16. You type 2 at Category:
    shows: Category: Science | The word has 7 letters. (+2 more lines)
  17. You type hint at Guess a letter / the word / 'hint':
    shows: Hint: Force that pulls objects down (1 life used) (+3 more lines)
  18. You type o at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+4 more lines)
  19. You type n at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+4 more lines)
  20. You type z at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+4 more lines)
  21. You type x at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+5 more lines)
  22. You type q at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+5 more lines)
  23. You type 4 at Enter choice:
    runs: add_word()
  24. You type Science at Category:
  25. You type atom at New word:
  26. You type Smallest unit of an element at Hint :
    shows: Added to Science - words now: 4 (+1 more lines)
  27. You type 1 at Enter choice:
    runs: play()
    shows: 1.Computer 2.Science 3.Geography
  28. You type 3 at Category:
    shows: Category: Geography | The word has 6 letters. (+2 more lines)
  29. You type c at Guess a letter / the word / 'hint':
    shows: Good guess! c appears 2 time(s) (+2 more lines)
  30. You type x at Guess a letter / the word / 'hint':
    shows: Wrong guess! (+3 more lines)
  31. You type deccan at Guess a letter / the word / 'hint':
    shows: Word: DECCAN - YOU WIN! Score: 56 (+1 more lines)
  32. You type 2 at Enter choice:
    runs: statistics()
    shows: Games played: 3 | Won: 2 | Lost: 1 (+2 more lines)
  33. You type 3 at Enter choice:
    runs: show_history()
    shows: 1. keyboard Won 68 (+3 more lines)
  34. You type 0 at Enter choice:
    runs: statistics()
    shows: Games played: 3 | Won: 2 | Lost: 1 (+2 more lines)
โ‘ค Inside each function - line by line
play() - lines 18โ€“58
LineCodeWhat it does
18
def play():
๐Ÿงฉ Function DEFINES a function play(). Python only remembers it here - its body runs later, each time play() is called.
20
cats = list(WORDS)
๐Ÿงฎ Store / Calculate Makes a list from WORDS; the result is stored in variable cats
21
for i, c in enumerate(cats, 1):
๐Ÿ” Loop LOOP over cats with position: in each round i, c get (position, item)
22
print(f"{i}.{c}", end="  ")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i}.{c}" with the values filled into { } on the screen (ends with " " instead of a new line)
23
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
24
cat = cats[int(input("\nCategory: ")) - 1]
โŒจ๏ธ Input Stores a slice cats[int(input("\nCategory: ")) - 1] (part of cats) in variable cat
25
except (ValueError, IndexError):
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, IndexError) occurs - that error
26
cat = random.choice(cats)
๐Ÿงฎ Store / Calculate Picks one random item from cats; the result is stored in variable cat
27
word, hint = random.choice(WORDS[cat])
๐Ÿงฎ Store / Calculate Picks one random item from WORDS[cat]; the result is stored in variables word, hint
28
guessed, lives, wrong = set(), 6, []
๐Ÿงฎ Store / Calculate Stores set(), 6, [] into guessed, lives, wrong respectively
29
print(f"Category: {cat} | The word has {len(word)} letters.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Category: {cat} | The word has {len(word)} โ€ฆ with the values filled into { } on the screen
30
while lives > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as lives is greater than 0; checks the condition before every round
31
print(STAGES[6 - lives])
๐Ÿ–ฅ๏ธ Output Displays the value of STAGES[6 - lives] on the screen
32
print("Word :", " ".join(c if c in guessed else "_" for c in word))
๐Ÿ–ฅ๏ธ Output Displays the text "Word :", then the value of " ".join(c if c in guessed else "_" for c in โ€ฆ on the screen
33
print("Lives:", "<3 " * lives, "| Wrong:", " ".join(wrong) or "-")
๐Ÿ–ฅ๏ธ Output Displays the text "Lives:", then the value of "<3 " * lives, then the text "| Wrong:", then the value of " ".join(wrong) or "-" on the screen
34
g = input("Guess a letter / the word / 'hint': ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable g
35
if g == "hint":
๐Ÿ”€ Decision CHECKS whether g is equal to "hint". If True, the indented lines below run; otherwise Python jumps to the elif/else part
36
lives -= 1
๐Ÿงฎ Store / Calculate Subtracts 1 from lives (same as lives = lives - 1)
37
print("Hint:", hint, "(1 life used)")
๐Ÿ–ฅ๏ธ Output Displays the text "Hint:", then the value of hint, then the text "(1 life used)" on the screen
38
elif g == word:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether g is equal to word
39
guessed.update(word)
๐Ÿงฎ Store / Calculate Updates guessed with word
40
elif len(g) != 1 or not g.isalpha():
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (len(g) is not equal to 1 OR NOT g.isalpha() is True)
41
print("Enter one letter or the full word.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter one letter or the full word." on the screen
42
elif g in guessed or g in wrong:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (g is present in guessed OR g is present in wrong)
43
print("Already guessed", g)
๐Ÿ–ฅ๏ธ Output Displays the text "Already guessed", then the value of g on the screen
44
elif g in word:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether g is present in word
45
guessed.add(g)
๐Ÿงฎ Store / Calculate Adds g to guessed
46
print("Good guess!", g, "appears", word.count(g), "time(s)")
๐Ÿ–ฅ๏ธ Output Displays the text "Good guess!", then the value of g, then the text "appears", then the value of word.count(g), then the text "time(s)" on the screen
47
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
48
wrong.append(g)
๐Ÿงฎ Store / Calculate Adds g at the end of list wrong
49
lives -= 1
๐Ÿงฎ Store / Calculate Subtracts 1 from lives (same as lives = lives - 1)
50
print("Wrong guess!")
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong guess!" on the screen
51
if all(c in guessed for c in word):
๐Ÿ”€ Decision CHECKS whether all(c in guessed for c in word) is True. If True, the indented lines below run; otherwise they are skipped
52
score = lives * 10 + len(word)
๐Ÿงฎ Store / Calculate Stores the value of lives * 10 + len(word) (calculated using +) in variable score
53
print("Word:", word.upper(), "- YOU WIN! Score:", score)
๐Ÿ–ฅ๏ธ Output Displays the text "Word:", then the value of word.upper(), then the text "- YOU WIN! Score:", then the value of score on the screen
54
history.append((word, "Won", score))
๐Ÿงฎ Store / Calculate Adds (word, "Won", score) at the end of list history
55
return
๐Ÿงฉ Function Ends the function and goes back to the caller
56
print(STAGES[6])
๐Ÿ–ฅ๏ธ Output Displays the value of STAGES[6] on the screen
57
print("GAME OVER! The word was:", word.upper())
๐Ÿ–ฅ๏ธ Output Displays the text "GAME OVER! The word was:", then the value of word.upper() on the screen
58
history.append((word, "Lost", 0))
๐Ÿงฎ Store / Calculate Adds (word, "Lost", 0) at the end of list history
statistics() - lines 61โ€“67
LineCodeWhat it does
61
def statistics():
๐Ÿงฉ Function DEFINES a function statistics(). Python only remembers it here - its body runs later, each time statistics() is called.
63
won = sum(1 for h in history if h[1] == "Won")
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for h in history if h[1] == "Won"); the result is stored in variable won
64
n = len(history)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in history; the result is stored in variable n
65
print("Games played:", n, "| Won:", won, "| Lost:", n - won)
๐Ÿ–ฅ๏ธ Output Displays the text "Games played:", then the value of n, then the text "| Won:", then the value of won, then the text "| Lost:", then the value of n - won on the screen
66
if n:
๐Ÿ”€ Decision CHECKS whether n is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
67
print(f"Win percentage: {won / n * 100:.1f}% | Best score: {max(h[2] for h in history)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Win percentage: {won / n * 100:.1f}% | Bestโ€ฆ with the values filled into { } on the screen
show_history() - lines 70โ€“75
LineCodeWhat it does
70
def show_history():
๐Ÿงฉ Function DEFINES a function show_history(). Python only remembers it here - its body runs later, each time show_history() is called.
72
for i, (w, r, s) in enumerate(history, 1):
๐Ÿ” Loop LOOP over history with position: in each round i, (w, r, s) get (position, item)
73
print(f"{i}. {w:<10}{r:<6}{s:>4}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i}. {w:<10}{r:<6}{s:>4}" with the values filled into { } on the screen
74
if not history:
๐Ÿ”€ Decision CHECKS whether history is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
75
print("No games yet.")
๐Ÿ–ฅ๏ธ Output Displays the text "No games yet." on the screen
add_word() - lines 78โ€“87
LineCodeWhat it does
78
def add_word():
๐Ÿงฉ Function DEFINES a function add_word(). Python only remembers it here - its body runs later, each time add_word() is called.
80
cat = input("Category: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cat
81
w = input("New word: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable w
82
if not w.isalpha():
๐Ÿ”€ Decision CHECKS whether NOT w.isalpha() is True. If True, the indented lines below run; otherwise they are skipped
83
print("Word must have letters only.")
๐Ÿ–ฅ๏ธ Output Displays the text "Word must have letters only." on the screen
84
return
๐Ÿงฉ Function Ends the function and goes back to the caller
85
h = input("Hint    : ").strip()
โŒจ๏ธ Input Shows "Hint : ", reads the typed text, removes extra spaces (strip) and stores it in variable h
86
WORDS.setdefault(cat, []).append((w, h))
๐Ÿงฎ Store / Calculate Adds (w, h) at the end of list WORDS.setdefault(cat, [])
87
print("Added to", cat, "- words now:", len(WORDS[cat]))
๐Ÿ–ฅ๏ธ Output Displays the text "Added to", then the value of cat, then the text "- words now:", then the value of len(WORDS[cat]) on the screen
rules() - lines 90โ€“93
LineCodeWhat it does
90
def rules():
๐Ÿงฉ Function DEFINES a function rules(). Python only remembers it here - its body runs later, each time rules() is called.
92
print("Guess the hidden word one letter at a time. You have 6 lives.")
๐Ÿ–ฅ๏ธ Output Displays the text "Guess the hidden word one letter โ€ฆ" on the screen
93
print("Each wrong letter or hint costs a life. Type the full word to win at once.")
๐Ÿ–ฅ๏ธ Output Displays the text "Each wrong letter or hint costs aโ€ฆ" on the screen
Q1. Why is a set used for guessed letters?

A set keeps unique letters and checking membership ('a' in guessed) is very fast.

Q2. How is the masked word displayed?

A generator expression joins each letter if it has been guessed, otherwise '_': ' '.join(c if c in guessed else '_' for c in word).

Q3. Which function picks a random word?

random.choice() picks one (word, hint) tuple from the chosen category list.

Q4. How is the score calculated?

score = lives left x 10 + length of the word; only won games get a score.

Q5. How does the program know the word is complete?

When every letter of the word is in the guessed set: all(c in guessed for c in word).

09

Student Attendance Register

PYTHONDictionary of listsnested loopscount()percentagemax() with key
๐Ÿ“ 123 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 152 output lines๐Ÿ“„ 25+ page report

Record P/A attendance of every student for a week, calculate attendance percentage, flag students below 75% and name the best attendee.

โœจ Features
  • Class register with roll numbers and names
  • Mark attendance day by day with P / A / L (leave) codes and validation
  • Student-wise report: present, absent, leave, attendance % and status
  • Day-wise report: strength present each day with bar chart
  • Defaulters below 75 % and consecutive-absence alert (3 days)
  • Edit a wrong entry and search a student
โ˜ฐ Main menu
1Mark AttendanceMarks P / A / L for every student for a new day
2Student ReportPresent, absent, leave and % of each student
3Day-wise ReportNumber present each day with a bar chart
4DefaultersStudents below 75 % attendance
5Absence AlertStudents absent 3 days in a row
6Search StudentFull attendance record of one student
7Edit EntryCorrects the mark of a student for a day
8Add StudentAdds a new student to the register
0ExitPrints the summary and ends
๐ŸŽฏ Objectives
  • Store lists inside a dictionary
  • Compute percentage with count() and formatted output
  • Validate P/A entries with a while loop
๐Ÿ“š Data dictionary
NameTypePurpose
registerdictRoll no -> {'name': str, 'marks': list of 'P'/'A'/'L'}
dayslist of strDates / day labels marked so far
CODESdict'P' Present, 'A' Absent, 'L' Leave
LIMITintMinimum attendance percentage - 75
Why it matters: A practical school problem solved with a dictionary of lists, aggregate functions and formatted reports.
# =====================================================================
#   STUDENT ATTENDANCE REGISTER
#   Concepts : dictionaries, lists, strings, loops, functions,
#              counting and percentages
# =====================================================================

CODES = {"P": "Present", "A": "Absent", "L": "Leave"}
LIMIT = 75
register = {1: {"name": "Aman", "marks": []}, 2: {"name": "Bhavna", "marks": []},
            3: {"name": "Chirag", "marks": []}, 4: {"name": "Deepa", "marks": []},
            5: {"name": "Eshan", "marks": []}, 6: {"name": "Farah", "marks": []}}
days = []


def pct(marks):
    """Attendance % - leave counts as attended."""
    return (marks.count("P") + marks.count("L")) / len(marks) * 100 if marks else 0


def mark_attendance():
    """Marks P / A / L for a new day."""
    day = input("Day / date label: ").strip()
    days.append(day)
    for roll, s in register.items():
        while True:
            m = input(f"  {roll}. {s['name']:<8} (P/A/L): ").strip().upper()
            if m in CODES:
                break
            print("  Enter P, A or L.")
        s["marks"] += [" "] * (len(days) - 1 - len(s["marks"]))
        s["marks"].append(m)
    print("Attendance saved for", day, "- present:", sum(1 for s in register.values() if s["marks"][-1] == "P"))


def student_report():
    """Report of all students."""
    print(f"{'Roll':<5}{'Name':<9}{'P':>3}{'A':>3}{'L':>3}{'%':>8}  Status")
    print("-" * 42)
    for roll, s in register.items():
        m = s["marks"]
        p = pct(m)
        print(f"{roll:<5}{s['name']:<9}{m.count('P'):>3}{m.count('A'):>3}{m.count('L'):>3}{p:>7.1f}%  {'OK' if p >= LIMIT else 'SHORTAGE'}")
    print("Days marked:", len(days), days)


def day_report():
    """Presents per day."""
    for i, d in enumerate(days):
        n = sum(1 for s in register.values() if len(s["marks"]) > i and s["marks"][i] == "P")
        print(f"{d:<5} {n}/{len(register)}  " + "#" * (n * 3))


def defaulters():
    """Students below the limit."""
    low = [(r, s["name"], pct(s["marks"])) for r, s in register.items() if pct(s["marks"]) < LIMIT]
    if not low:
        print("No defaulters.")
    for r, n, p in low:
        print(f"Roll {r} {n:<8} {p:.1f}%  -> needs {LIMIT}% ; inform parents")


def absence_alert():
    """3 consecutive absences."""
    found = False
    for r, s in register.items():
        if "AAA" in "".join(s["marks"]):
            print(f"ALERT: Roll {r} {s['name']} was absent 3 days in a row!")
            found = True
    if not found:
        print("No continuous absence.")


def search():
    """Record of one student."""
    try:
        r = int(input("Roll number: "))
    except ValueError:
        print("Enter a number.")
        return
    if r not in register:
        print("Roll number not found.")
        return
    s = register[r]
    print(s["name"], ":", "  ".join(f"{d}-{m}" for d, m in zip(days, s["marks"])))
    print(f"Attendance {pct(s['marks']):.1f}%")


def edit_entry():
    """Corrects one entry."""
    try:
        r = int(input("Roll number: "))
        d = int(input(f"Day number (1-{len(days)}): ")) - 1
        m = input("Correct mark (P/A/L): ").strip().upper()
        if m not in CODES:
            raise ValueError
        register[r]["marks"][d] = m
        print("Updated:", register[r]["name"], days[d], "->", CODES[m])
    except (ValueError, KeyError, IndexError):
        print("Invalid entry.")


def add_student():
    """Adds a student to the register."""
    name = input("Name: ").strip().title()
    roll = max(register) + 1
    register[roll] = {"name": name, "marks": ["A"] * 0}
    print(name, "added with roll number", roll, "(attendance starts from the next day)")


menu = {"1": mark_attendance, "2": student_report, "3": day_report, "4": defaulters,
        "5": absence_alert, "6": search, "7": edit_entry, "8": add_student}
print("=" * 50)
print("CLASS XI-A ATTENDANCE REGISTER".center(50))
print("=" * 50)
while True:
    print("\n1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert")
    print("6.Search 7.Edit 8.Add Student 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Register closed. Total days:", len(days))
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Load class register
  3. Display menu and read choice
  4. Choice is Mark Attendance? → No: run selected report
  5. Read day label and P/A/L for each student
  6. Code valid? → No: ask again
  7. Append mark to each student's list
  8. Reports - % = (P + L) / days x 100
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Mark day with code 'X''Enter P, A or L' and asked againPASS
2Student present 4 of 5 days80.0 % - OKPASS
3Student present 2 of 540.0 % - SHORTAGEPASS
4Leave daysCounted as attended in %PASS
53 consecutive AAlert printed for the studentPASS
6Day-wise reportPresents per day with bar chartPASS
7Edit roll 3 day 2 to PRecord and % updatedPASS
8Search roll 9'Roll number not found'PASS
โš  Limitations
  • Attendance is kept only during the run
  • Day labels are typed by the teacher
  • One class at a time
  • No holiday calendar
๐Ÿš€ Future scope
  • Store the register in a CSV file month-wise
  • SMS / e-mail alert to parents
  • Use datetime for automatic dates
  • Monthly graph with Matplotlib

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: CODES, LIMIT, register, days.
  2. 9 functions are defined (lines 15โ€“107) - Python stores them but does NOT run them yet.
  3. Main program starts at line 110: menu = {"1": mark_attendance, "2": student_report, "3": day_report, "4 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
pct(marks)15โ€“17Attendance % - leave counts as attended.student_report(), defaulters(), search()
mark_attendance()20โ€“32Marks P / A / L for a new day.main program (menu)
student_report()35โ€“43Report of all students.main program (menu)
day_report()46โ€“50Presents per day.main program (menu)
defaulters()53โ€“59Students below the limit.main program (menu)
absence_alert()62โ€“703 consecutive absences.main program (menu)
search()73โ€“85Record of one student.main program (menu)
edit_entry()88โ€“99Corrects one entry.main program (menu)
add_student()102โ€“107Adds a student to the register.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
110
menu = {"1": mark_attendance, "2": student_report, "3": day_report, "4": defaulters,
        "5": absence_alert, "6": search, "7": edit_entry, "8": add_student}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": mark_attendance, "2": student_report, "โ€ฆ in variable menu
112
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
113
print("CLASS XI-A ATTENDANCE REGISTER".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "CLASS XI-A ATTENDANCE REGISTER".center(50) on the screen
114
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
115
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
116
print("\n1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Mark 2.Student Report 3.Day Repโ€ฆ" on the screen
117
print("6.Search 7.Edit 8.Add Student 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "6.Search 7.Edit 8.Add Student 0.Eโ€ฆ" on the screen
118
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
119
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
120
print("Register closed. Total days:", len(days))
๐Ÿ–ฅ๏ธ Output Displays the text "Register closed. Total days:", then the value of len(days) on the screen
121
break
๐Ÿ” Loop BREAK - leaves the loop immediately
122
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CLASS XI-A ATTENDANCE REGISTER (+2 more lines)
  2. You type 1 at Enter choice:
    runs: mark_attendance()
  3. You type Mon at Day / date label:
  4. You type P at 1. Aman (P/A/L):
  5. You type P at 2. Bhavna (P/A/L):
  6. You type A at 3. Chirag (P/A/L):
  7. You type P at 4. Deepa (P/A/L):
  8. You type P at 5. Eshan (P/A/L):
  9. You type P at 6. Farah (P/A/L):
    shows: Attendance saved for Mon - present: 5 (+2 more lines)
  10. You type 1 at Enter choice:
    runs: mark_attendance()
  11. You type Tue at Day / date label:
  12. You type P at 1. Aman (P/A/L):
  13. You type A at 2. Bhavna (P/A/L):
  14. You type A at 3. Chirag (P/A/L):
  15. You type P at 4. Deepa (P/A/L):
  16. You type X at 5. Eshan (P/A/L):
    shows: Enter P, A or L.
  17. You type L at 5. Eshan (P/A/L):
  18. You type P at 6. Farah (P/A/L):
    shows: Attendance saved for Tue - present: 3 (+2 more lines)
  19. You type 1 at Enter choice:
    runs: mark_attendance()
  20. You type Wed at Day / date label:
  21. You type P at 1. Aman (P/A/L):
  22. You type P at 2. Bhavna (P/A/L):
  23. You type A at 3. Chirag (P/A/L):
  24. You type P at 4. Deepa (P/A/L):
  25. You type P at 5. Eshan (P/A/L):
  26. You type A at 6. Farah (P/A/L):
    shows: Attendance saved for Wed - present: 4 (+2 more lines)
  27. You type 1 at Enter choice:
    runs: mark_attendance()
  28. You type Thu at Day / date label:
  29. You type P at 1. Aman (P/A/L):
  30. You type A at 2. Bhavna (P/A/L):
  31. You type A at 3. Chirag (P/A/L):
  32. You type P at 4. Deepa (P/A/L):
  33. You type P at 5. Eshan (P/A/L):
  34. You type P at 6. Farah (P/A/L):
    shows: Attendance saved for Thu - present: 4 (+2 more lines)
  35. You type 1 at Enter choice:
    runs: mark_attendance()
  36. You type Fri at Day / date label:
  37. You type A at 1. Aman (P/A/L):
  38. You type P at 2. Bhavna (P/A/L):
  39. You type P at 3. Chirag (P/A/L):
  40. You type P at 4. Deepa (P/A/L):

โ€ฆ and 20 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
pct() - lines 15โ€“17
LineCodeWhat it does
15
def pct(marks):
๐Ÿงฉ Function DEFINES a function pct(marks). Python only remembers it here - its body runs later, each time pct() is called.
17
return (marks.count("P") + marks.count("L")) / len(marks) * 100 if marks else 0
๐Ÿงฉ Function Sends back (returns) either (marks.count("P") + marks.count("L")) / len(mโ€ฆ or 0 depending on marks to the line that called the function
mark_attendance() - lines 20โ€“32
LineCodeWhat it does
20
def mark_attendance():
๐Ÿงฉ Function DEFINES a function mark_attendance(). Python only remembers it here - its body runs later, each time mark_attendance() is called.
22
day = input("Day / date label: ").strip()
โŒจ๏ธ Input Shows "Day / date label: ", reads the typed text, removes extra spaces (strip) and stores it in variable day
23
days.append(day)
๐Ÿงฎ Store / Calculate Adds day at the end of list days
24
for roll, s in register.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary register; roll, s get one pair each round
25
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
26
m = input(f"  {roll}. {s['name']:<8} (P/A/L): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable m
27
if m in CODES:
๐Ÿ”€ Decision CHECKS whether m is present in CODES. If True, the indented lines below run; otherwise they are skipped
28
break
๐Ÿ” Loop BREAK - leaves the loop immediately
29
print("  Enter P, A or L.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter P, A or L." on the screen
30
s["marks"] += [" "] * (len(days) - 1 - len(s["marks"]))
๐Ÿงฎ Store / Calculate Adds [" "] * (len(days) - 1 - len(s["marks"])) to s["marks"] (same as s["marks"] = s["marks"] + [" "] * (len(days) - 1 -โ€ฆ)
31
s["marks"].append(m)
๐Ÿงฎ Store / Calculate Adds m at the end of list s["marks"]
32
print("Attendance saved for", day, "- present:", sum(1 for s in register.values() if s["marks"][-1] == "P"))
๐Ÿ–ฅ๏ธ Output Displays the text "Attendance saved for", then the value of day, then the text "- present:", then the value of sum(1 for s in register.values() if s["marks"โ€ฆ on the screen
student_report() - lines 35โ€“43
LineCodeWhat it does
35
def student_report():
๐Ÿงฉ Function DEFINES a function student_report(). Python only remembers it here - its body runs later, each time student_report() is called.
37
print(f"{'Roll':<5}{'Name':<9}{'P':>3}{'A':>3}{'L':>3}{'%':>8}  Status")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Roll':<5}{'Name':<9}{'P':>3}{'A':>3}{'L':โ€ฆ with the values filled into { } on the screen
38
print("-" * 42)
๐Ÿ–ฅ๏ธ Output Displays a line of 42 "-" signs on the screen
39
for roll, s in register.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary register; roll, s get one pair each round
40
m = s["marks"]
๐Ÿงฎ Store / Calculate Stores the item s["marks"] in variable m
41
p = pct(m)
๐Ÿงฎ Store / Calculate Calls our own function pct(m) - attendance % - leave counts as attended; the result is stored in variable p
42
print(f"{roll:<5}{s['name']:<9}{m.count('P'):>3}{m.count('A'):>3}{m.count('L'):>3}{p:>7.1f}%  {'OK' if p >= LIMIT else 'SHORTAGE'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{roll:<5}{s['name']:<9}{m.count('P'):>3}{m.โ€ฆ with the values filled into { } on the screen
43
print("Days marked:", len(days), days)
๐Ÿ–ฅ๏ธ Output Displays the text "Days marked:", then the value of len(days), then the value of days on the screen
day_report() - lines 46โ€“50
LineCodeWhat it does
46
def day_report():
๐Ÿงฉ Function DEFINES a function day_report(). Python only remembers it here - its body runs later, each time day_report() is called.
48
for i, d in enumerate(days):
๐Ÿ” Loop LOOP over days with position: in each round i, d get (position, item)
49
n = sum(1 for s in register.values() if len(s["marks"]) > i and s["marks"][i] == "P")
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for s in register.values() if len(s["marksโ€ฆ; the result is stored in variable n
50
print(f"{d:<5} {n}/{len(register)}  " + "#" * (n * 3))
๐Ÿ–ฅ๏ธ Output Displays the value of f"{d:<5} {n}/{len(register)} " + "#" * (n * 3) on the screen
defaulters() - lines 53โ€“59
LineCodeWhat it does
53
def defaulters():
๐Ÿงฉ Function DEFINES a function defaulters(). Python only remembers it here - its body runs later, each time defaulters() is called.
55
low = [(r, s["name"], pct(s["marks"])) for r, s in register.items() if pct(s["marks"]) < LIMIT]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [(r, s["name"], pct(s["marks"])) for r, s in โ€ฆ in variable low
56
if not low:
๐Ÿ”€ Decision CHECKS whether low is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
57
print("No defaulters.")
๐Ÿ–ฅ๏ธ Output Displays the text "No defaulters." on the screen
58
for r, n, p in low:
๐Ÿ” Loop LOOP: takes each item of low one-by-one into r, n, p and runs the indented block for it
59
print(f"Roll {r} {n:<8} {p:.1f}%  -> needs {LIMIT}% ; inform parents")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Roll {r} {n:<8} {p:.1f}% -> needs {LIMIT}% โ€ฆ with the values filled into { } on the screen
absence_alert() - lines 62โ€“70
LineCodeWhat it does
62
def absence_alert():
๐Ÿงฉ Function DEFINES a function absence_alert(). Python only remembers it here - its body runs later, each time absence_alert() is called.
64
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
65
for r, s in register.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary register; r, s get one pair each round
66
if "AAA" in "".join(s["marks"]):
๐Ÿ”€ Decision CHECKS whether "AAA" is present in "".join(s["marks"]). If True, the indented lines below run; otherwise they are skipped
67
print(f"ALERT: Roll {r} {s['name']} was absent 3 days in a row!")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"ALERT: Roll {r} {s['name']} was absent 3 daโ€ฆ with the values filled into { } on the screen
68
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
69
if not found:
๐Ÿ”€ Decision CHECKS whether found is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
70
print("No continuous absence.")
๐Ÿ–ฅ๏ธ Output Displays the text "No continuous absence." on the screen
search() - lines 73โ€“85
LineCodeWhat it does
73
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
75
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
76
r = int(input("Roll number: "))
โŒจ๏ธ Input Shows "Roll number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable r
77
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
78
print("Enter a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a number." on the screen
79
return
๐Ÿงฉ Function Ends the function and goes back to the caller
80
if r not in register:
๐Ÿ”€ Decision CHECKS whether r is not present in register. If True, the indented lines below run; otherwise they are skipped
81
print("Roll number not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Roll number not found." on the screen
82
return
๐Ÿงฉ Function Ends the function and goes back to the caller
83
s = register[r]
๐Ÿงฎ Store / Calculate Stores the item register[r] in variable s
84
print(s["name"], ":", "  ".join(f"{d}-{m}" for d, m in zip(days, s["marks"])))
๐Ÿ–ฅ๏ธ Output Displays the value of s["name"], then the text ":", then the value of " ".join(f"{d}-{m}" for d, m in zip(days, s["โ€ฆ on the screen
85
print(f"Attendance {pct(s['marks']):.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Attendance {pct(s['marks']):.1f}%" with the values filled into { } on the screen
edit_entry() - lines 88โ€“99
LineCodeWhat it does
88
def edit_entry():
๐Ÿงฉ Function DEFINES a function edit_entry(). Python only remembers it here - its body runs later, each time edit_entry() is called.
90
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
91
r = int(input("Roll number: "))
โŒจ๏ธ Input Shows "Roll number: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable r
92
d = int(input(f"Day number (1-{len(days)}): ")) - 1
โŒจ๏ธ Input Stores the value of int(input(f"Day number (1-{len(days)}): ")) -โ€ฆ (calculated using -) in variable d
93
m = input("Correct mark (P/A/L): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable m
94
if m not in CODES:
๐Ÿ”€ Decision CHECKS whether m is not present in CODES. If True, the indented lines below run; otherwise they are skipped
95
raise ValueError
๐Ÿ›ก๏ธ Error handling RAISES (creates) an error ValueError
96
register[r]["marks"][d] = m
๐Ÿงฎ Store / Calculate Puts the value of m into register[r]["marks"][d] (item d of register[r]["marks"])
97
print("Updated:", register[r]["name"], days[d], "->", CODES[m])
๐Ÿ–ฅ๏ธ Output Displays the text "Updated:", then the value of register[r]["name"], then the value of days[d], then the text "->", then the value of CODES[m] on the screen
98
except (ValueError, KeyError, IndexError):
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, KeyError, IndexError) occurs - that error
99
print("Invalid entry.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid entry." on the screen
add_student() - lines 102โ€“107
LineCodeWhat it does
102
def add_student():
๐Ÿงฉ Function DEFINES a function add_student(). Python only remembers it here - its body runs later, each time add_student() is called.
104
name = input("Name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
105
roll = max(register) + 1
๐Ÿงฎ Store / Calculate Stores the value of max(register) + 1 (calculated using +) in variable roll
106
register[roll] = {"name": name, "marks": ["A"] * 0}
๐Ÿงฎ Store / Calculate Puts a dictionary {"name": name, "marks": ["A"] * 0} into register[roll] (item roll of register)
107
print(name, "added with roll number", roll, "(attendance starts from the next day)")
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "added with roll number", then the value of roll, then the text "(attendance starts from the next โ€ฆ" on the screen
Q1. How is attendance percentage calculated?

(present days + leave days) / total days x 100; leave is treated as authorised.

Q2. How are consecutive absences found?

By checking if the string 'AAA' appears in ''.join(marks) of the student.

Q3. Why is a dictionary keyed on roll number?

Roll numbers are unique, so each student's record can be reached directly.

Q4. What does count() do here?

marks.count('P') counts how many times 'P' occurs in the list of marks.

Q5. How is invalid input handled while marking?

A while loop keeps asking until the code is one of P, A or L.

10

Password Strength Checker & Generator

PYTHONString methods (isupperislowerisdigitisalnum)random module
๐Ÿ“ 122 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 84 output lines๐Ÿ“„ 25+ page report

Rates a password out of 5 using length, case, digit and symbol rules, gives improvement tips and generates a random strong password of any length.

โœจ Features
  • Password strength meter with a score out of 10 and a coloured-style bar
  • Checks length, upper / lower case, digits, symbols, repeated characters and common passwords
  • Strong random password generator with chosen length and symbol option
  • Memorable passphrase generator (word-word-number)
  • Estimated time to crack by brute force
  • Password policy check for school accounts and safety tips
โ˜ฐ Main menu
1Check StrengthScores a password and gives tips
2Generate PasswordRandom password of chosen length
3Generate PassphraseEasy-to-remember strong passphrase
4Crack-time EstimateApproximate brute-force time for a password
5Policy CheckChecks school password policy rules
6Bulk CheckStrength of many passwords together
7Safety TipsCyber-safety tips for passwords
0ExitEnds the program
๐ŸŽฏ Objectives
  • Apply string methods like isupper(), isdigit(), isalnum()
  • Return multiple values from a function
  • Generate random strings with random.choice() and shuffle()
๐Ÿ“š Data dictionary
NameTypePurpose
COMMONsetVery common weak passwords (123456, password ...)
LOWER / UPPER / DIGITS / SYMBOLSstrCharacter groups used for checking and generating
WORDSlistSimple words used in passphrases
scoreintStrength score from 0 to 10
Why it matters: Teaches cyber-safety (Society, Law & Ethics) through string processing and the random module.
# =====================================================================
#   PASSWORD STRENGTH CHECKER & GENERATOR
#   Concepts : strings & string methods, sets, lists, functions,
#              random module, loops
# =====================================================================
import random

LOWER = "abcdefghijklmnopqrstuvwxyz"
UPPER = LOWER.upper()
DIGITS = "0123456789"
SYMBOLS = "@#$%&*!?_-"
COMMON = {"123456", "password", "12345678", "qwerty", "111111", "abc123", "india123", "iloveyou", "admin", "welcome"}
WORDS = ["Tiger", "River", "Mango", "Rocket", "Pixel", "Lotus", "Comet", "Ocean", "Falcon", "Maple"]


def check(pw):
    """Returns score (0-10), level and tips."""
    score, tips = 0, []
    if pw.lower() in COMMON:
        return 0, "VERY WEAK (common password)", ["Never use common passwords."]
    score += 3 if len(pw) >= 12 else 2 if len(pw) >= 8 else 0
    if len(pw) < 8:
        tips.append("Use at least 8 (better 12) characters")
    for group, name in ((LOWER, "lowercase letter"), (UPPER, "uppercase letter"), (DIGITS, "digit"), (SYMBOLS, "symbol")):
        if any(c in group for c in pw):
            score += 2 if group == SYMBOLS else 1.5 if group == UPPER else 1
        else:
            tips.append("Add at least one " + name)
    if any(pw[i] == pw[i + 1] == pw[i + 2] for i in range(len(pw) - 2)):
        score -= 2
        tips.append("Avoid repeating the same character")
    score = max(0, min(10, round(score + (1 if len(set(pw)) >= 8 else 0))))
    level = ("VERY STRONG" if score >= 9 else "STRONG" if score >= 7 else "MEDIUM" if score >= 5 else "WEAK")
    return score, level, tips


def show_check(pw):
    """Prints the result of check()."""
    s, level, tips = check(pw)
    print(f"{pw:<16} [{'#' * s}{'.' * (10 - s)}] {s}/10  {level}")
    for t in tips:
        print("   Tip:", t)


def generate(n, symbols=True):
    """Random password with every character group."""
    n = max(n, 8)
    pools = [LOWER, UPPER, DIGITS] + ([SYMBOLS] if symbols else [])
    pw = [random.choice(p) for p in pools]
    allc = "".join(pools)
    while len(pw) < n:
        pw.append(random.choice(allc))
    random.shuffle(pw)
    return "".join(pw)


def passphrase():
    """Word-Word-Number passphrase."""
    a, b = random.sample(WORDS, 2)
    return f"{a}-{b}-{random.randint(10, 99)}{random.choice('@#$!')}"


def crack_time(pw):
    """Approximate brute-force time."""
    size = sum(len(g) for g in (LOWER, UPPER, DIGITS, SYMBOLS) if any(c in g for c in pw))
    secs = size ** len(pw) / 1e10
    for unit, n in (("years", 31536000), ("days", 86400), ("hours", 3600), ("minutes", 60)):
        if secs >= n:
            return f"about {secs / n:,.1f} {unit}"
    return "less than a second" if secs < 1 else f"about {secs:.0f} seconds"


def policy(pw):
    """School account policy."""
    rules = [(len(pw) >= 8, "At least 8 characters"), (any(c.isupper() for c in pw), "One capital letter"),
             (any(c.isdigit() for c in pw), "One digit"), (any(c in SYMBOLS for c in pw), "One symbol"),
             (" " not in pw, "No spaces")]
    for ok, r in rules:
        print(("  [PASS] " if ok else "  [FAIL] ") + r)
    print("Policy result:", "ACCEPTED" if all(ok for ok, _ in rules) else "REJECTED")


print("=" * 56)
print("PASSWORD STRENGTH CHECKER & GENERATOR".center(56))
print("=" * 56)
while True:
    print("\n1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "1":
        show_check(input("Enter password: "))
    elif ch == "2":
        try:
            n = int(input("Length (min 8): "))
        except ValueError:
            n = 12
        sym = input("Include symbols? (Y/N): ").strip().upper() == "Y"
        pw = generate(n, sym)
        print("Generated:", pw)
        show_check(pw)
    elif ch == "3":
        p = passphrase()
        print("Passphrase:", p)
        show_check(p)
    elif ch == "4":
        pw = input("Password: ")
        print("Time to crack by brute force:", crack_time(pw))
    elif ch == "5":
        policy(input("Password: "))
    elif ch == "6":
        for pw in input("Passwords (comma separated): ").split(","):
            show_check(pw.strip())
    elif ch == "7":
        for t in ("Use a different password for every account.", "Never share OTP / password with anyone.",
                  "Enable two-factor authentication.", "Change passwords if a site is hacked.",
                  "Do not save passwords on shared computers."):
            print(" *", t)
    elif ch == "0":
        print("Stay safe online!")
        break
    else:
        print("Invalid choice")

        
  1. Start
  2. Display menu and read choice
  3. Choice is Check? → No: generate / estimate / policy / tips
  4. Read password
  5. Score length, cases, digits, symbols; penalise repeats and common words
  6. Show level, bar and tips
  7. Generate random password / passphrase when chosen
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1'password'Common password - VERY WEAKPASS
2'Kv@2026School'Score 10/10 - VERY STRONGPASS
3'aaaaaaa1'Repeated characters penaltyPASS
4Generate length 1212-character password with all groupsPASS
5Generate length 4Length raised to the minimum 8PASS
6PassphraseWord-Word-Number patternPASS
7Crack time of 'abc123'Seconds or lessPASS
8Policy check 'kv2026'Lists the rules that failPASS
โš  Limitations
  • Crack-time estimate is approximate (assumes 10 billion guesses per second)
  • Common-password list is small
  • Generated passwords are not stored
  • English words only
๐Ÿš€ Future scope
  • Check against a large leaked-password list file
  • Encrypted password vault using a master password
  • GUI with a live strength bar
  • Two-factor authentication demo

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): random - random number functions are loaded.
  2. Global variables / constants are created: LOWER, UPPER, DIGITS, SYMBOLS, COMMON, WORDS.
  3. 6 functions are defined (lines 16โ€“80) - Python stores them but does NOT run them yet.
  4. Main program starts at line 83: print("=" * 56) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
check(pw)16โ€“34Returns score (0-10), level and tips.show_check()
show_check(pw)37โ€“42Prints the result of check().main program
generate(n, symbols)45โ€“54Random password with every character group.main program
passphrase()57โ€“60Word-Word-Number passphrase.main program
crack_time(pw)63โ€“70Approximate brute-force time.main program
policy(pw)73โ€“80School account policy.main program
โ‘ข Main program - line by line
LineCodeWhat it does
83
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
84
print("PASSWORD STRENGTH CHECKER & GENERATOR".center(56))
๐Ÿ–ฅ๏ธ Output Displays the value of "PASSWORD STRENGTH CHECKER & GENERATOR".centeโ€ฆ on the screen
85
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
86
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
87
print("\n1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Check 2.Generate 3.Passphrase 4โ€ฆ" on the screen
88
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
89
if ch == "1":
๐Ÿ”€ Decision CHECKS whether ch is equal to "1". If True, the indented lines below run; otherwise Python jumps to the elif/else part
90
show_check(input("Enter password: "))
โŒจ๏ธ Input Calls our own function show_check(input("Enter passwoโ€ฆ) - prints the result of check()
91
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
92
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
93
n = int(input("Length (min 8): "))
โŒจ๏ธ Input Shows "Length (min 8): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
94
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
95
n = 12
๐Ÿงฎ Store / Calculate Stores the number 12 in variable n
96
sym = input("Include symbols? (Y/N): ").strip().upper() == "Y"
โŒจ๏ธ Input Stores True/False for input("Include symbols? (Y/N): ").strip().uppโ€ฆ is equal to "Y" in variable sym
97
pw = generate(n, sym)
๐Ÿงฎ Store / Calculate Calls our own function generate(n, sym) - random password with every character group; the result is stored in variable pw
98
print("Generated:", pw)
๐Ÿ–ฅ๏ธ Output Displays the text "Generated:", then the value of pw on the screen
99
show_check(pw)
๐Ÿงฎ Store / Calculate Calls our own function show_check(pw) - prints the result of check()
100
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
101
p = passphrase()
๐Ÿงฎ Store / Calculate Calls our own function passphrase() - word-word-number passphrase; the result is stored in variable p
102
print("Passphrase:", p)
๐Ÿ–ฅ๏ธ Output Displays the text "Passphrase:", then the value of p on the screen
103
show_check(p)
๐Ÿงฎ Store / Calculate Calls our own function show_check(p) - prints the result of check()
104
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
105
pw = input("Password: ")
โŒจ๏ธ Input Shows the message "Password: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable pw
106
print("Time to crack by brute force:", crack_time(pw))
๐Ÿ–ฅ๏ธ Output Displays the text "Time to crack by brute force:", then the value of crack_time(pw) on the screen
107
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
108
policy(input("Password: "))
โŒจ๏ธ Input Calls our own function policy(input("Password: ")) - school account policy
109
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
110
for pw in input("Passwords (comma separated): ").split(","):
๐Ÿ” Loop LOOP: takes each item of input("Passwords (comma separated): ").split(โ€ฆ one-by-one into pw and runs the indented block for it
111
show_check(pw.strip())
๐Ÿงฎ Store / Calculate Calls our own function show_check(pw.strip()) - prints the result of check()
112
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
113
for t in ("Use a different password for every account.", "Never share OTP / password with anyone.",
          "Enable two-factor authentication.", "Change paโ€ฆ
๐Ÿ” Loop LOOP: takes each item of ("Use a different password for every account.โ€ฆ one-by-one into t and runs the indented block for it
116
print(" *", t)
๐Ÿ–ฅ๏ธ Output Displays the text "*", then the value of t on the screen
117
elif ch == "0":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "0"
118
print("Stay safe online!")
๐Ÿ–ฅ๏ธ Output Displays the text "Stay safe online!" on the screen
119
break
๐Ÿ” Loop BREAK - leaves the loop immediately
120
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
121
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: PASSWORD STRENGTH CHECKER & GENERATOR (+1 more lines)
  2. You type 1 at Enter choice:
  3. You type password at Enter password:
    runs: show_check() โ†’ check()
    shows: password [..........] 0/10 VERY WEAK (common password) (+2 more lines)
  4. You type 1 at Enter choice:
  5. You type Kv@2026School at Enter password:
    runs: show_check() โ†’ check()
    shows: Kv@2026School [##########] 10/10 VERY STRONG (+1 more lines)
  6. You type 1 at Enter choice:
  7. You type aaaaaaa1 at Enter password:
    runs: show_check() โ†’ check()
    shows: aaaaaaa1 [##........] 2/10 WEAK (+4 more lines)
  8. You type 2 at Enter choice:
  9. You type 12 at Length (min 8):
  10. You type Y at Include symbols? (Y/N):
    runs: generate() โ†’ show_check() โ†’ check()
    shows: Generated: 1_8C_E-n4K@d (+2 more lines)
  11. You type 2 at Enter choice:
  12. You type 4 at Length (min 8):
  13. You type N at Include symbols? (Y/N):
    runs: generate() โ†’ show_check() โ†’ check()
    shows: Generated: zKw3vqw7 (+3 more lines)
  14. You type 3 at Enter choice:
    runs: passphrase() โ†’ show_check() โ†’ check()
    shows: Passphrase: Pixel-Ocean-28$ (+2 more lines)
  15. You type 4 at Enter choice:
  16. You type abc123 at Password:
    runs: crack_time()
    shows: Time to crack by brute force: less than a second (+1 more lines)
  17. You type 4 at Enter choice:
  18. You type Kv@2026School at Password:
    runs: crack_time()
    shows: Time to crack by brute force: about 4,431,143.8 years (+1 more lines)
  19. You type 5 at Enter choice:
  20. You type kv2026 at Password:
    runs: policy()
    shows: [FAIL] At least 8 characters (+6 more lines)
  21. You type 6 at Enter choice:
  22. You type india123,Delhi@2026,qwerty,T!ger_Run9 at Passwords (comma separated):
    runs: show_check() โ†’ check() โ†’ show_check() โ†’ check() โ†’ show_check() โ†’ check() โ†’ show_check() โ†’ check()
    shows: india123 [..........] 0/10 VERY WEAK (common password) (+6 more lines)
  23. You type 7 at Enter choice:
    shows: * Use a different password for every account. (+5 more lines)
  24. You type 0 at Enter choice:
    shows: Stay safe online!
โ‘ค Inside each function - line by line
check() - lines 16โ€“34
LineCodeWhat it does
16
def check(pw):
๐Ÿงฉ Function DEFINES a function check(pw). Python only remembers it here - its body runs later, each time check() is called.
18
score, tips = 0, []
๐Ÿงฎ Store / Calculate Stores 0, [] into score, tips respectively
19
if pw.lower() in COMMON:
๐Ÿ”€ Decision CHECKS whether pw.lower() is present in COMMON. If True, the indented lines below run; otherwise they are skipped
20
return 0, "VERY WEAK (common password)", ["Never use common passwords."]
๐Ÿงฉ Function Sends back (returns) the tuple 0, "VERY WEAK (common password)", ["Never useโ€ฆ to the line that called the function
21
score += 3 if len(pw) >= 12 else 2 if len(pw) >= 8 else 0
๐Ÿงฎ Store / Calculate Adds 3 if len(pw) >= 12 else 2 if len(pw) >= 8 elsโ€ฆ to score (same as score = score + 3 if len(pw) >= 12 else โ€ฆ)
22
if len(pw) < 8:
๐Ÿ”€ Decision CHECKS whether len(pw) is less than 8. If True, the indented lines below run; otherwise they are skipped
23
tips.append("Use at least 8 (better 12) characters")
๐Ÿงฎ Store / Calculate Adds "Use at least 8 (better 12) characters" at the end of list tips
24
for group, name in ((LOWER, "lowercase letter"), (UPPER, "uppercase letter"), (DIGITS, "digit"), (SYMBOLS, "symbol")):
๐Ÿ” Loop LOOP: takes each item of ((LOWER, "lowercase letter"), (UPPER, "uppercโ€ฆ one-by-one into group, name and runs the indented block for it
25
if any(c in group for c in pw):
๐Ÿ”€ Decision CHECKS whether any(c in group for c in pw) is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
26
score += 2 if group == SYMBOLS else 1.5 if group == UPPER else 1
๐Ÿงฎ Store / Calculate Adds 2 if group == SYMBOLS else 1.5 if group == UPโ€ฆ to score (same as score = score + 2 if group == SYMBOLS elโ€ฆ)
27
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
28
tips.append("Add at least one " + name)
๐Ÿงฎ Store / Calculate Adds "Add at least one " + name at the end of list tips
29
if any(pw[i] == pw[i + 1] == pw[i + 2] for i in range(len(pw) - 2)):
๐Ÿ”€ Decision CHECKS whether any(pw[i] == pw[i + 1] == pw[i + 2] for i in โ€ฆ is True. If True, the indented lines below run; otherwise they are skipped
30
score -= 2
๐Ÿงฎ Store / Calculate Subtracts 2 from score (same as score = score - 2)
31
tips.append("Avoid repeating the same character")
๐Ÿงฎ Store / Calculate Adds "Avoid repeating the same character" at the end of list tips
32
score = max(0, min(10, round(score + (1 if len(set(pw)) >= 8 else 0))))
๐Ÿงฎ Store / Calculate Finds the largest value among 0, min(10, round(score + (1 if len(set(pw)) >= 8โ€ฆ; the result is stored in variable score
33
level = ("VERY STRONG" if score >= 9 else "STRONG" if score >= 7 else "MEDIUM" if score >= 5 else "WEAK")
๐Ÿงฎ Store / Calculate Stores either "VERY STRONG" or "STRONG" if score >= 7 else "MEDIUM" if scoreโ€ฆ depending on score >= 9 in variable level
34
return score, level, tips
๐Ÿงฉ Function Sends back (returns) the tuple score, level, tips to the line that called the function
show_check() - lines 37โ€“42
LineCodeWhat it does
37
def show_check(pw):
๐Ÿงฉ Function DEFINES a function show_check(pw). Python only remembers it here - its body runs later, each time show_check() is called.
39
s, level, tips = check(pw)
๐Ÿงฎ Store / Calculate Calls our own function check(pw) - returns score (0-10), level and tips; the result is stored in variables s, level, tips
40
print(f"{pw:<16} [{'#' * s}{'.' * (10 - s)}] {s}/10  {level}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{pw:<16} [{'#' * s}{'.' * (10 - s)}] {s}/10โ€ฆ with the values filled into { } on the screen
41
for t in tips:
๐Ÿ” Loop LOOP: takes each item of tips one-by-one into t and runs the indented block for it
42
print("   Tip:", t)
๐Ÿ–ฅ๏ธ Output Displays the text "Tip:", then the value of t on the screen
generate() - lines 45โ€“54
LineCodeWhat it does
45
def generate(n, symbols=True):
๐Ÿงฉ Function DEFINES a function generate(n, symbols). Python only remembers it here - its body runs later, each time generate() is called.
47
n = max(n, 8)
๐Ÿงฎ Store / Calculate Finds the largest value among n, 8; the result is stored in variable n
48
pools = [LOWER, UPPER, DIGITS] + ([SYMBOLS] if symbols else [])
๐Ÿงฎ Store / Calculate Stores the value of [LOWER, UPPER, DIGITS] + ([SYMBOLS] if symbolโ€ฆ (calculated using +) in variable pools
49
pw = [random.choice(p) for p in pools]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [random.choice(p) for p in pools] in variable pw
50
allc = "".join(pools)
๐Ÿงฎ Store / Calculate Joins all items of pools into one string, putting "" between them; the result is stored in variable allc
51
while len(pw) < n:
๐Ÿ” Loop LOOP: repeats the indented block as long as len(pw) is less than n; checks the condition before every round
52
pw.append(random.choice(allc))
๐Ÿงฎ Store / Calculate Adds random.choice(allc) at the end of list pw
53
random.shuffle(pw)
๐Ÿงฎ Store / Calculate Shuffles (mixes) the items of pw randomly
54
return "".join(pw)
๐Ÿงฉ Function Sends back (returns) the result of: joins all items of pw into one string, putting "" between them to the line that called the function
passphrase() - lines 57โ€“60
LineCodeWhat it does
57
def passphrase():
๐Ÿงฉ Function DEFINES a function passphrase(). Python only remembers it here - its body runs later, each time passphrase() is called.
59
a, b = random.sample(WORDS, 2)
๐Ÿงฎ Store / Calculate Picks 2 random items from WORDS; the result is stored in variables a, b
60
return f"{a}-{b}-{random.randint(10, 99)}{random.choice('@#$!')}"
๐Ÿงฉ Function Sends back (returns) the f-string f"{a}-{b}-{random.randint(10, 99)}{random.choโ€ฆ (values inside { } are filled in) to the line that called the function
crack_time() - lines 63โ€“70
LineCodeWhat it does
63
def crack_time(pw):
๐Ÿงฉ Function DEFINES a function crack_time(pw). Python only remembers it here - its body runs later, each time crack_time() is called.
65
size = sum(len(g) for g in (LOWER, UPPER, DIGITS, SYMBOLS) if any(c in g for c in pw))
๐Ÿงฎ Store / Calculate Adds up all the values in (len(g) for g in (LOWER, UPPER, DIGITS, SYMBOโ€ฆ; the result is stored in variable size
66
secs = size ** len(pw) / 1e10
๐Ÿงฎ Store / Calculate Stores the value of size ** len(pw) / 1e10 (calculated using รท) in variable secs
67
for unit, n in (("years", 31536000), ("days", 86400), ("hours", 3600), ("minutes", 60)):
๐Ÿ” Loop LOOP: takes each item of (("years", 31536000), ("days", 86400), ("hourโ€ฆ one-by-one into unit, n and runs the indented block for it
68
if secs >= n:
๐Ÿ”€ Decision CHECKS whether secs is greater than or equal to n. If True, the indented lines below run; otherwise they are skipped
69
return f"about {secs / n:,.1f} {unit}"
๐Ÿงฉ Function Sends back (returns) the f-string f"about {secs / n:,.1f} {unit}" (values inside { } are filled in) to the line that called the function
70
return "less than a second" if secs < 1 else f"about {secs:.0f} seconds"
๐Ÿงฉ Function Sends back (returns) either "less than a second" or f"about {secs:.0f} seconds" depending on secs < 1 to the line that called the function
policy() - lines 73โ€“80
LineCodeWhat it does
73
def policy(pw):
๐Ÿงฉ Function DEFINES a function policy(pw). Python only remembers it here - its body runs later, each time policy() is called.
75
rules = [(len(pw) >= 8, "At least 8 characters"), (any(c.isupper() for c in pw), "One capital letter"),
         (any(c.isdigit() for c in pw), "One digit"),โ€ฆ
๐Ÿงฎ Store / Calculate Stores a list [(len(pw) >= 8, "At least 8 characters"), (anโ€ฆ in variable rules
78
for ok, r in rules:
๐Ÿ” Loop LOOP: takes each item of rules one-by-one into ok, r and runs the indented block for it
79
print(("  [PASS] " if ok else "  [FAIL] ") + r)
๐Ÿ–ฅ๏ธ Output Displays the value of (" [PASS] " if ok else " [FAIL] ") + r on the screen
80
print("Policy result:", "ACCEPTED" if all(ok for ok, _ in rules) else "REJECTED")
๐Ÿ–ฅ๏ธ Output Displays the text "Policy result:", then the value of "ACCEPTED" if all(ok for ok, _ in rules) elseโ€ฆ on the screen
Q1. Why should a password contain different types of characters?

Each extra character group increases the number of possible combinations, making brute-force guessing much slower.

Q2. How is the crack time estimated?

Combinations = (size of character set) ** length; dividing by guesses per second gives seconds needed in the worst case.

Q3. Which functions of the random module are used?

choice() picks a random character/word, shuffle() mixes the characters, randint() gives a random number.

Q4. How are repeated characters detected?

By checking if any character occurs three times in a row, e.g. pw[i] == pw[i+1] == pw[i+2].

Q5. Why should passwords not be shared even with friends?

Anyone with your password can misuse your account; this is part of cyber-safety and digital citizenship.

๐Ÿ“— Class XI Informatics Practices (065) โ€” 10 Projects 10 projects

01

Loan/EMI Comparison Calculator

PYTHONFunctionsmath formulasmenu-driven design
๐Ÿ“ 133 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 88 output lines๐Ÿ“„ 25+ page report

Compare EMIs for 2-3 different banks (different interest rates/tenures) using the EMI formula from Practical 9, and recommend the cheapest option.

โœจ Features
  • EMI calculator with the standard reducing-balance formula
  • Compares any number of banks and recommends the lowest total cost
  • Year-wise amortisation schedule: interest paid, principal paid and balance
  • Affordability check: EMI should be within 40 % of monthly income
  • Prepayment savings calculator
  • Maximum loan amount for a given EMI budget
โ˜ฐ Main menu
1Single EMIEMI, total interest and total payment of one loan
2Compare BanksEMI and total cost of several banks with best option
3Amortisation ScheduleYear-wise interest, principal and closing balance
4Affordability CheckIs the EMI within 40 % of income?
5Prepayment SavingInterest saved by a one-time part payment
6Loan EligibilityMaximum loan possible for an EMI you can pay
0ExitEnds the program
๐ŸŽฏ Objectives
  • Implement the EMI formula using a function
  • Store and compare results with a dictionary
  • Use min() with a key to find the best option
๐Ÿ“š Data dictionary
NameTypePurpose
emifloatMonthly instalment = P x r x (1+r)^n / ((1+r)^n - 1)
banksdictBank name -> (rate, years, emi, total)
rfloatMonthly interest rate = annual rate / 1200
nintNumber of monthly instalments = years x 12
Why it matters: A genuinely usable personal-finance tool for parents choosing a loan.
# =====================================================================
#   LOAN / EMI COMPARISON CALCULATOR
#   Concepts : arithmetic expressions, functions, dictionaries, loops,
#              formatted output, input validation
# =====================================================================


def read_num(msg):
    """Reads a positive number; returns None if invalid."""
    try:
        v = float(input(msg))
        return v if v >= 0 else None
    except ValueError:
        print("Enter a valid number.")
        return None


def calc_emi(p, rate, years):
    """EMI by the reducing-balance formula."""
    r, n = rate / 1200, int(years * 12)
    if r == 0:
        return p / n
    return p * r * (1 + r) ** n / ((1 + r) ** n - 1)


def single_emi():
    """EMI, interest and total of one loan."""
    p = read_num("Loan amount (Rs.): ")
    if p is None:
        return
    rate = read_num("Annual interest rate (%): ")
    years = read_num("Tenure (years): ")
    emi = calc_emi(p, rate, years)
    total = emi * years * 12
    print(f"Monthly EMI     : Rs. {emi:,.2f}")
    print(f"Total interest  : Rs. {total - p:,.2f}")
    print(f"Total payment   : Rs. {total:,.2f}")
    print(f"Interest share  : {(total - p) / total * 100:.1f}% of the total payment")


def compare_banks():
    """Compares several banks."""
    p = read_num("Loan amount (Rs.): ")
    k = int(read_num("How many banks? ") or 0)
    banks = {}
    for i in range(k):
        name = input(f"Bank {i + 1} name: ").strip()
        rate = read_num("  Rate (%)     : ")
        yrs = read_num("  Tenure (yrs) : ")
        emi = calc_emi(p, rate, yrs)
        banks[name] = (rate, yrs, emi, emi * yrs * 12)
    print(f"\n{'Bank':<8}{'Rate':>6}{'Years':>6}{'EMI':>12}{'Total cost':>14}")
    print("-" * 46)
    for b, (rt, y, e, t) in sorted(banks.items(), key=lambda x: x[1][3]):
        print(f"{b:<8}{rt:>6}{y:>6.0f}{e:>12,.2f}{t:>14,.2f}")
    best = min(banks, key=lambda b: banks[b][3])
    low_emi = min(banks, key=lambda b: banks[b][2])
    print("Lowest total cost :", best)
    print("Lowest monthly EMI:", low_emi, "(longer tenure may cost more)" if low_emi != best else "")


def schedule():
    """Year-wise amortisation schedule."""
    p = read_num("Loan amount (Rs.): ")
    rate = read_num("Rate (%): ")
    years = int(read_num("Tenure (years): "))
    emi, r, bal = calc_emi(p, rate, years), rate / 1200, p
    print(f"EMI Rs. {emi:,.2f}")
    print(f"{'Year':<6}{'Interest':>12}{'Principal':>12}{'Balance':>14}")
    for y in range(1, years + 1):
        yi = yp = 0
        for _ in range(12):
            interest = bal * r
            yi += interest
            yp += emi - interest
            bal -= emi - interest
        print(f"{y:<6}{yi:>12,.0f}{yp:>12,.0f}{max(bal, 0):>14,.0f}")


def affordability():
    """EMI should be at most 40 % of income."""
    inc = read_num("Monthly income (Rs.): ")
    emi = read_num("EMI (Rs.): ")
    share = emi / inc * 100
    print(f"EMI is {share:.1f}% of income.")
    print("AFFORDABLE" if share <= 40 else "NOT AFFORDABLE - reduce loan or increase tenure")


def prepayment():
    """Interest saved by a part payment."""
    p = read_num("Loan amount: ")
    rate = read_num("Rate (%): ")
    years = int(read_num("Tenure (years): "))
    after = int(read_num("Prepay after how many years: "))
    amt = read_num("Prepayment amount: ")
    emi, r = calc_emi(p, rate, years), rate / 1200
    bal, paid = p, 0
    for _ in range(after * 12):
        bal -= emi - bal * r
        paid += emi
    normal_total = emi * years * 12
    bal -= amt
    months = 0
    while bal > 0:
        bal -= emi - bal * r
        months += 1
    new_total = paid + amt + emi * months
    print(f"Loan closes {years * 12 - after * 12 - months} months earlier.")
    print(f"Interest saved: Rs. {normal_total - new_total:,.2f}")


def eligibility():
    """Maximum loan for an affordable EMI."""
    emi = read_num("EMI you can pay (Rs.): ")
    rate = read_num("Rate (%): ")
    years = read_num("Tenure (years): ")
    r, n = rate / 1200, years * 12
    p = emi * ((1 + r) ** n - 1) / (r * (1 + r) ** n)
    print(f"You are eligible for a loan of about Rs. {p:,.0f}")


menu = {"1": single_emi, "2": compare_banks, "3": schedule, "4": affordability, "5": prepayment, "6": eligibility}
print("=" * 50)
print("LOAN / EMI COMPARISON CALCULATOR".center(50))
print("=" * 50)
while True:
    print("\n1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Borrow wisely!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Compare? → No: run the selected calculator
  4. Read loan amount and number of banks
  5. Read bank name, rate and tenure for each bank
  6. EMI and total payment for every bank
  7. Best bank = minimum total payment
  8. Display comparison table and recommendation
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1P = 500000, 8.5 %, 5 yearsEMI Rs. 10258.27PASS
2Rate 0 %EMI = P / n (no interest)PASS
3Compare 3 banksLowest total cost recommendedPASS
4Schedule for 5 yearsBalance becomes 0 in year 5PASS
5Income 30000, EMI 10258Affordable (34.2 %)PASS
6Income 20000, EMI 10258Not affordable warningPASS
7Prepay 100000 after 2 yearsInterest saved shownPASS
8Amount 'abc''Enter a valid number'PASS
โš  Limitations
  • Assumes fixed interest rate for the whole tenure
  • Processing fees and insurance are not included
  • Prepayment assumes the same EMI and reduces tenure
  • Results are not saved
๐Ÿš€ Future scope
  • Plot balance vs time with Matplotlib
  • Floating-rate loans
  • Save comparisons to a CSV file
  • Web version using Flask

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. 8 functions are defined (lines 8โ€“119) - Python stores them but does NOT run them yet.
  2. Main program starts at line 122: menu = {"1": single_emi, "2": compare_banks, "3": schedule, "4": affor - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_num(msg)8โ€“15Reads a positive number; returns None if invalid.single_emi(), compare_banks(), schedule(), affordability()
calc_emi(p, rate, years)18โ€“23EMI by the reducing-balance formula.single_emi(), compare_banks(), schedule(), prepayment()
single_emi()26โ€“38EMI, interest and total of one loan.main program (menu)
compare_banks()41โ€“59Compares several banks.main program (menu)
schedule()62โ€“77Year-wise amortisation schedule.main program (menu)
affordability()80โ€“86EMI should be at most 40 % of income.main program (menu)
prepayment()89โ€“109Interest saved by a part payment.main program (menu)
eligibility()112โ€“119Maximum loan for an affordable EMI.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
122
menu = {"1": single_emi, "2": compare_banks, "3": schedule, "4": affordability, "5": prepayment, "6": eligibility}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": single_emi, "2": compare_banks, "3": scโ€ฆ in variable menu
123
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
124
print("LOAN / EMI COMPARISON CALCULATOR".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "LOAN / EMI COMPARISON CALCULATOR".center(50) on the screen
125
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
126
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
127
print("\n1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.EMI 2.Compare 3.Schedule 4.Affoโ€ฆ" on the screen
128
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
129
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
130
print("Borrow wisely!")
๐Ÿ–ฅ๏ธ Output Displays the text "Borrow wisely!" on the screen
131
break
๐Ÿ” Loop BREAK - leaves the loop immediately
132
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: LOAN / EMI COMPARISON CALCULATOR (+1 more lines)
  2. You type 1 at Enter choice:
    runs: single_emi() โ†’ read_num()
  3. You type 500000 at Loan amount (Rs.):
    runs: read_num()
  4. You type 8.5 at Annual interest rate (%):
    runs: read_num()
  5. You type 5 at Tenure (years):
    runs: calc_emi()
    shows: Monthly EMI : Rs. 10,258.27 (+4 more lines)
  6. You type 2 at Enter choice:
    runs: compare_banks() โ†’ read_num()
  7. You type 500000 at Loan amount (Rs.):
    runs: read_num()
  8. You type 3 at How many banks?
  9. You type SBI at Bank 1 name:
    runs: read_num()
  10. You type 8.5 at Rate (%) :
    runs: read_num()
  11. You type 5 at Tenure (yrs) :
    runs: calc_emi()
  12. You type HDFC at Bank 2 name:
    runs: read_num()
  13. You type 9.1 at Rate (%) :
    runs: read_num()
  14. You type 5 at Tenure (yrs) :
    runs: calc_emi()
  15. You type PNB at Bank 3 name:
    runs: read_num()
  16. You type 8.25 at Rate (%) :
    runs: read_num()
  17. You type 6 at Tenure (yrs) :
    runs: calc_emi()
    shows: Bank Rate Years EMI Total cost (+6 more lines)
  18. You type 3 at Enter choice:
    runs: schedule() โ†’ read_num()
  19. You type 500000 at Loan amount (Rs.):
    runs: read_num()
  20. You type 8.5 at Rate (%):
    runs: read_num()
  21. You type 5 at Tenure (years):
    runs: calc_emi()
    shows: EMI Rs. 10,258.27 (+7 more lines)
  22. You type 4 at Enter choice:
    runs: affordability() โ†’ read_num()
  23. You type 30000 at Monthly income (Rs.):
    runs: read_num()
  24. You type 10258.27 at EMI (Rs.):
    shows: EMI is 34.2% of income. (+2 more lines)
  25. You type 4 at Enter choice:
    runs: affordability() โ†’ read_num()
  26. You type 20000 at Monthly income (Rs.):
    runs: read_num()
  27. You type 10258.27 at EMI (Rs.):
    shows: EMI is 51.3% of income. (+2 more lines)
  28. You type 5 at Enter choice:
    runs: prepayment() โ†’ read_num()
  29. You type 500000 at Loan amount:
    runs: read_num()
  30. You type 8.5 at Rate (%):
    runs: read_num()
  31. You type 5 at Tenure (years):
    runs: read_num()
  32. You type 2 at Prepay after how many years:
    runs: read_num()
  33. You type 100000 at Prepayment amount:
    runs: calc_emi()
    shows: Loan closes 12 months earlier. (+2 more lines)
  34. You type 6 at Enter choice:
    runs: eligibility() โ†’ read_num()
  35. You type 12000 at EMI you can pay (Rs.):
    runs: read_num()
  36. You type 9 at Rate (%):
    runs: read_num()
  37. You type 5 at Tenure (years):
    shows: You are eligible for a loan of about Rs. 578,080 (+1 more lines)
  38. You type 1 at Enter choice:
    runs: single_emi() โ†’ read_num()
  39. You type abc at Loan amount (Rs.):
    shows: Enter a valid number. (+1 more lines)
  40. You type 0 at Enter choice:
    shows: Borrow wisely!
โ‘ค Inside each function - line by line
read_num() - lines 8โ€“15
LineCodeWhat it does
8
def read_num(msg):
๐Ÿงฉ Function DEFINES a function read_num(msg). Python only remembers it here - its body runs later, each time read_num() is called.
10
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
11
v = float(input(msg))
โŒจ๏ธ Input Shows msg, reads what the user types, and float() converts that text into a decimal number; the number is stored in variable v
12
return v if v >= 0 else None
๐Ÿงฉ Function Sends back (returns) either v or None depending on v >= 0 to the line that called the function
13
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
14
print("Enter a valid number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a valid number." on the screen
15
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
calc_emi() - lines 18โ€“23
LineCodeWhat it does
18
def calc_emi(p, rate, years):
๐Ÿงฉ Function DEFINES a function calc_emi(p, rate, years). Python only remembers it here - its body runs later, each time calc_emi() is called.
20
r, n = rate / 1200, int(years * 12)
๐Ÿงฎ Store / Calculate Stores rate / 1200, int(years * 12) into r, n respectively
21
if r == 0:
๐Ÿ”€ Decision CHECKS whether r is equal to 0. If True, the indented lines below run; otherwise they are skipped
22
return p / n
๐Ÿงฉ Function Sends back (returns) the value of p / n (calculated using รท) to the line that called the function
23
return p * r * (1 + r) ** n / ((1 + r) ** n - 1)
๐Ÿงฉ Function Sends back (returns) the value of p * r * (1 + r) ** n / ((1 + r) ** n - 1) (calculated using รท) to the line that called the function
single_emi() - lines 26โ€“38
LineCodeWhat it does
26
def single_emi():
๐Ÿงฉ Function DEFINES a function single_emi(). Python only remembers it here - its body runs later, each time single_emi() is called.
28
p = read_num("Loan amount (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Loan amount (Rs.):โ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable p
29
if p is None:
๐Ÿ”€ Decision CHECKS whether p is None. If True, the indented lines below run; otherwise they are skipped
30
return
๐Ÿงฉ Function Ends the function and goes back to the caller
31
rate = read_num("Annual interest rate (%): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Annual interest raโ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable rate
32
years = read_num("Tenure (years): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Tenure (years): ") - reads a positive number; returns none if invalid; the result is stored in variable years
33
emi = calc_emi(p, rate, years)
๐Ÿงฎ Store / Calculate Calls our own function calc_emi(p, rate, years) - emi by the reducing-balance formula; the result is stored in variable emi
34
total = emi * years * 12
๐Ÿงฎ Store / Calculate Stores the value of emi * years * 12 (calculated using ร—) in variable total
35
print(f"Monthly EMI     : Rs. {emi:,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Monthly EMI : Rs. {emi:,.2f}" with the values filled into { } on the screen
36
print(f"Total interest  : Rs. {total - p:,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Total interest : Rs. {total - p:,.2f}" with the values filled into { } on the screen
37
print(f"Total payment   : Rs. {total:,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Total payment : Rs. {total:,.2f}" with the values filled into { } on the screen
38
print(f"Interest share  : {(total - p) / total * 100:.1f}% of the total payment")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Interest share : {(total - p) / total * 100โ€ฆ with the values filled into { } on the screen
compare_banks() - lines 41โ€“59
LineCodeWhat it does
41
def compare_banks():
๐Ÿงฉ Function DEFINES a function compare_banks(). Python only remembers it here - its body runs later, each time compare_banks() is called.
43
p = read_num("Loan amount (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Loan amount (Rs.):โ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable p
44
k = int(read_num("How many banks? ") or 0)
๐Ÿงฎ Store / Calculate Converts read_num("How many banks? ") or 0 into a whole number (int); the result is stored in variable k
45
banks = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable banks
46
for i in range(k):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to k - 1; for each number, i takes that value and the indented block runs once
47
name = input(f"Bank {i + 1} name: ").strip()
โŒจ๏ธ Input Shows f"Bank {i + 1} name: ", reads the typed text, removes extra spaces (strip) and stores it in variable name
48
rate = read_num("  Rate (%)     : ")
๐Ÿงฎ Store / Calculate Calls our own function read_num(" Rate (%) : ") - reads a positive number; returns none if invalid; the result is stored in variable rate
49
yrs = read_num("  Tenure (yrs) : ")
๐Ÿงฎ Store / Calculate Calls our own function read_num(" Tenure (yrs) : ") - reads a positive number; returns none if invalid; the result is stored in variable yrs
50
emi = calc_emi(p, rate, yrs)
๐Ÿงฎ Store / Calculate Calls our own function calc_emi(p, rate, yrs) - emi by the reducing-balance formula; the result is stored in variable emi
51
banks[name] = (rate, yrs, emi, emi * yrs * 12)
๐Ÿงฎ Store / Calculate Puts the tuple (rate, yrs, emi, emi * yrs * 12) into banks[name] (item name of banks)
52
print(f"\n{'Bank':<8}{'Rate':>6}{'Years':>6}{'EMI':>12}{'Total cost':>14}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\n{'Bank':<8}{'Rate':>6}{'Years':>6}{'EMI':โ€ฆ with the values filled into { } on the screen
53
print("-" * 46)
๐Ÿ–ฅ๏ธ Output Displays a line of 46 "-" signs on the screen
54
for b, (rt, y, e, t) in sorted(banks.items(), key=lambda x: x[1][3]):
๐Ÿ” Loop LOOP: takes each item of sorted(banks.items(), key=lambda x: x[1][3]) one-by-one into b, (rt, y, e, t) and runs the indented block for it
55
print(f"{b:<8}{rt:>6}{y:>6.0f}{e:>12,.2f}{t:>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{b:<8}{rt:>6}{y:>6.0f}{e:>12,.2f}{t:>14,.2fโ€ฆ with the values filled into { } on the screen
56
best = min(banks, key=lambda b: banks[b][3])
๐Ÿงฎ Store / Calculate Finds the smallest value among banks; the result is stored in variable best
57
low_emi = min(banks, key=lambda b: banks[b][2])
๐Ÿงฎ Store / Calculate Finds the smallest value among banks; the result is stored in variable low_emi
58
print("Lowest total cost :", best)
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest total cost :", then the value of best on the screen
59
print("Lowest monthly EMI:", low_emi, "(longer tenure may cost more)" if low_emi != best else "")
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest monthly EMI:", then the value of low_emi, then the value of "(longer tenure may cost more)" if low_emi !=โ€ฆ on the screen
schedule() - lines 62โ€“77
LineCodeWhat it does
62
def schedule():
๐Ÿงฉ Function DEFINES a function schedule(). Python only remembers it here - its body runs later, each time schedule() is called.
64
p = read_num("Loan amount (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Loan amount (Rs.):โ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable p
65
rate = read_num("Rate (%): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Rate (%): ") - reads a positive number; returns none if invalid; the result is stored in variable rate
66
years = int(read_num("Tenure (years): "))
๐Ÿงฎ Store / Calculate Converts read_num("Tenure (years): ") into a whole number (int); the result is stored in variable years
67
emi, r, bal = calc_emi(p, rate, years), rate / 1200, p
๐Ÿงฎ Store / Calculate Stores calc_emi(p, rate, years), rate / 1200, p into emi, r, bal respectively
68
print(f"EMI Rs. {emi:,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"EMI Rs. {emi:,.2f}" with the values filled into { } on the screen
69
print(f"{'Year':<6}{'Interest':>12}{'Principal':>12}{'Balance':>14}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Year':<6}{'Interest':>12}{'Principal':>12โ€ฆ with the values filled into { } on the screen
70
for y in range(1, years + 1):
๐Ÿ” Loop LOOP: gives the numbers from 1 up to years + 1 - 1; for each number, y takes that value and the indented block runs once
71
yi = yp = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable yi
72
for _ in range(12):
๐Ÿ” Loop LOOP: gives the numbers 0 to 11 (12 numbers); for each number, _ takes that value and the indented block runs once
73
interest = bal * r
๐Ÿงฎ Store / Calculate Stores the value of bal * r (calculated using ร—) in variable interest
74
yi += interest
๐Ÿงฎ Store / Calculate Adds interest to yi (same as yi = yi + interest)
75
yp += emi - interest
๐Ÿงฎ Store / Calculate Adds emi - interest to yp (same as yp = yp + emi - interest)
76
bal -= emi - interest
๐Ÿงฎ Store / Calculate Subtracts emi - interest from bal (same as bal = bal - emi - interest)
77
print(f"{y:<6}{yi:>12,.0f}{yp:>12,.0f}{max(bal, 0):>14,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{y:<6}{yi:>12,.0f}{yp:>12,.0f}{max(bal, 0):โ€ฆ with the values filled into { } on the screen
affordability() - lines 80โ€“86
LineCodeWhat it does
80
def affordability():
๐Ÿงฉ Function DEFINES a function affordability(). Python only remembers it here - its body runs later, each time affordability() is called.
82
inc = read_num("Monthly income (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Monthly income (Rsโ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable inc
83
emi = read_num("EMI (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("EMI (Rs.): ") - reads a positive number; returns none if invalid; the result is stored in variable emi
84
share = emi / inc * 100
๐Ÿงฎ Store / Calculate Stores the value of emi / inc * 100 (calculated using ร—) in variable share
85
print(f"EMI is {share:.1f}% of income.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"EMI is {share:.1f}% of income." with the values filled into { } on the screen
86
print("AFFORDABLE" if share <= 40 else "NOT AFFORDABLE - reduce loan or increase tenure")
๐Ÿ–ฅ๏ธ Output Displays the value of "AFFORDABLE" if share <= 40 else "NOT AFFORDAโ€ฆ on the screen
prepayment() - lines 89โ€“109
LineCodeWhat it does
89
def prepayment():
๐Ÿงฉ Function DEFINES a function prepayment(). Python only remembers it here - its body runs later, each time prepayment() is called.
91
p = read_num("Loan amount: ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Loan amount: ") - reads a positive number; returns none if invalid; the result is stored in variable p
92
rate = read_num("Rate (%): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Rate (%): ") - reads a positive number; returns none if invalid; the result is stored in variable rate
93
years = int(read_num("Tenure (years): "))
๐Ÿงฎ Store / Calculate Converts read_num("Tenure (years): ") into a whole number (int); the result is stored in variable years
94
after = int(read_num("Prepay after how many years: "))
๐Ÿงฎ Store / Calculate Converts read_num("Prepay after how many years: ") into a whole number (int); the result is stored in variable after
95
amt = read_num("Prepayment amount: ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Prepayment amount:โ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable amt
96
emi, r = calc_emi(p, rate, years), rate / 1200
๐Ÿงฎ Store / Calculate Stores calc_emi(p, rate, years), rate / 1200 into emi, r respectively
97
bal, paid = p, 0
๐Ÿงฎ Store / Calculate Stores p, 0 into bal, paid respectively
98
for _ in range(after * 12):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to after * 12 - 1; for each number, _ takes that value and the indented block runs once
99
bal -= emi - bal * r
๐Ÿงฎ Store / Calculate Subtracts emi - bal * r from bal (same as bal = bal - emi - bal * r)
100
paid += emi
๐Ÿงฎ Store / Calculate Adds emi to paid (same as paid = paid + emi)
101
normal_total = emi * years * 12
๐Ÿงฎ Store / Calculate Stores the value of emi * years * 12 (calculated using ร—) in variable normal_total
102
bal -= amt
๐Ÿงฎ Store / Calculate Subtracts amt from bal (same as bal = bal - amt)
103
months = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable months
104
while bal > 0:
๐Ÿ” Loop LOOP: repeats the indented block as long as bal is greater than 0; checks the condition before every round
105
bal -= emi - bal * r
๐Ÿงฎ Store / Calculate Subtracts emi - bal * r from bal (same as bal = bal - emi - bal * r)
106
months += 1
๐Ÿงฎ Store / Calculate Adds 1 to months (same as months = months + 1)
107
new_total = paid + amt + emi * months
๐Ÿงฎ Store / Calculate Stores the value of paid + amt + emi * months (calculated using +) in variable new_total
108
print(f"Loan closes {years * 12 - after * 12 - months} months earlier.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Loan closes {years * 12 - after * 12 - montโ€ฆ with the values filled into { } on the screen
109
print(f"Interest saved: Rs. {normal_total - new_total:,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Interest saved: Rs. {normal_total - new_totโ€ฆ with the values filled into { } on the screen
eligibility() - lines 112โ€“119
LineCodeWhat it does
112
def eligibility():
๐Ÿงฉ Function DEFINES a function eligibility(). Python only remembers it here - its body runs later, each time eligibility() is called.
114
emi = read_num("EMI you can pay (Rs.): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("EMI you can pay (Rโ€ฆ) - reads a positive number; returns none if invalid; the result is stored in variable emi
115
rate = read_num("Rate (%): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Rate (%): ") - reads a positive number; returns none if invalid; the result is stored in variable rate
116
years = read_num("Tenure (years): ")
๐Ÿงฎ Store / Calculate Calls our own function read_num("Tenure (years): ") - reads a positive number; returns none if invalid; the result is stored in variable years
117
r, n = rate / 1200, years * 12
๐Ÿงฎ Store / Calculate Stores rate / 1200, years * 12 into r, n respectively
118
p = emi * ((1 + r) ** n - 1) / (r * (1 + r) ** n)
๐Ÿงฎ Store / Calculate Stores the value of emi * ((1 + r) ** n - 1) / (r * (1 + r) ** n) (calculated using รท) in variable p
119
print(f"You are eligible for a loan of about Rs. {p:,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"You are eligible for a loan of about Rs. {pโ€ฆ with the values filled into { } on the screen
Q1. Write the EMI formula.

EMI = P x r x (1 + r)^n / ((1 + r)^n - 1) where r is the monthly rate (annual % / 1200) and n the number of months.

Q2. How is the total interest found?

Total interest = EMI x number of months - principal.

Q3. How does the program pick the best bank?

min(banks, key=lambda b: banks[b][3]) selects the bank with the smallest total payment.

Q4. What is an amortisation schedule?

A table showing how each year's payments are split into interest and principal and how the balance reduces.

Q5. Why is a special case needed for 0 % rate?

The formula divides by ((1+r)^n - 1) which becomes 0 when r = 0, so EMI = P / n is used instead.

02

Shop Billing & GST Calculator

PYTHONDictionariesloopstax computation (Practical 10)
๐Ÿ“ 132 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 135 output lines๐Ÿ“„ 25+ page report

Enter item name, price, quantity and GST slab; generate an itemised bill with subtotal, GST amount, and grand total โ€” like a local kirana-store billing counter.

โœจ Features
  • Product catalogue with item code, name, price and GST slab (0, 5, 12, 18, 28 %)
  • Cart: add items by code, change quantity, remove item
  • Tax invoice with CGST + SGST split, discount and round-off
  • Customer details and invoice number
  • Day's sales summary: number of bills, sales and tax collected
  • Low-stock alert after every sale
โ˜ฐ Main menu
1Show CatalogueItems with price, GST and stock
2Add to CartAdds an item by code and quantity (checks stock)
3View CartItems in the current cart
4Remove from CartRemoves an item from the cart
5Generate InvoicePrints the GST invoice and updates stock
6Sales SummaryBills, sales and tax of the day
7Low StockItems with stock below 5
0ExitCloses the shop
๐ŸŽฏ Objectives
  • Use lists of tuples to store bill items
  • Apply percentage and tax calculations
  • Format tabular output using f-strings
๐Ÿ“š Data dictionary
NameTypePurpose
cataloguedictCode -> [name, price, gst %, stock]
cartdictCode -> quantity in the current bill
saleslist of tuple(invoice no, customer, amount, gst) of each bill
DISCOUNT_LIMITintBills above Rs. 2000 get 5 % discount
Why it matters: Directly usable by a small shop owner in the community โ€” strong 'real world' value.
# =====================================================================
#   SHOP BILLING & GST CALCULATOR
#   Concepts : dictionaries, lists, tuples, loops, conditions,
#              arithmetic, formatted output
# =====================================================================

catalogue = {101: ["Notebook (pack of 6)", 240.0, 12, 30], 102: ["Geometry Box", 180.0, 18, 12],
             103: ["Ball Pen (box)", 120.0, 18, 6], 104: ["School Bag", 1450.0, 18, 8],
             105: ["Water Bottle", 350.0, 12, 4], 106: ["Story Book", 199.0, 0, 15]}
cart = {}
sales = []
bill_no = 1000


def show_catalogue():
    """Displays all items."""
    print(f"{'Code':<6}{'Item':<22}{'Price':>8}{'GST%':>6}{'Stock':>7}")
    print("-" * 49)
    for c, (n, p, g, s) in catalogue.items():
        print(f"{c:<6}{n:<22}{p:>8.2f}{g:>6}{s:>7}")


def add_to_cart():
    """Adds an item to the cart."""
    try:
        code = int(input("Item code: "))
        qty = int(input("Quantity : "))
    except ValueError:
        print("Enter numbers only.")
        return
    if code not in catalogue:
        print("Item not found.")
        return
    have = cart.get(code, 0)
    if qty <= 0 or qty + have > catalogue[code][3]:
        print("Only", catalogue[code][3] - have, "in stock.")
        return
    cart[code] = have + qty
    print(f"Added {qty} x {catalogue[code][0]}")


def view_cart():
    """Shows the cart."""
    if not cart:
        print("Cart is empty.")
        return
    for c, q in cart.items():
        print(f"{c}  {catalogue[c][0]:<22} x {q:<3} = Rs. {catalogue[c][1] * q:.2f}")


def remove_item():
    """Removes an item from the cart."""
    try:
        c = int(input("Code to remove: "))
    except ValueError:
        return
    print("Removed." if cart.pop(c, None) else "Not in cart.")


def invoice():
    """Generates a GST invoice."""
    global bill_no
    if not cart:
        print("Cart is empty.")
        return
    cust = input("Customer name: ").strip().title()
    bill_no += 1
    print("\n" + "=" * 62)
    print("KV STATIONERY MART - TAX INVOICE".center(62))
    print(f"Invoice No: {bill_no}      Customer: {cust}")
    print("=" * 62)
    print(f"{'Item':<22}{'Qty':>4}{'Rate':>9}{'Amount':>10}{'GST%':>6}{'GST':>9}")
    sub = gst = 0
    for c, q in cart.items():
        n, p, g, s = catalogue[c]
        amt = p * q
        tax = amt * g / 100
        sub += amt
        gst += tax
        print(f"{n:<22}{q:>4}{p:>9.2f}{amt:>10.2f}{g:>6}{tax:>9.2f}")
        catalogue[c][3] -= q
    disc = sub * 0.05 if sub > 2000 else 0
    if disc:
        gst *= 0.95            # GST is charged on the discounted value
    total = sub - disc + gst
    print("-" * 62)
    print(f"{'Sub-total':<45}{sub:>15.2f}")
    if disc:
        print(f"{'Discount 5% (bill above Rs. 2000)':<45}{-disc:>15.2f}")
    print(f"{'CGST':<45}{gst / 2:>15.2f}")
    print(f"{'SGST':<45}{gst / 2:>15.2f}")
    print(f"{'Round off':<45}{round(total) - total:>15.2f}")
    print(f"{'NET PAYABLE':<45}{round(total):>15.2f}")
    print("=" * 62)
    sales.append((bill_no, cust, round(total), gst))
    cart.clear()
    low_stock()


def summary():
    """Sales of the day."""
    if not sales:
        print("No sales yet.")
        return
    for b, c, amt, g in sales:
        print(f"Bill {b}  {c:<12} Rs. {amt:>8}  (GST {g:.2f})")
    print(f"Bills: {len(sales)} | Sales: Rs. {sum(s[2] for s in sales)} | GST collected: Rs. {sum(s[3] for s in sales):.2f}")


def low_stock():
    """Items with stock below 5."""
    low = [(c, v[0], v[3]) for c, v in catalogue.items() if v[3] < 5]
    for c, n, s in low:
        print(f"LOW STOCK: {n} - only {s} left")
    if not low:
        print("All items have enough stock.")


menu = {"1": show_catalogue, "2": add_to_cart, "3": view_cart, "4": remove_item,
        "5": invoice, "6": summary, "7": low_stock}
print("=" * 62)
print("SHOP BILLING & GST CALCULATOR".center(62))
print("=" * 62)
while True:
    print("\n1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        summary()
        print("Shop closed.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Add to cart? → No: run selected option
  4. Read item code and quantity
  5. Code exists and stock enough? → No: show message
  6. Add to cart
  7. Invoice - amount, GST (CGST/SGST), discount, round off
  8. Reduce stock and save sale
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Add code 101 qty 2Added to cartPASS
2Code 999'Item not found'PASS
3Qty more than stock'Only n in stock'PASS
4Invoice of Rs. 24005 % discount appliedPASS
5GST 18 % on Rs. 1000CGST 90 + SGST 90PASS
6Remove item from cartItem removedPASS
7Invoice with empty cart'Cart is empty'PASS
8Sales summaryBills, sales and GST totalsPASS
โš  Limitations
  • Stock is not saved after closing
  • Single counter / single user
  • No barcode scanner
  • Simple fixed discount rule
๐Ÿš€ Future scope
  • Store catalogue and sales in MySQL
  • Print invoice as PDF
  • UPI QR code on the invoice
  • Monthly GST return report

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: catalogue, cart, sales, bill_no.
  2. 7 functions are defined (lines 15โ€“116) - Python stores them but does NOT run them yet.
  3. Main program starts at line 119: menu = {"1": show_catalogue, "2": add_to_cart, "3": view_cart, "4": re - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
show_catalogue()15โ€“20Displays all items.main program (menu)
add_to_cart()23โ€“39Adds an item to the cart.main program (menu)
view_cart()42โ€“48Shows the cart.main program (menu)
remove_item()51โ€“57Removes an item from the cart.main program (menu)
invoice()60โ€“97Generates a GST invoice.main program (menu)
summary()100โ€“107Sales of the day.main program (menu), main program
low_stock()110โ€“116Items with stock below 5.invoice(), main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
119
menu = {"1": show_catalogue, "2": add_to_cart, "3": view_cart, "4": remove_item,
        "5": invoice, "6": summary, "7": low_stock}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": show_catalogue, "2": add_to_cart, "3": โ€ฆ in variable menu
121
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
122
print("SHOP BILLING & GST CALCULATOR".center(62))
๐Ÿ–ฅ๏ธ Output Displays the value of "SHOP BILLING & GST CALCULATOR".center(62) on the screen
123
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
124
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
125
print("\n1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Catalogue 2.Add 3.Cart 4.Removeโ€ฆ" on the screen
126
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
127
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
128
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary() - sales of the day
129
print("Shop closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Shop closed." on the screen
130
break
๐Ÿ” Loop BREAK - leaves the loop immediately
131
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: SHOP BILLING & GST CALCULATOR (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show_catalogue()
    shows: Code Item Price GST% Stock (+7 more lines)
  3. You type 2 at Enter choice:
    runs: add_to_cart()
  4. You type 101 at Item code:
  5. You type 3 at Quantity :
    shows: Added 3 x Notebook (pack of 6) (+1 more lines)
  6. You type 2 at Enter choice:
    runs: add_to_cart()
  7. You type 104 at Item code:
  8. You type 1 at Quantity :
    shows: Added 1 x School Bag (+1 more lines)
  9. You type 2 at Enter choice:
    runs: add_to_cart()
  10. You type 999 at Item code:
  11. You type 2 at Quantity :
    shows: Item not found. (+1 more lines)
  12. You type 103 at Enter choice:
    shows: Invalid choice (+1 more lines)
  13. You type 50 at Enter choice:
    shows: Invalid choice (+1 more lines)
  14. You type 2 at Enter choice:
    runs: add_to_cart()
  15. You type 103 at Item code:
  16. You type 3 at Quantity :
    shows: Added 3 x Ball Pen (box) (+1 more lines)
  17. You type 3 at Enter choice:
    runs: view_cart()
    shows: 101 Notebook (pack of 6) x 3 = Rs. 720.00 (+3 more lines)
  18. You type 4 at Enter choice:
    runs: remove_item()
  19. You type 103 at Code to remove:
    shows: Removed. (+1 more lines)
  20. You type 5 at Enter choice:
    runs: invoice()
  21. You type Neha Gupta at Customer name:
    runs: low_stock()
    shows: KV STATIONERY MART - TAX INVOICE (+12 more lines)
  22. You type 2 at Enter choice:
    runs: add_to_cart()
  23. You type 102 at Item code:
  24. You type 1 at Quantity :
    shows: Added 1 x Geometry Box (+1 more lines)
  25. You type 2 at Enter choice:
    runs: add_to_cart()
  26. You type 105 at Item code:
  27. You type 4 at Quantity :
    shows: Added 4 x Water Bottle (+1 more lines)
  28. You type 5 at Enter choice:
    runs: invoice()
  29. You type Arjun at Customer name:
    runs: low_stock()
    shows: KV STATIONERY MART - TAX INVOICE (+11 more lines)
  30. You type 5 at Enter choice:
    runs: invoice()
    shows: Cart is empty. (+1 more lines)
  31. You type X at Enter choice:
    shows: Invalid choice (+1 more lines)
  32. You type 6 at Enter choice:
    runs: summary()
    shows: Bill 1001 Neha Gupta Rs. 2392 (GST 330.03) (+3 more lines)
  33. You type 7 at Enter choice:
    runs: low_stock()
    shows: LOW STOCK: Water Bottle - only 0 left (+1 more lines)
  34. You type 0 at Enter choice:
    runs: summary()
    shows: Bill 1001 Neha Gupta Rs. 2392 (GST 330.03) (+3 more lines)
โ‘ค Inside each function - line by line
show_catalogue() - lines 15โ€“20
LineCodeWhat it does
15
def show_catalogue():
๐Ÿงฉ Function DEFINES a function show_catalogue(). Python only remembers it here - its body runs later, each time show_catalogue() is called.
17
print(f"{'Code':<6}{'Item':<22}{'Price':>8}{'GST%':>6}{'Stock':>7}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Code':<6}{'Item':<22}{'Price':>8}{'GST%':โ€ฆ with the values filled into { } on the screen
18
print("-" * 49)
๐Ÿ–ฅ๏ธ Output Displays a line of 49 "-" signs on the screen
19
for c, (n, p, g, s) in catalogue.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary catalogue; c, (n, p, g, s) get one pair each round
20
print(f"{c:<6}{n:<22}{p:>8.2f}{g:>6}{s:>7}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c:<6}{n:<22}{p:>8.2f}{g:>6}{s:>7}" with the values filled into { } on the screen
add_to_cart() - lines 23โ€“39
LineCodeWhat it does
23
def add_to_cart():
๐Ÿงฉ Function DEFINES a function add_to_cart(). Python only remembers it here - its body runs later, each time add_to_cart() is called.
25
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
26
code = int(input("Item code: "))
โŒจ๏ธ Input Shows "Item code: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable code
27
qty = int(input("Quantity : "))
โŒจ๏ธ Input Shows "Quantity : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable qty
28
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
29
print("Enter numbers only.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter numbers only." on the screen
30
return
๐Ÿงฉ Function Ends the function and goes back to the caller
31
if code not in catalogue:
๐Ÿ”€ Decision CHECKS whether code is not present in catalogue. If True, the indented lines below run; otherwise they are skipped
32
print("Item not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Item not found." on the screen
33
return
๐Ÿงฉ Function Ends the function and goes back to the caller
34
have = cart.get(code, 0)
๐Ÿงฎ Store / Calculate Gets the value for key code from cart (or 0 if the key is not there); the result is stored in variable have
35
if qty <= 0 or qty + have > catalogue[code][3]:
๐Ÿ”€ Decision CHECKS whether (qty is less than or equal to 0 OR qty + have is greater than catalogue[code][3]). If True, the indented lines below run; otherwise they are skipped
36
print("Only", catalogue[code][3] - have, "in stock.")
๐Ÿ–ฅ๏ธ Output Displays the text "Only", then the value of catalogue[code][3] - have, then the text "in stock." on the screen
37
return
๐Ÿงฉ Function Ends the function and goes back to the caller
38
cart[code] = have + qty
๐Ÿงฎ Store / Calculate Puts the value of have + qty (calculated using +) into cart[code] (item code of cart)
39
print(f"Added {qty} x {catalogue[code][0]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Added {qty} x {catalogue[code][0]}" with the values filled into { } on the screen
view_cart() - lines 42โ€“48
LineCodeWhat it does
42
def view_cart():
๐Ÿงฉ Function DEFINES a function view_cart(). Python only remembers it here - its body runs later, each time view_cart() is called.
44
if not cart:
๐Ÿ”€ Decision CHECKS whether cart is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
45
print("Cart is empty.")
๐Ÿ–ฅ๏ธ Output Displays the text "Cart is empty." on the screen
46
return
๐Ÿงฉ Function Ends the function and goes back to the caller
47
for c, q in cart.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary cart; c, q get one pair each round
48
print(f"{c}  {catalogue[c][0]:<22} x {q:<3} = Rs. {catalogue[c][1] * q:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c} {catalogue[c][0]:<22} x {q:<3} = Rs. {cโ€ฆ with the values filled into { } on the screen
remove_item() - lines 51โ€“57
LineCodeWhat it does
51
def remove_item():
๐Ÿงฉ Function DEFINES a function remove_item(). Python only remembers it here - its body runs later, each time remove_item() is called.
53
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
54
c = int(input("Code to remove: "))
โŒจ๏ธ Input Shows "Code to remove: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable c
55
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
56
return
๐Ÿงฉ Function Ends the function and goes back to the caller
57
print("Removed." if cart.pop(c, None) else "Not in cart.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Removed." if cart.pop(c, None) else "Not in โ€ฆ on the screen
invoice() - lines 60โ€“97
LineCodeWhat it does
60
def invoice():
๐Ÿงฉ Function DEFINES a function invoice(). Python only remembers it here - its body runs later, each time invoice() is called.
62
global bill_no
๐Ÿงฉ Function Tells Python that bill_no means the GLOBAL variable (outside the function)
63
if not cart:
๐Ÿ”€ Decision CHECKS whether cart is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
64
print("Cart is empty.")
๐Ÿ–ฅ๏ธ Output Displays the text "Cart is empty." on the screen
65
return
๐Ÿงฉ Function Ends the function and goes back to the caller
66
cust = input("Customer name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cust
67
bill_no += 1
๐Ÿงฎ Store / Calculate Adds 1 to bill_no (same as bill_no = bill_no + 1)
68
print("\n" + "=" * 62)
๐Ÿ–ฅ๏ธ Output Displays the value of "\n" + "=" * 62 on the screen
69
print("KV STATIONERY MART - TAX INVOICE".center(62))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV STATIONERY MART - TAX INVOICE".center(62) on the screen
70
print(f"Invoice No: {bill_no}      Customer: {cust}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Invoice No: {bill_no} Customer: {cust}" with the values filled into { } on the screen
71
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
72
print(f"{'Item':<22}{'Qty':>4}{'Rate':>9}{'Amount':>10}{'GST%':>6}{'GST':>9}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Item':<22}{'Qty':>4}{'Rate':>9}{'Amount':โ€ฆ with the values filled into { } on the screen
73
sub = gst = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable sub
74
for c, q in cart.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary cart; c, q get one pair each round
75
n, p, g, s = catalogue[c]
๐Ÿงฎ Store / Calculate Stores the item catalogue[c] in variables n, p, g, s
76
amt = p * q
๐Ÿงฎ Store / Calculate Stores the value of p * q (calculated using ร—) in variable amt
77
tax = amt * g / 100
๐Ÿงฎ Store / Calculate Stores the value of amt * g / 100 (calculated using รท) in variable tax
78
sub += amt
๐Ÿงฎ Store / Calculate Adds amt to sub (same as sub = sub + amt)
79
gst += tax
๐Ÿงฎ Store / Calculate Adds tax to gst (same as gst = gst + tax)
80
print(f"{n:<22}{q:>4}{p:>9.2f}{amt:>10.2f}{g:>6}{tax:>9.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<22}{q:>4}{p:>9.2f}{amt:>10.2f}{g:>6}{taโ€ฆ with the values filled into { } on the screen
81
catalogue[c][3] -= q
๐Ÿงฎ Store / Calculate Subtracts q from catalogue[c][3] (same as catalogue[c][3] = catalogue[c][3] - q)
82
disc = sub * 0.05 if sub > 2000 else 0
๐Ÿงฎ Store / Calculate Stores either sub * 0.05 or 0 depending on sub > 2000 in variable disc
83
if disc:
๐Ÿ”€ Decision CHECKS whether disc is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
84
gst *= 0.95            # GST is charged on the discounted value
๐Ÿงฎ Store / Calculate Multiplies gst by 0.95 (same as gst = gst ร— 0.95)
85
total = sub - disc + gst
๐Ÿงฎ Store / Calculate Stores the value of sub - disc + gst (calculated using +) in variable total
86
print("-" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "-" signs on the screen
87
print(f"{'Sub-total':<45}{sub:>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Sub-total':<45}{sub:>15.2f}" with the values filled into { } on the screen
88
if disc:
๐Ÿ”€ Decision CHECKS whether disc is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
89
print(f"{'Discount 5% (bill above Rs. 2000)':<45}{-disc:>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Discount 5% (bill above Rs. 2000)':<45}{-โ€ฆ with the values filled into { } on the screen
90
print(f"{'CGST':<45}{gst / 2:>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'CGST':<45}{gst / 2:>15.2f}" with the values filled into { } on the screen
91
print(f"{'SGST':<45}{gst / 2:>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'SGST':<45}{gst / 2:>15.2f}" with the values filled into { } on the screen
92
print(f"{'Round off':<45}{round(total) - total:>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Round off':<45}{round(total) - total:>15.โ€ฆ with the values filled into { } on the screen
93
print(f"{'NET PAYABLE':<45}{round(total):>15.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'NET PAYABLE':<45}{round(total):>15.2f}" with the values filled into { } on the screen
94
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
95
sales.append((bill_no, cust, round(total), gst))
๐Ÿงฎ Store / Calculate Adds (bill_no, cust, round(total), gst) at the end of list sales
96
cart.clear()
๐Ÿงฎ Store / Calculate Removes all items from cart
97
low_stock()
๐Ÿงฎ Store / Calculate Calls our own function low_stock() - items with stock below 5
summary() - lines 100โ€“107
LineCodeWhat it does
100
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
102
if not sales:
๐Ÿ”€ Decision CHECKS whether sales is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
103
print("No sales yet.")
๐Ÿ–ฅ๏ธ Output Displays the text "No sales yet." on the screen
104
return
๐Ÿงฉ Function Ends the function and goes back to the caller
105
for b, c, amt, g in sales:
๐Ÿ” Loop LOOP: takes each item of sales one-by-one into b, c, amt, g and runs the indented block for it
106
print(f"Bill {b}  {c:<12} Rs. {amt:>8}  (GST {g:.2f})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bill {b} {c:<12} Rs. {amt:>8} (GST {g:.2f})" with the values filled into { } on the screen
107
print(f"Bills: {len(sales)} | Sales: Rs. {sum(s[2] for s in sales)} | GST collected: Rs. {sum(s[3] for s in sales):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bills: {len(sales)} | Sales: Rs. {sum(s[2] โ€ฆ with the values filled into { } on the screen
low_stock() - lines 110โ€“116
LineCodeWhat it does
110
def low_stock():
๐Ÿงฉ Function DEFINES a function low_stock(). Python only remembers it here - its body runs later, each time low_stock() is called.
112
low = [(c, v[0], v[3]) for c, v in catalogue.items() if v[3] < 5]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [(c, v[0], v[3]) for c, v in catalogue.items(โ€ฆ in variable low
113
for c, n, s in low:
๐Ÿ” Loop LOOP: takes each item of low one-by-one into c, n, s and runs the indented block for it
114
print(f"LOW STOCK: {n} - only {s} left")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"LOW STOCK: {n} - only {s} left" with the values filled into { } on the screen
115
if not low:
๐Ÿ”€ Decision CHECKS whether low is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
116
print("All items have enough stock.")
๐Ÿ–ฅ๏ธ Output Displays the text "All items have enough stock." on the screen
Q1. What is the difference between CGST and SGST?

For sales within a state, GST is split equally: half is Central GST and half is State GST.

Q2. Why is a dictionary used for the catalogue?

The item code is a unique key, so price, GST and stock of an item can be found directly.

Q3. How is the round-off calculated?

round(total) - total gives the paise adjustment so the final amount is in whole rupees.

Q4. How is stock updated?

After the invoice is generated, the quantity sold is subtracted from catalogue[code][3].

Q5. How is the discount applied?

If the amount before tax is more than Rs. 2000, 5 % of it is subtracted.

03

Class Result Dictionary System

PYTHONDictionary of listssearchhighest/lowest (Practicals 19-21)
๐Ÿ“ 129 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 91 output lines๐Ÿ“„ 25+ page report

Store 5-subject marks for a whole class in a dictionary, compute rank list by total marks, and let a teacher search any student's full mark-sheet by name.

โœจ Features
  • Class result system using a dictionary of lists
  • Mark sheet with total, percentage, grade and result for every student
  • Rank list with ties handled
  • Subject-wise statistics: mean, median, highest, lowest (statistics module)
  • Search, modify and delete records; merit list above a cut-off
  • Pass percentage and grade-wise counts
โ˜ฐ Main menu
1Add StudentName and marks of 5 subjects
2Mark SheetMarks, total, %, grade of all students
3Rank ListStudents ranked by total marks
4Subject StatisticsMean, median, highest and lowest of each subject
5Search StudentMark sheet of one student
6Modify MarksChanges marks of one subject
7Delete StudentRemoves a record
8Merit ListStudents above a percentage cut-off
9Class SummaryPass %, grade counts
0ExitEnds the program
๐ŸŽฏ Objectives
  • Use a dictionary whose values are lists
  • Sort items with sorted() and a lambda key
  • Search a record by key
๐Ÿ“š Data dictionary
NameTypePurpose
class_datadictName -> list of 5 marks
SUBJECTSlistSubject names
statisticsmodulemean() and median() functions
Why it matters: A working prototype of a school's internal result-management dictionary.
# =====================================================================
#   CLASS RESULT DICTIONARY SYSTEM
#   Concepts : dictionaries, lists, list comprehension, sorting,
#              statistics module, functions
# =====================================================================
import statistics

SUBJECTS = ["English", "Maths", "IP", "Physics", "Economics"]
class_data = {"Ravi": [78, 85, 92, 70, 81], "Simran": [88, 79, 95, 84, 90],
              "Kabir": [65, 58, 72, 61, 69], "Meera": [92, 96, 98, 89, 94],
              "Tanvi": [55, 32, 64, 48, 59], "Arjun": [78, 85, 92, 70, 81]}


def total(name):
    return sum(class_data[name])


def percent(name):
    return total(name) / len(SUBJECTS)


def grade(p):
    """Grade from percentage."""
    return "A1" if p >= 90 else "A2" if p >= 80 else "B1" if p >= 70 else "B2" if p >= 60 else "C" if p >= 33 else "E"


def result(name):
    return "PASS" if min(class_data[name]) >= 33 else "COMPARTMENT"


def add_student():
    """Adds a student."""
    name = input("Name: ").strip().title()
    try:
        class_data[name] = [float(input(f"  {s:<10}: ")) for s in SUBJECTS]
        print("Added", name)
    except ValueError:
        print("Invalid marks - record not added.")


def mark_sheet(names=None):
    """Mark sheet of all (or given) students."""
    names = names or list(class_data)
    print(f"{'Name':<8}" + "".join(f"{s[:4]:>6}" for s in SUBJECTS) + f"{'Total':>7}{'%':>7}  Gr  Result")
    print("-" * 72)
    for n in names:
        print(f"{n:<8}" + "".join(f"{m:>6.0f}" for m in class_data[n]) +
              f"{total(n):>7.0f}{percent(n):>7.1f}  {grade(percent(n)):<3} {result(n)}")


def rank_list():
    """Ranks with ties."""
    order = sorted(class_data, key=total, reverse=True)
    rank, prev = 0, None
    for i, n in enumerate(order, 1):
        if total(n) != prev:
            rank = i
        prev = total(n)
        print(f"Rank {rank}: {n:<8} Total {total(n):.0f}")


def subject_stats():
    """Mean, median, highest, lowest."""
    print(f"{'Subject':<11}{'Mean':>7}{'Median':>8}{'High':>6}{'Low':>6}")
    for i, s in enumerate(SUBJECTS):
        col = [m[i] for m in class_data.values()]
        print(f"{s:<11}{statistics.mean(col):>7.1f}{statistics.median(col):>8.1f}{max(col):>6.0f}{min(col):>6.0f}")


def search():
    """One student's mark sheet."""
    n = input("Student name: ").strip().title()
    if n in class_data:
        mark_sheet([n])
    else:
        print("Student not found.")


def modify():
    """Modifies one subject's marks."""
    n = input("Student name: ").strip().title()
    if n not in class_data:
        print("Student not found.")
        return
    k = int(input("Subject no (1-5): ")) - 1
    class_data[n][k] = float(input("New marks: "))
    print("Updated. New total:", total(n))


def delete():
    """Deletes a student."""
    n = input("Student name: ").strip().title()
    print("Deleted." if class_data.pop(n, None) else "Student not found.")


def merit_list():
    """Students above a cut-off."""
    cut = float(input("Cut-off %: "))
    merit = [n for n in sorted(class_data, key=percent, reverse=True) if percent(n) >= cut]
    print("Merit list:", ", ".join(f"{n} ({percent(n):.1f}%)" for n in merit) or "none")


def class_summary():
    """Pass % and grade counts."""
    n = len(class_data)
    passed = sum(1 for s in class_data if result(s) == "PASS")
    print(f"Students {n} | Passed {passed} | Pass % {passed / n * 100:.1f}")
    counts = {}
    for s in class_data:
        g = grade(percent(s))
        counts[g] = counts.get(g, 0) + 1
    for g in sorted(counts):
        print(f"  {g:<3}" + "#" * (counts[g] * 3), counts[g])
    print("Class average:", round(statistics.mean(percent(s) for s in class_data), 2), "%")


menu = {"1": add_student, "2": mark_sheet, "3": rank_list, "4": subject_stats, "5": search,
        "6": modify, "7": delete, "8": merit_list, "9": class_summary}
print("=" * 72)
print("CLASS XI RESULT SYSTEM".center(72))
print("=" * 72)
while True:
    print("\n1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Bye!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Load sample class data
  3. Display menu and read choice
  4. Choice is Add? → No: run selected report
  5. Read name and 5 marks
  6. Total, %, grade for reports
  7. Rank list sorted by total
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Add 'Zoya' with marksRecord addedPASS
2Mark sheetTotal, % and grade of allPASS
3Two students with equal totalSame rank givenPASS
4Subject statisticsMean and median per subjectPASS
5Search 'Ravi'Mark sheet shownPASS
6Modify Zoya Maths to 99Total recalculatedPASS
7Merit list cut-off 80Only students >= 80 %PASS
8Delete unknown'Student not found'PASS
โš  Limitations
  • Data is not saved permanently
  • Exactly 5 subjects
  • Name must be unique
  • No graphs
๐Ÿš€ Future scope
  • Use Pandas DataFrame (Class XII IP)
  • Bar chart of results with Matplotlib
  • Save to CSV
  • Generate PDF mark sheets

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): statistics - mean, median, mode functions are loaded.
  2. Global variables / constants are created: SUBJECTS, class_data.
  3. 13 functions are defined (lines 14โ€“114) - Python stores them but does NOT run them yet.
  4. Main program starts at line 117: menu = {"1": add_student, "2": mark_sheet, "3": rank_list, "4": subjec - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
total(name)14โ€“15Totalpercent(), mark_sheet(), rank_list(), modify()
percent(name)18โ€“19Percentmark_sheet(), merit_list(), class_summary()
grade(p)22โ€“24Grade from percentage.mark_sheet(), class_summary()
result(name)27โ€“28Resultmark_sheet(), class_summary()
add_student()31โ€“38Adds a student.main program (menu)
mark_sheet(names)41โ€“48Mark sheet of all (or given) students.search(), main program (menu)
rank_list()51โ€“59Ranks with ties.main program (menu)
subject_stats()62โ€“67Mean, median, highest, lowest.main program (menu)
search()70โ€“76One student's mark sheet.main program (menu)
modify()79โ€“87Modifies one subject's marks.main program (menu)
delete()90โ€“93Deletes a student.main program (menu)
merit_list()96โ€“100Students above a cut-off.main program (menu)
class_summary()103โ€“114Pass % and grade counts.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
117
menu = {"1": add_student, "2": mark_sheet, "3": rank_list, "4": subject_stats, "5": search,
        "6": modify, "7": delete, "8": merit_list, "9": class_sumโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_student, "2": mark_sheet, "3": rankโ€ฆ in variable menu
119
print("=" * 72)
๐Ÿ–ฅ๏ธ Output Displays a line of 72 "=" signs on the screen
120
print("CLASS XI RESULT SYSTEM".center(72))
๐Ÿ–ฅ๏ธ Output Displays the value of "CLASS XI RESULT SYSTEM".center(72) on the screen
121
print("=" * 72)
๐Ÿ–ฅ๏ธ Output Displays a line of 72 "=" signs on the screen
122
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
123
print("\n1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Marksheet 3.Rank 4.Subjecโ€ฆ" on the screen
124
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
125
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
126
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
127
break
๐Ÿ” Loop BREAK - leaves the loop immediately
128
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CLASS XI RESULT SYSTEM (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add_student()
  3. You type Zoya at Name:
  4. You type 91 at English :
  5. You type 88 at Maths :
  6. You type 94 at IP :
  7. You type 86 at Physics :
  8. You type 90 at Economics :
    shows: Added Zoya (+1 more lines)
  9. You type 2 at Enter choice:
    runs: mark_sheet() โ†’ total() โ†’ percent() โ†’ total() โ†’ percent() โ†’ total() โ†’ grade() โ†’ result()
    shows: Name Engl Math IP Phys Econ Total % Gr Result (+8 more lines)
  10. You type 3 at Enter choice:
    runs: rank_list() โ†’ total() ร—28
    shows: Rank 1: Meera Total 469 (+7 more lines)
  11. You type 4 at Enter choice:
    runs: subject_stats()
    shows: Subject Mean Median High Low (+6 more lines)
  12. You type 5 at Enter choice:
    runs: search()
  13. You type Ravi at Student name:
    runs: mark_sheet() โ†’ total() โ†’ percent() โ†’ total() โ†’ percent() โ†’ total() โ†’ grade() โ†’ result()
    shows: Name Engl Math IP Phys Econ Total % Gr Result (+2 more lines)
  14. You type 6 at Enter choice:
    runs: modify()
  15. You type Zoya at Student name:
  16. You type 2 at Subject no (1-5):
  17. You type 99 at New marks:
    runs: total()
    shows: Updated. New total: 460.0 (+1 more lines)
  18. You type 8 at Enter choice:
    runs: merit_list()
  19. You type 80 at Cut-off %:
    runs: percent() โ†’ total() โ†’ percent() โ†’ total() โ†’ percent() โ†’ total() โ†’ percent() โ†’ total()
    shows: Merit list: Meera (93.8%), Zoya (92.0%), Simran (87.2%), Ravi (81.2%), Arjun (81.2%) (+1 more lines)
  20. You type 7 at Enter choice:
    runs: delete()
  21. You type Mohan at Student name:
    shows: Student not found. (+1 more lines)
  22. You type 9 at Enter choice:
    runs: class_summary() โ†’ result() ร—7 โ†’ percent() โ†’ total() โ†’ grade() โ†’ percent() โ†’ total() โ†’ grade()
    shows: Students 7 | Passed 6 | Pass % 85.7 (+6 more lines)
  23. You type 3 at Enter choice:
    runs: rank_list() โ†’ total() ร—28
    shows: Rank 1: Meera Total 469 (+7 more lines)
  24. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
total() - lines 14โ€“15
LineCodeWhat it does
14
def total(name):
๐Ÿงฉ Function DEFINES a function total(name). Python only remembers it here - its body runs later, each time total() is called.
15
return sum(class_data[name])
๐Ÿงฉ Function Sends back (returns) the result of: adds up all the values in class_data[name] to the line that called the function
percent() - lines 18โ€“19
LineCodeWhat it does
18
def percent(name):
๐Ÿงฉ Function DEFINES a function percent(name). Python only remembers it here - its body runs later, each time percent() is called.
19
return total(name) / len(SUBJECTS)
๐Ÿงฉ Function Sends back (returns) the value of total(name) / len(SUBJECTS) (calculated using รท) to the line that called the function
grade() - lines 22โ€“24
LineCodeWhat it does
22
def grade(p):
๐Ÿงฉ Function DEFINES a function grade(p). Python only remembers it here - its body runs later, each time grade() is called.
24
return "A1" if p >= 90 else "A2" if p >= 80 else "B1" if p >= 70 else "B2" if p >= 60 else "C" if p >= 33 else "E"
๐Ÿงฉ Function Sends back (returns) either "A1" or "A2" if p >= 80 else "B1" if p >= 70 else "B2โ€ฆ depending on p >= 90 to the line that called the function
result() - lines 27โ€“28
LineCodeWhat it does
27
def result(name):
๐Ÿงฉ Function DEFINES a function result(name). Python only remembers it here - its body runs later, each time result() is called.
28
return "PASS" if min(class_data[name]) >= 33 else "COMPARTMENT"
๐Ÿงฉ Function Sends back (returns) either "PASS" or "COMPARTMENT" depending on min(class_data[name]) >= 33 to the line that called the function
add_student() - lines 31โ€“38
LineCodeWhat it does
31
def add_student():
๐Ÿงฉ Function DEFINES a function add_student(). Python only remembers it here - its body runs later, each time add_student() is called.
33
name = input("Name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
34
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
35
class_data[name] = [float(input(f"  {s:<10}: ")) for s in SUBJECTS]
โŒจ๏ธ Input Puts a new list made by a list comprehension [float(input(f" {s:<10}: ")) for s in SUBJECTโ€ฆ into class_data[name] (item name of class_data)
36
print("Added", name)
๐Ÿ–ฅ๏ธ Output Displays the text "Added", then the value of name on the screen
37
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
38
print("Invalid marks - record not added.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid marks - record not added." on the screen
mark_sheet() - lines 41โ€“48
LineCodeWhat it does
41
def mark_sheet(names=None):
๐Ÿงฉ Function DEFINES a function mark_sheet(names). Python only remembers it here - its body runs later, each time mark_sheet() is called.
43
names = names or list(class_data)
๐Ÿงฎ Store / Calculate Stores the value of names, or list(class_data) if the first one is empty / None / 0 in variable names
44
print(f"{'Name':<8}" + "".join(f"{s[:4]:>6}" for s in SUBJECTS) + f"{'Total':>7}{'%':>7}  Gr  Result")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{'Name':<8}" + "".join(f"{s[:4]:>6}" for s โ€ฆ on the screen
45
print("-" * 72)
๐Ÿ–ฅ๏ธ Output Displays a line of 72 "-" signs on the screen
46
for n in names:
๐Ÿ” Loop LOOP: takes each item of names one-by-one into n and runs the indented block for it
47
print(f"{n:<8}" + "".join(f"{m:>6.0f}" for m in class_data[n]) +
      f"{total(n):>7.0f}{percent(n):>7.1f}  {grade(percent(n)):<3} {result(n)}")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{n:<8}" + "".join(f"{m:>6.0f}" for m in claโ€ฆ on the screen
rank_list() - lines 51โ€“59
LineCodeWhat it does
51
def rank_list():
๐Ÿงฉ Function DEFINES a function rank_list(). Python only remembers it here - its body runs later, each time rank_list() is called.
53
order = sorted(class_data, key=total, reverse=True)
๐Ÿงฎ Store / Calculate Makes a new sorted list from class_data; the result is stored in variable order
54
rank, prev = 0, None
๐Ÿงฎ Store / Calculate Stores 0, None into rank, prev respectively
55
for i, n in enumerate(order, 1):
๐Ÿ” Loop LOOP over order with position: in each round i, n get (position, item)
56
if total(n) != prev:
๐Ÿ”€ Decision CHECKS whether total(n) is not equal to prev. If True, the indented lines below run; otherwise they are skipped
57
rank = i
๐Ÿงฎ Store / Calculate Stores the value of i in variable rank
58
prev = total(n)
๐Ÿงฎ Store / Calculate Calls our own function total(n); the result is stored in variable prev
59
print(f"Rank {rank}: {n:<8} Total {total(n):.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Rank {rank}: {n:<8} Total {total(n):.0f}" with the values filled into { } on the screen
subject_stats() - lines 62โ€“67
LineCodeWhat it does
62
def subject_stats():
๐Ÿงฉ Function DEFINES a function subject_stats(). Python only remembers it here - its body runs later, each time subject_stats() is called.
64
print(f"{'Subject':<11}{'Mean':>7}{'Median':>8}{'High':>6}{'Low':>6}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Subject':<11}{'Mean':>7}{'Median':>8}{'Hiโ€ฆ with the values filled into { } on the screen
65
for i, s in enumerate(SUBJECTS):
๐Ÿ” Loop LOOP over SUBJECTS with position: in each round i, s get (position, item)
66
col = [m[i] for m in class_data.values()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [m[i] for m in class_data.values()] in variable col
67
print(f"{s:<11}{statistics.mean(col):>7.1f}{statistics.median(col):>8.1f}{max(col):>6.0f}{min(col):>6.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s:<11}{statistics.mean(col):>7.1f}{statistโ€ฆ with the values filled into { } on the screen
search() - lines 70โ€“76
LineCodeWhat it does
70
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
72
n = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
73
if n in class_data:
๐Ÿ”€ Decision CHECKS whether n is present in class_data. If True, the indented lines below run; otherwise Python jumps to the elif/else part
74
mark_sheet([n])
๐Ÿงฎ Store / Calculate Calls our own function mark_sheet([n]) - mark sheet of all (or given) students
75
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
76
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
modify() - lines 79โ€“87
LineCodeWhat it does
79
def modify():
๐Ÿงฉ Function DEFINES a function modify(). Python only remembers it here - its body runs later, each time modify() is called.
81
n = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
82
if n not in class_data:
๐Ÿ”€ Decision CHECKS whether n is not present in class_data. If True, the indented lines below run; otherwise they are skipped
83
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
84
return
๐Ÿงฉ Function Ends the function and goes back to the caller
85
k = int(input("Subject no (1-5): ")) - 1
โŒจ๏ธ Input Stores the value of int(input("Subject no (1-5): ")) - 1 (calculated using -) in variable k
86
class_data[n][k] = float(input("New marks: "))
โŒจ๏ธ Input Shows "New marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in class_data[n][k] (item k of class_data[n])
87
print("Updated. New total:", total(n))
๐Ÿ–ฅ๏ธ Output Displays the text "Updated. New total:", then the value of total(n) on the screen
delete() - lines 90โ€“93
LineCodeWhat it does
90
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
92
n = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
93
print("Deleted." if class_data.pop(n, None) else "Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Deleted." if class_data.pop(n, None) else "Sโ€ฆ on the screen
merit_list() - lines 96โ€“100
LineCodeWhat it does
96
def merit_list():
๐Ÿงฉ Function DEFINES a function merit_list(). Python only remembers it here - its body runs later, each time merit_list() is called.
98
cut = float(input("Cut-off %: "))
โŒจ๏ธ Input Shows "Cut-off %: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable cut
99
merit = [n for n in sorted(class_data, key=percent, reverse=True) if percent(n) >= cut]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [n for n in sorted(class_data, key=percent, rโ€ฆ in variable merit
100
print("Merit list:", ", ".join(f"{n} ({percent(n):.1f}%)" for n in merit) or "none")
๐Ÿ–ฅ๏ธ Output Displays the text "Merit list:", then the value of ", ".join(f"{n} ({percent(n):.1f}%)" for n inโ€ฆ on the screen
class_summary() - lines 103โ€“114
LineCodeWhat it does
103
def class_summary():
๐Ÿงฉ Function DEFINES a function class_summary(). Python only remembers it here - its body runs later, each time class_summary() is called.
105
n = len(class_data)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in class_data; the result is stored in variable n
106
passed = sum(1 for s in class_data if result(s) == "PASS")
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for s in class_data if result(s) == "PASS"); the result is stored in variable passed
107
print(f"Students {n} | Passed {passed} | Pass % {passed / n * 100:.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Students {n} | Passed {passed} | Pass % {paโ€ฆ with the values filled into { } on the screen
108
counts = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable counts
109
for s in class_data:
๐Ÿ” Loop LOOP: takes each item of class_data one-by-one into s and runs the indented block for it
110
g = grade(percent(s))
๐Ÿงฎ Store / Calculate Calls our own function grade(percent(s)) - grade from percentage; the result is stored in variable g
111
counts[g] = counts.get(g, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of counts.get(g, 0) + 1 (calculated using +) into counts[g] (item g of counts)
112
for g in sorted(counts):
๐Ÿ” Loop LOOP: takes each item of sorted(counts) one-by-one into g and runs the indented block for it
113
print(f"  {g:<3}" + "#" * (counts[g] * 3), counts[g])
๐Ÿ–ฅ๏ธ Output Displays the value of f" {g:<3}" + "#" * (counts[g] * 3), then the value of counts[g] on the screen
114
print("Class average:", round(statistics.mean(percent(s) for s in class_data), 2), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Class average:", then the value of round(statistics.mean(percent(s) for s in claโ€ฆ, then the text "%" on the screen
Q1. Why is a dictionary of lists used?

The student's name is the key and the list holds the five marks in a fixed subject order.

Q2. How are ties handled in the rank list?

If a student's total equals the previous student's total, the previous rank is reused.

Q3. Which functions of the statistics module are used?

statistics.mean() for the average and statistics.median() for the middle value.

Q4. How is a merit list prepared?

A list comprehension selects names whose percentage is greater than or equal to the cut-off.

Q5. What is the difference between del and pop() on a dictionary?

Both remove a key; pop() also returns the value and can take a default to avoid an error.

04

School Student Database (SQL)

MySQL (SQL)CREATE DATABASE/TABLEINSERTSELECTWHEREORDER BY
๐Ÿ“ 128 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 494 output lines๐Ÿ“„ 25+ page report

A fully working MySQL student database: 15 records loaded and ten office-style queries - toppers, section strength, birthdays, weak students and averages.

โœจ Features
  • Two related tables: student and activity (club participation) linked by student_id
  • Constraints: PRIMARY KEY, NOT NULL, CHECK on marks, DEFAULT values
  • 30 queries covering SELECT, WHERE, BETWEEN, IN, LIKE, IS NULL, DISTINCT, ORDER BY
  • Aggregate functions with GROUP BY and HAVING
  • String, numeric and date functions (UPPER, LENGTH, SUBSTR, ROUND, YEAR, MONTHNAME, DATEDIFF)
  • DML: UPDATE grades, DELETE, ALTER TABLE; equi-join of two tables
โ˜ฐ Main menu
M1Create Database & TablesCREATE DATABASE, CREATE TABLE with constraints, DESC
M2Insert RecordsINSERT INTO both tables (15 + 12 rows)
M3Simple QueriesSelection, projection, ORDER BY, DISTINCT, aliases
M4Conditional QueriesBETWEEN, IN, LIKE, IS NULL, AND / OR
M5Aggregate & GroupCOUNT, SUM, AVG, MAX, MIN with GROUP BY / HAVING
M6FunctionsString, maths and date functions
M7Modify DataALTER TABLE, UPDATE, DELETE
M8Join QueriesEqui-join of student and activity tables
M9Views & Sub-queriesCREATE VIEW, nested SELECT, NOT IN
M10Report CardFormatted output with string functions and IF()
๐ŸŽฏ Objectives
  • Create a database and table with proper data types
  • Retrieve data with WHERE, ORDER BY, GROUP BY and HAVING
  • Modify the table using ALTER TABLE and UPDATE
๐Ÿ“š Data dictionary
NameTypePurpose
studentTABLEstudent_id INT PK, name VARCHAR(30) NOT NULL, section CHAR(1), gender CHAR(1), dob DATE, marks DECIMAL(5,2) CHECK 0-100, city VARCHAR(20)
activityTABLEact_id INT PK, student_id INT (refers student), club VARCHAR(20), position VARCHAR(15) DEFAULT 'Member'
gradeCHAR(2)Column added later with ALTER TABLE and filled by UPDATE
Why it matters: Every query here is a typical Class XI SQL practical question, solved on one realistic table.
-- =====================================================================
--   SCHOOL STUDENT DATABASE  (MySQL)  -  Class XI Informatics Practices
-- =====================================================================
-- M1 : Create database and tables
DROP DATABASE IF EXISTS kv_office;
CREATE DATABASE kv_office;
USE kv_office;

CREATE TABLE student (
    student_id INT PRIMARY KEY,
    name       VARCHAR(30) NOT NULL,
    section    CHAR(1),
    gender     CHAR(1),
    dob        DATE,
    marks      DECIMAL(5,2) CHECK (marks BETWEEN 0 AND 100),
    city       VARCHAR(20)
);
CREATE TABLE activity (
    act_id     INT PRIMARY KEY,
    student_id INT,
    club       VARCHAR(20),
    position   VARCHAR(15) DEFAULT 'Member'
);
DESC student;

-- M2 : Insert records
INSERT INTO student VALUES
(1,'Amit','A','M','2009-07-14',88.5,'Delhi'),   (2,'Sara','B','F','2009-03-02',92.0,'Noida'),
(3,'Rahul','A','M','2009-07-25',65.5,'Delhi'),  (4,'Priya','B','F','2009-11-19',78.0,NULL),
(5,'Karan','A','M','2009-01-08',35.0,'Gurugram'),(6,'Neha','C','F','2009-07-30',81.5,'Delhi'),
(7,'Vikas','C','M','2008-12-12',29.0,NULL),     (8,'Anita','B','F','2009-05-21',70.0,'Faridabad'),
(9,'Imran','C','M','2009-09-09',94.5,'Delhi'),  (10,'Pooja','A','F','2009-02-17',47.0,'Noida'),
(11,'Farhan','B','M','2009-07-03',58.5,'Delhi'),(12,'Tina','C','F','2009-10-28',66.0,'Gurugram'),
(13,'Gaurav','A','M','2008-08-15',73.5,'Delhi'),(14,'Divya','B','F','2009-04-04',85.0,'Noida'),
(15,'Harsh','C','M','2009-06-11',39.5,'Delhi');
INSERT INTO activity (act_id, student_id, club, position) VALUES
(1,1,'Robotics','Captain'), (2,2,'Eco Club','Secretary'), (3,9,'Robotics','Member'),
(4,6,'Music','Member'), (5,14,'Eco Club','Member'), (6,3,'Sports','Vice Captain'),
(7,13,'Sports','Captain'), (8,2,'Robotics','Member'), (9,11,'Music','Leader'),
(10,8,'Literary','Editor');
INSERT INTO activity (act_id, student_id, club) VALUES (11,4,'Literary'), (12,12,'Eco Club');
INSERT INTO student VALUES (16,'Test','A','M','2009-01-01',105,'Delhi');

-- M3 : Simple queries
SELECT * FROM student;
SELECT name, marks FROM student ORDER BY marks DESC LIMIT 5;
SELECT DISTINCT city FROM student;
SELECT name AS Student, section AS Sec, marks AS Score FROM student WHERE section = 'B' ORDER BY name;

-- M4 : Conditional queries
SELECT name, dob FROM student WHERE MONTH(dob) = 7;
SELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;
SELECT name, city FROM student WHERE city IN ('Noida','Gurugram');
SELECT name FROM student WHERE name LIKE '_a%';
SELECT name, section FROM student WHERE city IS NULL;
SELECT name, marks FROM student WHERE marks < 40 OR (section = 'C' AND gender = 'F');

-- M5 : Aggregate functions, GROUP BY and HAVING
SELECT COUNT(*) AS Total, AVG(marks) AS Average, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student;
SELECT section, COUNT(*) AS Strength FROM student GROUP BY section;
SELECT section, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student GROUP BY section;
SELECT gender, ROUND(AVG(marks),2) AS Avg_Marks FROM student GROUP BY gender;
SELECT section, ROUND(AVG(marks),2) AS Average FROM student GROUP BY section HAVING AVG(marks) > 65;
SELECT city, COUNT(*) AS Students FROM student WHERE city IS NOT NULL GROUP BY city ORDER BY Students DESC;

-- M6 : String, numeric and date functions
SELECT UPPER(name) AS Name, LENGTH(name) AS Letters, SUBSTR(name,1,3) AS Short FROM student WHERE section = 'A';
SELECT CONCAT(name, ' (', section, ')') AS Student, ROUND(marks/100*500) AS Out_of_500 FROM student LIMIT 6;
SELECT name, YEAR(dob) AS Birth_Year, MONTHNAME(dob) AS Month FROM student WHERE YEAR(dob) = 2008;
SELECT name, DATEDIFF('2026-04-01', dob) DIV 365 AS Age_on_1_April FROM student ORDER BY dob LIMIT 5;

-- M7 : ALTER, UPDATE and DELETE
ALTER TABLE student ADD grade CHAR(2);
UPDATE student SET grade = 'A1' WHERE marks >= 90;
UPDATE student SET grade = 'A2' WHERE marks >= 75 AND marks < 90;
UPDATE student SET grade = 'B'  WHERE marks >= 60 AND marks < 75;
UPDATE student SET grade = 'C'  WHERE marks >= 40 AND marks < 60;
UPDATE student SET grade = 'D'  WHERE marks < 40;
SELECT grade, COUNT(*) AS Students FROM student GROUP BY grade ORDER BY grade;
UPDATE student SET city = 'Delhi' WHERE city IS NULL;
DELETE FROM student WHERE student_id = 7;
SELECT COUNT(*) AS Remaining FROM student;

-- M8 : Equi-join of two tables
SELECT s.name, s.section, a.club, a.position
FROM student s, activity a
WHERE s.student_id = a.student_id
ORDER BY a.club, s.name;
SELECT a.club, COUNT(*) AS Members, ROUND(AVG(s.marks),2) AS Avg_Marks
FROM student s, activity a
WHERE s.student_id = a.student_id
GROUP BY a.club;
SELECT name, dob FROM student WHERE dob = (SELECT MAX(dob) FROM student) OR dob = (SELECT MIN(dob) FROM student);

-- M9 : Views and sub-queries
CREATE VIEW toppers AS
    SELECT name, section, marks, grade
    FROM student
    WHERE marks >= 80;
SELECT * FROM toppers ORDER BY marks DESC;
SELECT name, marks
FROM student
WHERE marks > (SELECT AVG(marks) FROM student)
ORDER BY marks DESC;
SELECT name, section
FROM student
WHERE student_id NOT IN (SELECT student_id FROM activity);
SELECT section, name, marks
FROM student s1
WHERE marks = (SELECT MAX(marks) FROM student s2 WHERE s2.section = s1.section)
ORDER BY section;

-- M10 : Formatted report card
SELECT student_id AS Roll,
       CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTR(name, 2))) AS Name,
       section AS Sec,
       marks AS Marks,
       grade AS Grade,
       IF(marks >= 33, 'PASS', 'FAIL') AS Result
FROM student
ORDER BY section, marks DESC;
SELECT section,
       SUM(IF(marks >= 33, 1, 0)) AS Passed,
       SUM(IF(marks < 33, 1, 0)) AS Failed,
       ROUND(SUM(IF(marks >= 33, 1, 0)) / COUNT(*) * 100, 1) AS Pass_Percent
FROM student
GROUP BY section;

        
  1. Start
  2. CREATE DATABASE kv_office and USE it
  3. CREATE TABLE student and activity with constraints
  4. INSERT records into both tables
  5. Run selection and conditional queries
  6. Run aggregate queries with GROUP BY and HAVING
  7. ALTER TABLE, UPDATE grade, DELETE a record
  8. Run function and join queries
  9. Stop
#Test case / inputExpected resultStatus
1Top 5 scorers5 rows in descending order of marksPASS
2Section-wise strengthA 5, B 5, C 5PASS
3Birthday in July4 studentsPASS
4marks BETWEEN 60 AND 80Students in range listedPASS
5city IS NULLStudents without city shownPASS
6HAVING AVG(marks) > 65Only qualifying sectionsPASS
7UPDATE grades then GROUP BY gradeGrade-wise countsPASS
8Insert marks 105Rejected by CHECK constraint (error shown)PASS
9Equi-joinStudent names with their clubsPASS
10DELETE student 7 and COUNT14 students remainPASS
โš  Limitations
  • Static data typed in the script
  • No front-end; queries are run in the MySQL client
  • Only two tables
  • CHECK constraint needs MySQL 8.0.16+
๐Ÿš€ Future scope
  • Python front-end with mysql.connector (Class XII)
  • Add fee and attendance tables
  • Views for report cards
  • Export reports to CSV

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
๐Ÿ“Œ SCHOOL STUDENT DATABASE (MySQL) - Class XI Informatics Practices / M1 : Create database and tables
1
DDL ยท structure
DROP DATABASE IF EXISTS kv_office;

Deletes the database kv_office completely (structure + data). It cannot be undone.

โœ” Result: Query OK, 0 rows affected
2
DDL ยท structure
CREATE DATABASE kv_office;

Creates a new, empty database (a folder for tables) named kv_office.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
3
Command
USE kv_office;

Selects the database kv_office - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
4
DDL ยท structure
CREATE TABLE student (
    student_id INT PRIMARY KEY,
    name       VARCHAR(30) NOT NULL,
    section    CHAR(1),
    gender     CHAR(1),
    dob        DATE,
    marks      DECIMAL(5,2) CHECK (marks BETWEEN 0 AND 100),
    city       VARCHAR(20)
);

Creates a new table student with 7 columns. Each column gets a name and a data type:

  • student_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • name โ†’ VARCHAR(30) (text up to 30 characters); NOT NULL - must be filled
  • section โ†’ CHAR(1) (text up to 1 characters)
  • gender โ†’ CHAR(1) (text up to 1 characters)
  • dob โ†’ DATE (date (YYYY-MM-DD))
  • marks โ†’ DECIMAL(5,2) (decimal number, 5 digits in all with 2 after the point); CHECK (marks BETWEEN 0 AND 100) - other values are refused
  • city โ†’ VARCHAR(20) (text up to 20 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
5
DDL ยท structure
CREATE TABLE activity (
    act_id     INT PRIMARY KEY,
    student_id INT,
    club       VARCHAR(20),
    position   VARCHAR(15) DEFAULT 'Member'
);

Creates a new table activity with 4 columns. Each column gets a name and a data type:

  • act_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • student_id โ†’ INT (whole numbers)
  • club โ†’ VARCHAR(20) (text up to 20 characters)
  • position โ†’ VARCHAR(15) (text up to 15 characters); DEFAULT 'Member' - used when no value is given
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
6
Query ยท read only
DESC student;

Shows the STRUCTURE of table student: every column with its data type, NULL allowed or not, key and default value.

  • No data rows are shown - only the design of the table.
โœ” Result: 7 rows in set
๐Ÿ“Œ M2 : Insert records
7
DML ยท data change
INSERT INTO student VALUES
(1,'Amit','A','M','2009-07-14',88.5,'Delhi'),   (2,'Sara','B','F','2009-03-02',92.0,'Noida'),
(3,'Rahul','A','M','2009-07-25',65.5,'Delhi'),  (4,'Priya','B','F','2009-11-19',78.0,NULL),
(5,'Karan','A','M','2009-01-08',35.0,'Gurugram'),(6,'Neha','C','F','2009-07-30',81.5,'Delhi'),
(7,'Vikas','C','M','2008-12-12',29.0,NULL),     (8,'Anita','B','F','2009-05-21',70.0,'Faridabad'),
(9,'Imran','C','M','2009-09-09',94.5,'Delhi'),  (10,'Pooja','A','F','2009-02-17',47.0,'Noida'),
(11,'Farhan','B','M','2009-07-03',58.5,'Delhi'),(12,'Tina','C','F','2009-10-28',66.0,'Gurugramโ€ฆ

Adds 15 new rows into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 15 rows affected ยท Records: 15 Duplicates: 0 Warnings: 0
8
DML ยท data change
INSERT INTO activity (act_id, student_id, club, position) VALUES
(1,1,'Robotics','Captain'), (2,2,'Eco Club','Secretary'), (3,9,'Robotics','Member'),
(4,6,'Music','Member'), (5,14,'Eco Club','Member'), (6,3,'Sports','Vice Captain'),
(7,13,'Sports','Captain'), (8,2,'Robotics','Member'), (9,11,'Music','Leader'),
(10,8,'Literary','Editor');
โ€ฆ (1 more INSERT statement of the same kind)

These 2 INSERT statements add 2 rows, one row each, into table activity.

  • Values go into the listed columns (act_id, student_id, club, position) in the same order; other columns get NULL/default.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: each INSERT says "Query OK, 1 row affected"
9
DML ยท data change
INSERT INTO student VALUES (16,'Test','A','M','2009-01-01',105,'Delhi');

Adds one new row into table student.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: ERROR 3819 (HY000): Check constraint 'student_chk_1' is violated.
๐Ÿ“Œ M3 : Simple queries
10
Query ยท read only
SELECT * FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 15 rows in set
11
Query ยท read only
SELECT name, marks FROM student ORDER BY marks DESC LIMIT 5;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT name, marks โ†’ picks the columns / calculates the values to show.
  3. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
  4. LIMIT 5 โ†’ shows only the first 5 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
12
Query ยท read only
SELECT DISTINCT city FROM student;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT city โ†’ picks the columns / calculates the values to show.
  3. DISTINCT โ†’ removes repeated rows, so each value appears only once.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
13
Query ยท read only
SELECT name AS Student, section AS Sec, marks AS Score FROM student WHERE section = 'B' ORDER BY name;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE section = 'B' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name AS Student, section AS Sec, marks AS Score โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. ORDER BY name โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
๐Ÿ“Œ M4 : Conditional queries
14
Query ยท read only
SELECT name, dob FROM student WHERE MONTH(dob) = 7;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE MONTH(dob) = 7 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, dob โ†’ picks the columns / calculates the values to show.
  4. Functions used: MONTH() takes the month number.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 4 rows in set
15
Query ยท read only
SELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks BETWEEN 60 AND 80 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, marks โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
16
Query ยท read only
SELECT name, city FROM student WHERE city IN ('Noida','Gurugram');

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE city IN ('Noida','Gurugram') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, city โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
17
Query ยท read only
SELECT name FROM student WHERE name LIKE '_a%';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE name LIKE '_a%' (_ = exactly one character, % = any number of characters) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 6 rows in set
18
Query ยท read only
SELECT name, section FROM student WHERE city IS NULL;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE city IS NULL โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, section โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 2 rows in set
19
Query ยท read only
SELECT name, marks FROM student WHERE marks < 40 OR (section = 'C' AND gender = 'F');

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks < 40 OR (section = 'C' AND gender = 'F') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, marks โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
๐Ÿ“Œ M5 : Aggregate functions, GROUP BY and HAVING
20
Query ยท read only
SELECT COUNT(*) AS Total, AVG(marks) AS Average, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT COUNT(*) AS Total, AVG(marks) AS Average, MAX(marks) AS Highest, MIN(marks) AS Lowest โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: COUNT(*) counts all rows; AVG() finds the average; MAX() finds the largest value; MIN() finds the smallest value.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 1 row in set
21
Query ยท read only
SELECT section, COUNT(*) AS Strength FROM student GROUP BY section;

Fetches rows from student, grouped by section.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY section โ†’ makes groups: rows with the same section go into one group (one output row per group).
  3. SELECT section, COUNT(*) AS Strength โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 3 rows in set
22
Query ยท read only
SELECT section, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student GROUP BY section;

Fetches rows from student, grouped by section.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY section โ†’ makes groups: rows with the same section go into one group (one output row per group).
  3. SELECT section, MAX(marks) AS Highest, MIN(marks) AS Lowest โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: MAX() finds the largest value; MIN() finds the smallest value.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 3 rows in set
23
Query ยท read only
SELECT gender, ROUND(AVG(marks),2) AS Avg_Marks FROM student GROUP BY gender;

Fetches rows from student, grouped by gender.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY gender โ†’ makes groups: rows with the same gender go into one group (one output row per group).
  3. SELECT gender, ROUND(AVG(marks),2) AS Avg_Marks โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 2 rows in set
24
Query ยท read only
SELECT section, ROUND(AVG(marks),2) AS Average FROM student GROUP BY section HAVING AVG(marks) > 65;

Fetches rows from student, grouped by section.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY section โ†’ makes groups: rows with the same section go into one group (one output row per group).
  3. HAVING AVG(marks) > 65 โ†’ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
  4. SELECT section, ROUND(AVG(marks),2) AS Average โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 1 row in set
25
Query ยท read only
SELECT city, COUNT(*) AS Students FROM student WHERE city IS NOT NULL GROUP BY city ORDER BY Students DESC;

Fetches rows from student that satisfy a condition, grouped by city, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE city IS NOT NULL โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. GROUP BY city โ†’ makes groups: rows with the same city go into one group (one output row per group).
  4. SELECT city, COUNT(*) AS Students โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: COUNT(*) counts all rows.
  6. ORDER BY Students DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 4 rows in set
๐Ÿ“Œ M6 : String, numeric and date functions
26
Query ยท read only
SELECT UPPER(name) AS Name, LENGTH(name) AS Letters, SUBSTR(name,1,3) AS Short FROM student WHERE section = 'A';

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE section = 'A' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT UPPER(name) AS Name, LENGTH(name) AS Letters, SUBSTR(name,1,3) AS Short โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: UPPER() changes text to capitals; LENGTH() counts characters; SUBSTR(text, start, n) takes n characters from position start.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
27
Query ยท read only
SELECT CONCAT(name, ' (', section, ')') AS Student, ROUND(marks/100*500) AS Out_of_500 FROM student LIMIT 6;

Fetches rows from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT CONCAT(name, ' (', section, ')') AS Student, ROUND(marks/100*500) AS Out_of_500 โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: CONCAT() joins texts together; ROUND(x, d) rounds x to d decimal places.
  4. LIMIT 6 โ†’ shows only the first 6 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 6 rows in set
28
Query ยท read only
SELECT name, YEAR(dob) AS Birth_Year, MONTHNAME(dob) AS Month FROM student WHERE YEAR(dob) = 2008;

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE YEAR(dob) = 2008 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, YEAR(dob) AS Birth_Year, MONTHNAME(dob) AS Month โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: YEAR() takes the year from a date; MONTHNAME() gives the month name.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 2 rows in set
29
Query ยท read only
SELECT name, DATEDIFF('2026-04-01', dob) DIV 365 AS Age_on_1_April FROM student ORDER BY dob LIMIT 5;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT name, DATEDIFF('2026-04-01', dob) DIV 365 AS Age_on_1_April โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: DATEDIFF(d1, d2) gives days between two dates.
  4. ORDER BY dob โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
  5. LIMIT 5 โ†’ shows only the first 5 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscity
1AmitAM2009-07-1488.50Delhi
2SaraBF2009-03-0292.00Noida
3RahulAM2009-07-2565.50Delhi
4PriyaBF2009-11-1978.00NULL
5KaranAM2009-01-0835.00Gurugram
6NehaCF2009-07-3081.50Delhi
7VikasCM2008-12-1229.00NULL
8AnitaBF2009-05-2170.00Faridabad
9ImranCM2009-09-0994.50Delhi
10PoojaAF2009-02-1747.00Noida
11FarhanBM2009-07-0358.50Delhi
12TinaCF2009-10-2866.00Gurugram
13GauravAM2008-08-1573.50Delhi
14DivyaBF2009-04-0485.00Noida
+ 1 more rows
โœ” Result: 5 rows in set
๐Ÿ“Œ M7 : ALTER, UPDATE and DELETE
30
DDL ยท structure
ALTER TABLE student ADD grade CHAR(2);

Changes the STRUCTURE (design) of table student: adds a new column grade (existing rows get NULL in it).

  • Data in other columns is not touched.
โœ” Result: Query OK, 0 rows affected ยท Records: 0 Duplicates: 0 Warnings: 0
31
DML ยท data change
UPDATE student SET grade = 'A1' WHERE marks >= 90;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE marks >= 90 โ†’ finds only the rows that match.
  3. SET grade = 'A1' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE marks >= 90 โ†’ 2 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiNULL
2SaraBF2009-03-0292.00NoidaNULLโœŽ
3RahulAM2009-07-2565.50DelhiNULL
4PriyaBF2009-11-1978.00NULLNULL
5KaranAM2009-01-0835.00GurugramNULL
6NehaCF2009-07-3081.50DelhiNULL
7VikasCM2008-12-1229.00NULLNULL
8AnitaBF2009-05-2170.00FaridabadNULL
9ImranCM2009-09-0994.50DelhiNULLโœŽ
10PoojaAF2009-02-1747.00NoidaNULL
11FarhanBM2009-07-0358.50DelhiNULL
12TinaCF2009-10-2866.00GurugramNULL
13GauravAM2008-08-1573.50DelhiNULL
14DivyaBF2009-04-0485.00NoidaNULL
+ 1 more rows
โœ” Result: Query OK, 2 rows affected ยท Rows matched: 2 Changed: 2 Warnings: 0
32
DML ยท data change
UPDATE student SET grade = 'A2' WHERE marks >= 75 AND marks < 90;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE marks >= 75 AND marks < 90 โ†’ finds only the rows that match.
  3. SET grade = 'A2' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE marks >= 75 AND marks < 90 โ†’ 4 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiNULLโœŽ
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiNULL
4PriyaBF2009-11-1978.00NULLNULLโœŽ
5KaranAM2009-01-0835.00GurugramNULL
6NehaCF2009-07-3081.50DelhiNULLโœŽ
7VikasCM2008-12-1229.00NULLNULL
8AnitaBF2009-05-2170.00FaridabadNULL
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaNULL
11FarhanBM2009-07-0358.50DelhiNULL
12TinaCF2009-10-2866.00GurugramNULL
13GauravAM2008-08-1573.50DelhiNULL
14DivyaBF2009-04-0485.00NoidaNULLโœŽ
+ 1 more rows
โœ” Result: Query OK, 4 rows affected ยท Rows matched: 4 Changed: 4 Warnings: 0
33
DML ยท data change
UPDATE student SET grade = 'B'  WHERE marks >= 60 AND marks < 75;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE marks >= 60 AND marks < 75 โ†’ finds only the rows that match.
  3. SET grade = 'B' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE marks >= 60 AND marks < 75 โ†’ 4 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiNULLโœŽ
4PriyaBF2009-11-1978.00NULLA2
5KaranAM2009-01-0835.00GurugramNULL
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00NULLNULL
8AnitaBF2009-05-2170.00FaridabadNULLโœŽ
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaNULL
11FarhanBM2009-07-0358.50DelhiNULL
12TinaCF2009-10-2866.00GurugramNULLโœŽ
13GauravAM2008-08-1573.50DelhiNULLโœŽ
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: Query OK, 4 rows affected ยท Rows matched: 4 Changed: 4 Warnings: 0
34
DML ยท data change
UPDATE student SET grade = 'C'  WHERE marks >= 40 AND marks < 60;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE marks >= 40 AND marks < 60 โ†’ finds only the rows that match.
  3. SET grade = 'C' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE marks >= 40 AND marks < 60 โ†’ 2 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00NULLA2
5KaranAM2009-01-0835.00GurugramNULL
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00NULLNULL
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaNULLโœŽ
11FarhanBM2009-07-0358.50DelhiNULLโœŽ
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: Query OK, 2 rows affected ยท Rows matched: 2 Changed: 2 Warnings: 0
35
DML ยท data change
UPDATE student SET grade = 'D'  WHERE marks < 40;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE marks < 40 โ†’ finds only the rows that match.
  3. SET grade = 'D' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE marks < 40 โ†’ 3 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00NULLA2
5KaranAM2009-01-0835.00GurugramNULLโœŽ
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00NULLNULLโœŽ
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: Query OK, 3 rows affected ยท Rows matched: 3 Changed: 3 Warnings: 0
36
Query ยท read only
SELECT grade, COUNT(*) AS Students FROM student GROUP BY grade ORDER BY grade;

Fetches rows from student, grouped by grade, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY grade โ†’ makes groups: rows with the same grade go into one group (one output row per group).
  3. SELECT grade, COUNT(*) AS Students โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
  5. ORDER BY grade โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 15 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00NULLA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00NULLD
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: 5 rows in set
37
DML ยท data change
UPDATE student SET city = 'Delhi' WHERE city IS NULL;

Changes existing data in table student.

  1. UPDATE student โ†’ picks the table.
  2. WHERE city IS NULL โ†’ finds only the rows that match.
  3. SET city = 'Delhi' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE city IS NULL โ†’ 2 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00NULLA2โœŽ
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00NULLDโœŽ
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: Query OK, 2 rows affected ยท Rows matched: 2 Changed: 2 Warnings: 0
38
DML ยท data change
DELETE FROM student WHERE student_id = 7;

Removes rows from table student.

  1. FROM student โ†’ picks the table.
  2. WHERE student_id = 7 โ†’ finds the matching rows.
  3. Those rows are removed permanently โ†’ "Query OK, n rows affected".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE student_id = 7 โ†’ 1 row(s) matched.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
7VikasCM2008-12-1229.00DelhiD๐Ÿ—‘
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
+ 1 more rows
โœ” Result: Query OK, 1 row affected
39
Query ยท read only
SELECT COUNT(*) AS Remaining FROM student;

Fetches the summary values from student.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT COUNT(*) AS Remaining โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 1 row in set
๐Ÿ“Œ M8 : Equi-join of two tables
40
Query ยท read only
SELECT s.name, s.section, a.club, a.position
FROM student s, activity a
WHERE s.student_id = a.student_id
ORDER BY a.club, s.name;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student s, activity a โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE s.student_id = a.student_id โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT s.name, s.section, a.club, a.position โ†’ picks the columns / calculates the values to show.
  4. ORDER BY a.club, s.name โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: The tables are joined: student s, activity a โ†’ 168 combined rows.

student_idnamesectiongenderdobmarkscitygradeact_idstudent_idclubposition
1AmitAM2009-07-1488.5DelhiA211RoboticsCaptain
1AmitAM2009-07-1488.5DelhiA222Eco ClubSecretary
1AmitAM2009-07-1488.5DelhiA239RoboticsMember
1AmitAM2009-07-1488.5DelhiA246MusicMember
1AmitAM2009-07-1488.5DelhiA2514Eco ClubMember
1AmitAM2009-07-1488.5DelhiA263SportsVice Captain
1AmitAM2009-07-1488.5DelhiA2713SportsCaptain
1AmitAM2009-07-1488.5DelhiA282RoboticsMember
1AmitAM2009-07-1488.5DelhiA2911MusicLeader
1AmitAM2009-07-1488.5DelhiA2108LiteraryEditor
1AmitAM2009-07-1488.5DelhiA2114LiteraryMember
1AmitAM2009-07-1488.5DelhiA21212Eco ClubMember
2SaraBF2009-03-0292NoidaA111RoboticsCaptain
2SaraBF2009-03-0292NoidaA122Eco ClubSecretary
+ 154 more rows
โœ” Result: 12 rows in set
41
Query ยท read only
SELECT a.club, COUNT(*) AS Members, ROUND(AVG(s.marks),2) AS Avg_Marks
FROM student s, activity a
WHERE s.student_id = a.student_id
GROUP BY a.club;

Fetches rows from student that satisfy a condition, grouped by a.club.

  1. FROM student s, activity a โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE s.student_id = a.student_id โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. GROUP BY a.club โ†’ makes groups: rows with the same a.club go into one group (one output row per group).
  4. SELECT a.club, COUNT(*) AS Members, ROUND(AVG(s.marks),2) AS Avg_Marks โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: The tables are joined: student s, activity a โ†’ 168 combined rows.

student_idnamesectiongenderdobmarkscitygradeact_idstudent_idclubposition
1AmitAM2009-07-1488.5DelhiA211RoboticsCaptain
1AmitAM2009-07-1488.5DelhiA222Eco ClubSecretary
1AmitAM2009-07-1488.5DelhiA239RoboticsMember
1AmitAM2009-07-1488.5DelhiA246MusicMember
1AmitAM2009-07-1488.5DelhiA2514Eco ClubMember
1AmitAM2009-07-1488.5DelhiA263SportsVice Captain
1AmitAM2009-07-1488.5DelhiA2713SportsCaptain
1AmitAM2009-07-1488.5DelhiA282RoboticsMember
1AmitAM2009-07-1488.5DelhiA2911MusicLeader
1AmitAM2009-07-1488.5DelhiA2108LiteraryEditor
1AmitAM2009-07-1488.5DelhiA2114LiteraryMember
1AmitAM2009-07-1488.5DelhiA21212Eco ClubMember
2SaraBF2009-03-0292NoidaA111RoboticsCaptain
2SaraBF2009-03-0292NoidaA122Eco ClubSecretary
+ 154 more rows
โœ” Result: 5 rows in set
42
Query ยท read only
SELECT name, dob FROM student WHERE dob = (SELECT MAX(dob) FROM student) OR dob = (SELECT MIN(dob) FROM student);

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE dob = (SELECT MAX(dob) FROM student) OR dob = (SELECT MIN(dob) FROM student) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, dob โ†’ picks the columns / calculates the values to show.
  4. Functions used: MAX() finds the largest value; MIN() finds the smallest value.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 2 rows in set
๐Ÿ“Œ M9 : Views and sub-queries
43
DDL ยท structure
CREATE VIEW toppers AS
    SELECT name, section, marks, grade
    FROM student
    WHERE marks >= 80;

Creates a VIEW toppers - a saved SELECT query that behaves like a virtual table.

  • The query saved inside the view: Fetches rows from student that satisfy a condition.
  • FROM student โ†’ MySQL first opens table student and looks at all its rows.
  • WHERE marks >= 80 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  • SELECT name, section, marks, grade โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: Query OK, 0 rows affected
44
Query ยท read only
SELECT * FROM toppers ORDER BY marks DESC;

Fetches rows from toppers, in sorted order.

  1. FROM toppers โ†’ MySQL first opens table toppers and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
  3. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
โœ” Result: 5 rows in set
45
Query ยท read only
SELECT name, marks
FROM student
WHERE marks > (SELECT AVG(marks) FROM student)
ORDER BY marks DESC;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks > (SELECT AVG(marks) FROM student) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, marks โ†’ picks the columns / calculates the values to show.
  4. Functions used: AVG() finds the average.
  5. ORDER BY marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 8 rows in set
46
Query ยท read only
SELECT name, section
FROM student
WHERE student_id NOT IN (SELECT student_id FROM activity);

Fetches rows from student that satisfy a condition.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE student_id NOT IN (SELECT student_id FROM activity) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT name, section โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 3 rows in set
47
Query ยท read only
SELECT section, name, marks
FROM student s1
WHERE marks = (SELECT MAX(marks) FROM student s2 WHERE s2.section = s1.section)
ORDER BY section;

Fetches rows from student that satisfy a condition, in sorted order.

  1. FROM student s1 โ†’ MySQL first opens table student and looks at all its rows.
  2. WHERE marks = (SELECT MAX(marks) FROM student s2 WHERE s2.section = s1.section) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT section, name, marks โ†’ picks the columns / calculates the values to show.
  4. Functions used: MAX() finds the largest value.
  5. ORDER BY section โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 3 rows in set
๐Ÿ“Œ M10 : Formatted report card
48
Query ยท read only
SELECT student_id AS Roll,
       CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTR(name, 2))) AS Name,
       section AS Sec,
       marks AS Marks,
       grade AS Grade,
       IF(marks >= 33, 'PASS', 'FAIL') AS Result
FROM student
ORDER BY section, marks DESC;

Fetches rows from student, in sorted order.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. SELECT student_id AS Roll, CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTR(name, 2))) AS Name, section AS Sec, marks AS Marks, grade AS Grade, IF(marks >= 33, 'PASS', 'FAIL') AS Result โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: CONCAT() joins texts together; UPPER() changes text to capitals; LEFT(text, n) takes n characters from the left; LOWER() changes text to small letters; SUBSTR(text, start, n) takes n characters from position start.
  4. ORDER BY section, marks DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 14 rows in set
49
Query ยท read only
SELECT section,
       SUM(IF(marks >= 33, 1, 0)) AS Passed,
       SUM(IF(marks < 33, 1, 0)) AS Failed,
       ROUND(SUM(IF(marks >= 33, 1, 0)) / COUNT(*) * 100, 1) AS Pass_Percent
FROM student
GROUP BY section;

Fetches rows from student, grouped by section.

  1. FROM student โ†’ MySQL first opens table student and looks at all its rows.
  2. GROUP BY section โ†’ makes groups: rows with the same section go into one group (one output row per group).
  3. SELECT section, SUM(IF(marks >= 33, 1, 0)) AS Passed, SUM(IF(marks < 33, 1, 0)) AS Failed, ROUND(SUM(IF(marks >= 33, 1, 0)) / COUNT(*) * 100, 1) AS Pass_Percent โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: SUM() adds the values; ROUND(x, d) rounds x to d decimal places; COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table student - all 14 rows are taken.

student_idnamesectiongenderdobmarkscitygrade
1AmitAM2009-07-1488.50DelhiA2
2SaraBF2009-03-0292.00NoidaA1
3RahulAM2009-07-2565.50DelhiB
4PriyaBF2009-11-1978.00DelhiA2
5KaranAM2009-01-0835.00GurugramD
6NehaCF2009-07-3081.50DelhiA2
8AnitaBF2009-05-2170.00FaridabadB
9ImranCM2009-09-0994.50DelhiA1
10PoojaAF2009-02-1747.00NoidaC
11FarhanBM2009-07-0358.50DelhiC
12TinaCF2009-10-2866.00GurugramB
13GauravAM2008-08-1573.50DelhiB
14DivyaBF2009-04-0485.00NoidaA2
15HarshCM2009-06-1139.50DelhiD
โœ” Result: 3 rows in set
Q1. What is the difference between CHAR and VARCHAR?

CHAR(n) always uses n characters (fixed length); VARCHAR(n) uses only as many as stored (variable length).

Q2. What does the CHECK constraint do?

It allows only values that satisfy a condition, e.g. marks BETWEEN 0 AND 100; other values are rejected.

Q3. What is an equi-join?

A join where rows of two tables are combined on equal values of a common column, e.g. student.student_id = activity.student_id.

Q4. Difference between DELETE and DROP?

DELETE removes rows (data) and keeps the table; DROP removes the whole table or database with its structure.

Q5. What does LIKE '_a%' mean?

Names whose second character is 'a'; _ matches one character and % matches any number of characters.

05

Geography Quiz โ€” States & Capitals

PYTHONDictionary (Practical 18)random modulescoring logic
๐Ÿ“ 93 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 160 output lines๐Ÿ“„ 25+ page report

Use the states-capitals dictionary to auto-generate random questions, take user answers, and display a final score out of 10 โ€” a genuinely fun classroom quiz tool.

โœจ Features
  • Quiz on States & Capitals, Union Territories and Rivers of India
  • Multiple-choice options generated randomly from the data
  • Score, accuracy % and time bonus per round
  • Practice mode (shows the answer) and test mode
  • Leader board of players
  • Review of wrong answers at the end of each quiz
โ˜ฐ Main menu
1States & Capitals Quiz5 random questions on capitals of states
2UT QuizCapitals of Union Territories
3Rivers QuizWhich state / city is on which river
4Practice ModeShows state and capital pairs for revision
5Leader BoardBest scores of all players
6Search CapitalFinds the capital of a state or UT
0ExitEnds the quiz
๐ŸŽฏ Objectives
  • Use a dictionary as a question bank
  • Shuffle and slice a list with the random module
  • Compare strings ignoring case using lower() and strip()
๐Ÿ“š Data dictionary
NameTypePurpose
STATESdictState -> capital
UTSdictUnion Territory -> capital
RIVERSdictCity -> river on which it is situated
boarddictPlayer -> best score
Why it matters: Combines dictionary practicals with basic game-design thinking.
# =====================================================================
#   GEOGRAPHY QUIZ - STATES, CAPITALS, UTs & RIVERS OF INDIA
#   Concepts : dictionaries, lists, random module (sample, shuffle),
#              loops, functions, string methods
# =====================================================================
import random

STATES = {"Delhi": "New Delhi", "Maharashtra": "Mumbai", "Rajasthan": "Jaipur", "Punjab": "Chandigarh",
          "Kerala": "Thiruvananthapuram", "Gujarat": "Gandhinagar", "Bihar": "Patna", "Assam": "Dispur",
          "Goa": "Panaji", "Odisha": "Bhubaneswar", "Karnataka": "Bengaluru", "Tamil Nadu": "Chennai",
          "West Bengal": "Kolkata", "Telangana": "Hyderabad", "Uttarakhand": "Dehradun", "Sikkim": "Gangtok"}
UTS = {"Ladakh": "Leh", "Puducherry": "Puducherry", "Andaman and Nicobar Islands": "Sri Vijaya Puram",
       "Lakshadweep": "Kavaratti", "Jammu and Kashmir": "Srinagar (summer)", "Chandigarh UT": "Chandigarh"}
RIVERS = {"Varanasi": "Ganga", "Agra": "Yamuna", "Guwahati": "Brahmaputra", "Ahmedabad": "Sabarmati",
          "Hyderabad": "Musi", "Lucknow": "Gomti", "Kolkata": "Hooghly", "Srinagar": "Jhelum"}
board = {}


def quiz(bank, title, question):
    """Asks 5 multiple-choice questions from a dictionary."""
    keys = random.sample(list(bank), 5)
    values = list(set(bank.values()))
    score, wrong = 0, []
    print(f"\n--- {title} ---")
    for i, k in enumerate(keys, 1):
        correct = bank[k]
        opts = random.sample([v for v in values if v != correct], 3) + [correct]
        random.shuffle(opts)
        print(f"Q{i}. {question.format(k)}")
        for letter, o in zip("ABCD", opts):
            print(f"    {letter}) {o}")
        ans = input("Your option: ").strip().upper()
        if ans not in "ABCD" or len(ans) != 1:
            print("Choose A, B, C or D. Counted as wrong.")
            wrong.append((k, correct))
        elif opts["ABCD".index(ans)] == correct:
            print("Correct!")
            score += 1
        else:
            print("Wrong! Answer:", correct)
            wrong.append((k, correct))
    print(f"Score {score}/5  Accuracy {score * 20}%")
    if wrong:
        print("Review:", "; ".join(f"{k} -> {v}" for k, v in wrong))
    board[player] = max(board.get(player, 0), score)


def practice():
    """Shows pairs for revision."""
    for i, (s, c) in enumerate(sorted(STATES.items()), 1):
        print(f"{s:<12}: {c:<20}", end="\n" if i % 2 == 0 else "")


def leader_board():
    """Best scores."""
    for i, (n, s) in enumerate(sorted(board.items(), key=lambda x: -x[1]), 1):
        print(f"{i}. {n:<10} {s}/5  " + "*" * s)


def search():
    """Finds capital of a state / UT."""
    k = input("State / UT name: ").strip().title()
    ans = STATES.get(k) or UTS.get(k)
    print(f"Capital of {k}: {ans}" if ans else "Not found.")


print("=" * 50)
print("INDIA GEOGRAPHY QUIZ".center(50))
print("=" * 50)
player = input("Player name: ").strip().title()
board[player] = 0
while True:
    print("\n1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "1":
        quiz(STATES, "STATES & CAPITALS", "What is the capital of {}?")
    elif ch == "2":
        quiz(UTS, "UNION TERRITORIES", "What is the capital of {}?")
    elif ch == "3":
        quiz(RIVERS, "RIVER CITIES", "{} is situated on which river?")
    elif ch == "4":
        practice()
    elif ch == "5":
        leader_board()
    elif ch == "6":
        search()
    elif ch == "0":
        leader_board()
        print("Jai Hind! Keep exploring India.")
        break
    else:
        print("Invalid choice")

        
  1. Start
  2. Read player name
  3. Display menu and read choice
  4. Choice is a quiz? → No: practice / leader board / search
  5. Pick 5 random questions; make 4 options
  6. Ask question and read option A-D
  7. Answer correct? → No: store for review
  8. Score and accuracy; update leader board
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Correct option'Correct!' and score + 1PASS
2Wrong optionCorrect answer shown, kept for reviewPASS
3Option 'Z''Choose A, B, C or D' and counted wrongPASS
4Search 'Kerala'ThiruvananthapuramPASS
5Search unknown state'Not found'PASS
6Leader boardPlayers sorted by best scorePASS
7Rivers quizCity-river questions askedPASS
8Practice modePairs displayedPASS
โš  Limitations
  • Fixed question bank inside the program
  • No timer in seconds (console)
  • Scores are lost on exit
  • English only
๐Ÿš€ Future scope
  • Load questions from a CSV file
  • Add a map image with Matplotlib
  • Hindi language option
  • Online leader board

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): random - random number functions are loaded.
  2. Global variables / constants are created: STATES, UTS, RIVERS, board.
  3. 4 functions are defined (lines 19โ€“64) - Python stores them but does NOT run them yet.
  4. Main program starts at line 67: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
quiz(bank, title, question)19โ€“45Asks 5 multiple-choice questions from a dictionary.main program
practice()48โ€“51Shows pairs for revision.main program
leader_board()54โ€“57Best scores.main program
search()60โ€“64Finds capital of a state / UT.main program
โ‘ข Main program - line by line
LineCodeWhat it does
67
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
68
print("INDIA GEOGRAPHY QUIZ".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "INDIA GEOGRAPHY QUIZ".center(50) on the screen
69
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
70
player = input("Player name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable player
71
board[player] = 0
๐Ÿงฎ Store / Calculate Puts the number 0 into board[player] (item player of board)
72
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
73
print("\n1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.States 2.UTs 3.Rivers 4.Practicโ€ฆ" on the screen
74
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
75
if ch == "1":
๐Ÿ”€ Decision CHECKS whether ch is equal to "1". If True, the indented lines below run; otherwise Python jumps to the elif/else part
76
quiz(STATES, "STATES & CAPITALS", "What is the capital of {}?")
๐Ÿงฎ Store / Calculate Calls our own function quiz(STATES, "STATES & CAPITALS", "What is the capitaโ€ฆ) - asks 5 multiple-choice questions from a dictionary
77
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
78
quiz(UTS, "UNION TERRITORIES", "What is the capital of {}?")
๐Ÿงฎ Store / Calculate Calls our own function quiz(UTS, "UNION TERRITORIES", "What is the capitaโ€ฆ) - asks 5 multiple-choice questions from a dictionary
79
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
80
quiz(RIVERS, "RIVER CITIES", "{} is situated on which river?")
๐Ÿงฎ Store / Calculate Calls our own function quiz(RIVERS, "RIVER CITIES", "{} is situated on โ€ฆ) - asks 5 multiple-choice questions from a dictionary
81
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
82
practice()
๐Ÿงฎ Store / Calculate Calls our own function practice() - shows pairs for revision
83
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
84
leader_board()
๐Ÿงฎ Store / Calculate Calls our own function leader_board() - best scores
85
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
86
search()
๐Ÿงฎ Store / Calculate Calls our own function search() - finds capital of a state / ut
87
elif ch == "0":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "0"
88
leader_board()
๐Ÿงฎ Store / Calculate Calls our own function leader_board() - best scores
89
print("Jai Hind! Keep exploring India.")
๐Ÿ–ฅ๏ธ Output Displays the text "Jai Hind! Keep exploring India." on the screen
90
break
๐Ÿ” Loop BREAK - leaves the loop immediately
91
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
92
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: INDIA GEOGRAPHY QUIZ
  2. You type Diya at Player name:
    shows: 1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
  3. You type 4 at Enter choice:
    runs: practice()
    shows: Assam : Dispur Bihar : Patna (+8 more lines)
  4. You type 1 at Enter choice:
    runs: quiz()
    shows: --- STATES & CAPITALS --- (+5 more lines)
  5. You type B at Your option:
    shows: Wrong! Answer: Chandigarh (+5 more lines)
  6. You type A at Your option:
    shows: Wrong! Answer: Gandhinagar (+5 more lines)
  7. You type C at Your option:
    shows: Wrong! Answer: Panaji (+5 more lines)
  8. You type D at Your option:
    shows: Correct! (+5 more lines)
  9. You type B at Your option:
    shows: Correct! (+3 more lines)
  10. You type 2 at Enter choice:
    runs: quiz()
    shows: --- UNION TERRITORIES --- (+5 more lines)
  11. You type A at Your option:
    shows: Wrong! Answer: Chandigarh (+5 more lines)
  12. You type Z at Your option:
    shows: Choose A, B, C or D. Counted as wrong. (+5 more lines)
  13. You type C at Your option:
    shows: Wrong! Answer: Leh (+5 more lines)
  14. You type B at Your option:
    shows: Wrong! Answer: Sri Vijaya Puram (+5 more lines)
  15. You type D at Your option:
    shows: Wrong! Answer: Puducherry (+3 more lines)
  16. You type 3 at Enter choice:
    runs: quiz()
    shows: --- RIVER CITIES --- (+5 more lines)
  17. You type A at Your option:
    shows: Wrong! Answer: Hooghly (+5 more lines)
  18. You type B at Your option:
    shows: Wrong! Answer: Sabarmati (+5 more lines)
  19. You type C at Your option:
    shows: Correct! (+5 more lines)
  20. You type A at Your option:
    shows: Wrong! Answer: Jhelum (+5 more lines)
  21. You type B at Your option:
    shows: Wrong! Answer: Gomti (+3 more lines)
  22. You type 6 at Enter choice:
    runs: search()
  23. You type kerala at State / UT name:
    shows: Capital of Kerala: Thiruvananthapuram (+1 more lines)
  24. You type 6 at Enter choice:
    runs: search()
  25. You type Atlantis at State / UT name:
    shows: Not found. (+1 more lines)
  26. You type 5 at Enter choice:
    runs: leader_board()
    shows: 1. Diya 2/5 ** (+1 more lines)
  27. You type 0 at Enter choice:
    runs: leader_board()
    shows: 1. Diya 2/5 ** (+1 more lines)
โ‘ค Inside each function - line by line
quiz() - lines 19โ€“45
LineCodeWhat it does
19
def quiz(bank, title, question):
๐Ÿงฉ Function DEFINES a function quiz(bank, title, question). Python only remembers it here - its body runs later, each time quiz() is called.
21
keys = random.sample(list(bank), 5)
๐Ÿงฎ Store / Calculate Picks 5 random items from list(bank); the result is stored in variable keys
22
values = list(set(bank.values()))
๐Ÿงฎ Store / Calculate Makes a list from set(bank.values()); the result is stored in variable values
23
score, wrong = 0, []
๐Ÿงฎ Store / Calculate Stores 0, [] into score, wrong respectively
24
print(f"\n--- {title} ---")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\n--- {title} ---" with the values filled into { } on the screen
25
for i, k in enumerate(keys, 1):
๐Ÿ” Loop LOOP over keys with position: in each round i, k get (position, item)
26
correct = bank[k]
๐Ÿงฎ Store / Calculate Stores the item bank[k] in variable correct
27
opts = random.sample([v for v in values if v != correct], 3) + [correct]
๐Ÿงฎ Store / Calculate Stores the value of random.sample([v for v in values if v != corrโ€ฆ (calculated using +) in variable opts
28
random.shuffle(opts)
๐Ÿงฎ Store / Calculate Shuffles (mixes) the items of opts randomly
29
print(f"Q{i}. {question.format(k)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Q{i}. {question.format(k)}" with the values filled into { } on the screen
30
for letter, o in zip("ABCD", opts):
๐Ÿ” Loop LOOP that walks through "ABCD", opts together; letter, o get one item from each
31
print(f"    {letter}) {o}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {letter}) {o}" with the values filled into { } on the screen
32
ans = input("Your option: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable ans
33
if ans not in "ABCD" or len(ans) != 1:
๐Ÿ”€ Decision CHECKS whether (ans is not present in "ABCD" OR len(ans) is not equal to 1). If True, the indented lines below run; otherwise Python jumps to the elif/else part
34
print("Choose A, B, C or D. Counted as wrong.")
๐Ÿ–ฅ๏ธ Output Displays the text "Choose A, B, C or D. Counted as wโ€ฆ" on the screen
35
wrong.append((k, correct))
๐Ÿงฎ Store / Calculate Adds (k, correct) at the end of list wrong
36
elif opts["ABCD".index(ans)] == correct:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether opts["ABCD".index(ans)] is equal to correct
37
print("Correct!")
๐Ÿ–ฅ๏ธ Output Displays the text "Correct!" on the screen
38
score += 1
๐Ÿงฎ Store / Calculate Adds 1 to score (same as score = score + 1)
39
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
40
print("Wrong! Answer:", correct)
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong! Answer:", then the value of correct on the screen
41
wrong.append((k, correct))
๐Ÿงฎ Store / Calculate Adds (k, correct) at the end of list wrong
42
print(f"Score {score}/5  Accuracy {score * 20}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Score {score}/5 Accuracy {score * 20}%" with the values filled into { } on the screen
43
if wrong:
๐Ÿ”€ Decision CHECKS whether wrong is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
44
print("Review:", "; ".join(f"{k} -> {v}" for k, v in wrong))
๐Ÿ–ฅ๏ธ Output Displays the text "Review:", then the value of "; ".join(f"{k} -> {v}" for k, v in wrong) on the screen
45
board[player] = max(board.get(player, 0), score)
๐Ÿงฎ Store / Calculate Finds the largest value among board.get(player, 0), score; the result is put into board[player] (item player of board)
practice() - lines 48โ€“51
LineCodeWhat it does
48
def practice():
๐Ÿงฉ Function DEFINES a function practice(). Python only remembers it here - its body runs later, each time practice() is called.
50
for i, (s, c) in enumerate(sorted(STATES.items()), 1):
๐Ÿ” Loop LOOP over sorted(STATES.items()) with position: in each round i, (s, c) get (position, item)
51
print(f"{s:<12}: {c:<20}", end="\n" if i % 2 == 0 else "")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s:<12}: {c:<20}" with the values filled into { } on the screen (ends with "\n" if i % 2 == 0 else "" instead of a new line)
leader_board() - lines 54โ€“57
LineCodeWhat it does
54
def leader_board():
๐Ÿงฉ Function DEFINES a function leader_board(). Python only remembers it here - its body runs later, each time leader_board() is called.
56
for i, (n, s) in enumerate(sorted(board.items(), key=lambda x: -x[1]), 1):
๐Ÿ” Loop LOOP over sorted(board.items(), key=lambda x: -x[1]) with position: in each round i, (n, s) get (position, item)
57
print(f"{i}. {n:<10} {s}/5  " + "*" * s)
๐Ÿ–ฅ๏ธ Output Displays the value of f"{i}. {n:<10} {s}/5 " + "*" * s on the screen
search() - lines 60โ€“64
LineCodeWhat it does
60
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
62
k = input("State / UT name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable k
63
ans = STATES.get(k) or UTS.get(k)
๐Ÿงฎ Store / Calculate Stores the value of STATES.get(k), or UTS.get(k) if the first one is empty / None / 0 in variable ans
64
print(f"Capital of {k}: {ans}" if ans else "Not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of f"Capital of {k}: {ans}" if ans else "Not fouโ€ฆ on the screen
Q1. How are the four options created?

The correct answer plus three random wrong capitals chosen with random.sample() are shuffled with random.shuffle().

Q2. Why use random.sample() instead of choice() three times?

sample() returns distinct items, so options are never repeated.

Q3. How is the leader board updated?

board[name] = max(board.get(name, 0), score) keeps the best score of each player.

Q4. How are wrong answers reviewed?

Each wrong question is stored in a list of (question, correct answer) and printed after the quiz.

Q5. Why is the comparison case-insensitive in search?

title() converts the typed state name so 'kerala' and 'KERALA' both match 'Kerala'.

06

Electricity Bill Calculator

PYTHONSlab-wise if-elif logicfunctions returning multiple valuesdictionarystatistics module
๐Ÿ“ 139 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 119 output lines๐Ÿ“„ 25+ page report

Computes slab-wise energy charges, fixed charges and tax for several consumers, then prints bills, the highest bill and the average units consumed.

โœจ Features
  • Slab-wise domestic tariff with fixed charge and 5 % electricity duty
  • Separate commercial tariff
  • Consumer records with meter readings (previous and current)
  • Bill with slab break-up; late-payment surcharge
  • Reports: highest bill, average units, total revenue, consumers above 400 units
  • Energy-saving advice based on units
โ˜ฐ Main menu
1Add ConsumerName, type and meter readings; units = current - previous
2Bill of a ConsumerDetailed bill with slab break-up
3All BillsBill summary of every consumer
4StatisticsHighest, average, total revenue
5Heavy UsersConsumers above 400 units
6Late PaymentAdds 2 % surcharge
7Saving TipsAdvice based on usage
0ExitEnds the program
๐ŸŽฏ Objectives
  • Apply slab-wise conditional logic
  • Return several values from a function
  • Use the statistics module for the mean
๐Ÿ“š Data dictionary
NameTypePurpose
consumersdictConsumer no -> {name, type, prev, curr}
SLABSlist of tuple(upper limit, rate) for domestic tariff
COMMERCIAL_RATEfloatRs. 8.5 per unit
billsdictConsumer no -> total bill
Why it matters: A real tariff problem that exercises conditional logic, functions and the statistics module.
# =====================================================================
#   ELECTRICITY BILL CALCULATOR
#   Concepts : dictionaries, lists of tuples, loops, conditions,
#              functions, statistics module
# =====================================================================
import statistics

SLABS = [(100, 3.0), (200, 4.5), (400, 6.5), (float("inf"), 7.5)]
COMMERCIAL_RATE = 8.5
consumers = {}
bills = {}
next_no = 5001


def slab_charge(units):
    """Energy charge with break-up for domestic tariff."""
    charge, lower, parts = 0, 0, []
    for upper, rate in SLABS:
        if units > lower:
            u = min(units, upper) - lower
            charge += u * rate
            parts.append((lower + 1, int(min(units, upper)), u, rate, u * rate))
        lower = upper
    return charge, parts


def compute(no):
    """Returns energy, fixed, duty, total and break-up."""
    c = consumers[no]
    units = c["curr"] - c["prev"]
    if c["type"] == "C":
        energy, parts = units * COMMERCIAL_RATE, [(1, units, units, COMMERCIAL_RATE, units * COMMERCIAL_RATE)]
        fixed = 150
    else:
        energy, parts = slab_charge(units)
        fixed = 50 + (units // 100) * 10
    duty = energy * 0.05
    total = round(energy + fixed + duty, 2)
    bills[no] = total
    return units, energy, fixed, duty, total, parts


def add_consumer():
    """Adds a consumer with readings."""
    global next_no
    name = input("Consumer name    : ").strip().title()
    typ = input("Type D/C (domestic/commercial): ").strip().upper()
    try:
        prev = int(input("Previous reading : "))
        curr = int(input("Current reading  : "))
    except ValueError:
        print("Readings must be numbers.")
        return
    if curr < prev:
        print("Invalid reading - current is less than previous.")
        return
    consumers[next_no] = {"name": name, "type": "C" if typ == "C" else "D", "prev": prev, "curr": curr}
    print("Consumer no", next_no, "created. Units used:", curr - prev)
    next_no += 1


def bill_of():
    """Detailed bill of one consumer."""
    try:
        no = int(input("Consumer no: "))
    except ValueError:
        return
    if no not in consumers:
        print("Consumer not found.")
        return
    units, energy, fixed, duty, total, parts = compute(no)
    c = consumers[no]
    print("-" * 50)
    print(f"Consumer {no}: {c['name']} ({'Commercial' if c['type'] == 'C' else 'Domestic'})")
    print(f"Readings {c['prev']} -> {c['curr']}   Units {units}")
    for a, b, u, r, amt in parts:
        print(f"  Units {a:>4}-{b:<4}: {u:>4} x {r:>4} = {amt:>9.2f}")
    print(f"Energy charge {energy:>10.2f}\nFixed charge  {fixed:>10.2f}\nDuty (5%)     {duty:>10.2f}")
    print(f"TOTAL BILL    {total:>10.2f}")
    print("-" * 50)


def all_bills():
    """Bills of all consumers."""
    print(f"{'No':<6}{'Name':<13}{'Type':<5}{'Units':>6}{'Bill':>10}")
    for no in consumers:
        units, *_, total, _ = compute(no)
        print(f"{no:<6}{consumers[no]['name']:<13}{consumers[no]['type']:<5}{units:>6}{total:>10.2f}")


def stats():
    """Highest, average and revenue."""
    all_bills()
    top = max(bills, key=bills.get)
    units = [c["curr"] - c["prev"] for c in consumers.values()]
    print("Highest bill :", consumers[top]["name"], "Rs.", bills[top])
    print("Average units:", round(statistics.mean(units), 1), "| Median units:", statistics.median(units))
    print("Total revenue: Rs.", round(sum(bills.values()), 2))


def heavy_users():
    """Consumers above 400 units."""
    heavy = [c["name"] for c in consumers.values() if c["curr"] - c["prev"] > 400]
    print("Above 400 units:", heavy or "none")


def late_payment():
    """2 % surcharge."""
    try:
        no = int(input("Consumer no: "))
        units, e, f, d, total, p = compute(no)
        print(f"Bill Rs. {total} + surcharge Rs. {total * 0.02:.2f} = Rs. {total * 1.02:.2f}")
    except (ValueError, KeyError):
        print("Consumer not found.")


def tips():
    """Saving tips."""
    for no, c in consumers.items():
        u = c["curr"] - c["prev"]
        tip = ("Excellent - keep it up!" if u <= 100 else "Switch off fans/lights when not in use." if u <= 300
               else "Use 5-star AC, set it to 24 C; consider solar panels.")
        print(f"{c['name']:<12}{u:>5} units : {tip}")


menu = {"1": add_consumer, "2": bill_of, "3": all_bills, "4": stats, "5": heavy_users, "6": late_payment, "7": tips}
print("=" * 50)
print("ELECTRICITY BILL CALCULATOR".center(50))
print("=" * 50)
while True:
    print("\n1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Save electricity, save the planet!")
        break
    if ch in ("2", "6"):
        print("Consumers:", ", ".join(f"{k}-{v['name']}" for k, v in consumers.items()))
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Add? → No: run selected option
  4. Read name, type, previous and current reading
  5. Current >= previous? → No: 'Invalid reading'
  6. Units = current - previous
  7. Energy charge by slabs + fixed + 5 % duty
  8. Print bill / reports
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Units 80 (domestic)Energy Rs. 240 (first slab)PASS
2Units 250Slab break-up 100/100/50PASS
3Current reading less than previous'Invalid reading'PASS
4Commercial 300 unitsFlat Rs. 8.5 per unitPASS
5Late payment2 % surcharge addedPASS
6StatisticsHighest bill and total revenuePASS
7Heavy usersConsumers above 400 units listedPASS
8Unknown consumer no'Consumer not found'PASS
โš  Limitations
  • Tariff rates are sample values
  • Readings are typed manually
  • No database
  • Single billing month
๐Ÿš€ Future scope
  • Store month-wise readings in a CSV
  • Line chart of consumption
  • Online payment status
  • Solar net-metering credit

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): statistics - mean, median, mode functions are loaded.
  2. Global variables / constants are created: SLABS, COMMERCIAL_RATE, consumers, bills, next_no.
  3. 9 functions are defined (lines 15โ€“123) - Python stores them but does NOT run them yet.
  4. Main program starts at line 126: menu = {"1": add_consumer, "2": bill_of, "3": all_bills, "4": stats, " - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
slab_charge(units)15โ€“24Energy charge with break-up for domestic tariff.compute()
compute(no)27โ€“40Returns energy, fixed, duty, total and break-up.bill_of(), all_bills(), late_payment()
add_consumer()43โ€“59Adds a consumer with readings.main program (menu)
bill_of()62โ€“80Detailed bill of one consumer.main program (menu)
all_bills()83โ€“88Bills of all consumers.stats(), main program (menu)
stats()91โ€“98Highest, average and revenue.main program (menu)
heavy_users()101โ€“104Consumers above 400 units.main program (menu)
late_payment()107โ€“1142 % surcharge.main program (menu)
tips()117โ€“123Saving tips.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
126
menu = {"1": add_consumer, "2": bill_of, "3": all_bills, "4": stats, "5": heavy_users, "6": late_payment, "7": tips}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_consumer, "2": bill_of, "3": all_biโ€ฆ in variable menu
127
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
128
print("ELECTRICITY BILL CALCULATOR".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "ELECTRICITY BILL CALCULATOR".center(50) on the screen
129
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
130
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
131
print("\n1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Bill 3.All Bills 4.Stats โ€ฆ" on the screen
132
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
133
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
134
print("Save electricity, save the planet!")
๐Ÿ–ฅ๏ธ Output Displays the text "Save electricity, save the planet!" on the screen
135
break
๐Ÿ” Loop BREAK - leaves the loop immediately
136
if ch in ("2", "6"):
๐Ÿ”€ Decision CHECKS whether ch is present in ("2", "6"). If True, the indented lines below run; otherwise they are skipped
137
print("Consumers:", ", ".join(f"{k}-{v['name']}" for k, v in consumers.items()))
๐Ÿ–ฅ๏ธ Output Displays the text "Consumers:", then the value of ", ".join(f"{k}-{v['name']}" for k, v in consโ€ฆ on the screen
138
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: ELECTRICITY BILL CALCULATOR (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add_consumer()
  3. You type Ramesh at Consumer name :
  4. You type D at Type D/C (domestic/commercial):
  5. You type 1200 at Previous reading :
  6. You type 1280 at Current reading :
    shows: Consumer no 5001 created. Units used: 80 (+1 more lines)
  7. You type 1 at Enter choice:
    runs: add_consumer()
  8. You type Sunita at Consumer name :
  9. You type D at Type D/C (domestic/commercial):
  10. You type 3400 at Previous reading :
  11. You type 3650 at Current reading :
    shows: Consumer no 5002 created. Units used: 250 (+1 more lines)
  12. You type 1 at Enter choice:
    runs: add_consumer()
  13. You type Gupta Store at Consumer name :
  14. You type C at Type D/C (domestic/commercial):
  15. You type 5000 at Previous reading :
  16. You type 5300 at Current reading :
    shows: Consumer no 5003 created. Units used: 300 (+1 more lines)
  17. You type 1 at Enter choice:
    runs: add_consumer()
  18. You type Iqbal at Consumer name :
  19. You type D at Type D/C (domestic/commercial):
  20. You type 900 at Previous reading :
  21. You type 850 at Current reading :
    shows: Invalid reading - current is less than previous. (+1 more lines)
  22. You type 1 at Enter choice:
    runs: add_consumer()
  23. You type Iqbal at Consumer name :
  24. You type D at Type D/C (domestic/commercial):
  25. You type 900 at Previous reading :
  26. You type 1420 at Current reading :
    shows: Consumer no 5004 created. Units used: 520 (+1 more lines)
  27. You type 2 at Enter choice:
    runs: bill_of()
    shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
  28. You type 5002 at Consumer no:
    runs: compute() โ†’ slab_charge()
    shows: Consumer 5002: Sunita (Domestic) (+9 more lines)
  29. You type 2 at Enter choice:
    runs: bill_of()
    shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
  30. You type 5003 at Consumer no:
    runs: compute()
    shows: Consumer 5003: Gupta Store (Commercial) (+7 more lines)
  31. You type 3 at Enter choice:
    runs: all_bills() โ†’ compute() โ†’ slab_charge() โ†’ compute() โ†’ slab_charge() โ†’ compute() ร—2 โ†’ slab_charge()
    shows: No Name Type Units Bill (+5 more lines)
  32. You type 4 at Enter choice:
    runs: stats() โ†’ all_bills() โ†’ compute() โ†’ slab_charge() โ†’ compute() โ†’ slab_charge() โ†’ compute() ร—2 โ†’ slab_charge()
    shows: No Name Type Units Bill (+8 more lines)
  33. You type 5 at Enter choice:
    runs: heavy_users()
    shows: Above 400 units: ['Iqbal'] (+1 more lines)
  34. You type 6 at Enter choice:
    runs: late_payment()
    shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
  35. You type 5004 at Consumer no:
    runs: compute() โ†’ slab_charge()
    shows: Bill Rs. 3197.5 + surcharge Rs. 63.95 = Rs. 3261.45 (+1 more lines)
  36. You type 7 at Enter choice:
    runs: tips()
    shows: Ramesh 80 units : Excellent - keep it up! (+4 more lines)
  37. You type 2 at Enter choice:
    runs: bill_of()
    shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
  38. You type 99 at Consumer no:
    shows: Consumer not found. (+1 more lines)
  39. You type 0 at Enter choice:
    shows: Save electricity, save the planet!
โ‘ค Inside each function - line by line
slab_charge() - lines 15โ€“24
LineCodeWhat it does
15
def slab_charge(units):
๐Ÿงฉ Function DEFINES a function slab_charge(units). Python only remembers it here - its body runs later, each time slab_charge() is called.
17
charge, lower, parts = 0, 0, []
๐Ÿงฎ Store / Calculate Stores 0, 0, [] into charge, lower, parts respectively
18
for upper, rate in SLABS:
๐Ÿ” Loop LOOP: takes each item of SLABS one-by-one into upper, rate and runs the indented block for it
19
if units > lower:
๐Ÿ”€ Decision CHECKS whether units is greater than lower. If True, the indented lines below run; otherwise they are skipped
20
u = min(units, upper) - lower
๐Ÿงฎ Store / Calculate Stores the value of min(units, upper) - lower (calculated using -) in variable u
21
charge += u * rate
๐Ÿงฎ Store / Calculate Adds u * rate to charge (same as charge = charge + u * rate)
22
parts.append((lower + 1, int(min(units, upper)), u, rate, u * rate))
๐Ÿงฎ Store / Calculate Adds (lower + 1, int(min(units, upper)), u, rate, โ€ฆ at the end of list parts
23
lower = upper
๐Ÿงฎ Store / Calculate Stores the value of upper in variable lower
24
return charge, parts
๐Ÿงฉ Function Sends back (returns) the tuple charge, parts to the line that called the function
compute() - lines 27โ€“40
LineCodeWhat it does
27
def compute(no):
๐Ÿงฉ Function DEFINES a function compute(no). Python only remembers it here - its body runs later, each time compute() is called.
29
c = consumers[no]
๐Ÿงฎ Store / Calculate Stores the item consumers[no] in variable c
30
units = c["curr"] - c["prev"]
๐Ÿงฎ Store / Calculate Stores the value of c["curr"] - c["prev"] (calculated using -) in variable units
31
if c["type"] == "C":
๐Ÿ”€ Decision CHECKS whether c["type"] is equal to "C". If True, the indented lines below run; otherwise Python jumps to the elif/else part
32
energy, parts = units * COMMERCIAL_RATE, [(1, units, units, COMMERCIAL_RATE, units * COMMERCIAL_RATE)]
๐Ÿงฎ Store / Calculate Stores units * COMMERCIAL_RATE, [(1, units, units, COMMERCIAL_RATE, units * COMMERCIAL_RATE)] into energy, parts respectively
33
fixed = 150
๐Ÿงฎ Store / Calculate Stores the number 150 in variable fixed
34
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
35
energy, parts = slab_charge(units)
๐Ÿงฎ Store / Calculate Calls our own function slab_charge(units) - energy charge with break-up for domestic tariff; the result is stored in variables energy, parts
36
fixed = 50 + (units // 100) * 10
๐Ÿงฎ Store / Calculate Stores the value of 50 + (units // 100) * 10 (calculated using +) in variable fixed
37
duty = energy * 0.05
๐Ÿงฎ Store / Calculate Stores the value of energy * 0.05 (calculated using ร—) in variable duty
38
total = round(energy + fixed + duty, 2)
๐Ÿงฎ Store / Calculate Rounds energy + fixed + duty to 2 decimal places; the result is stored in variable total
39
bills[no] = total
๐Ÿงฎ Store / Calculate Puts the value of total into bills[no] (item no of bills)
40
return units, energy, fixed, duty, total, parts
๐Ÿงฉ Function Sends back (returns) the tuple units, energy, fixed, duty, total, parts to the line that called the function
add_consumer() - lines 43โ€“59
LineCodeWhat it does
43
def add_consumer():
๐Ÿงฉ Function DEFINES a function add_consumer(). Python only remembers it here - its body runs later, each time add_consumer() is called.
45
global next_no
๐Ÿงฉ Function Tells Python that next_no means the GLOBAL variable (outside the function)
46
name = input("Consumer name    : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
47
typ = input("Type D/C (domestic/commercial): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable typ
48
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
49
prev = int(input("Previous reading : "))
โŒจ๏ธ Input Shows "Previous reading : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable prev
50
curr = int(input("Current reading  : "))
โŒจ๏ธ Input Shows "Current reading : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable curr
51
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
52
print("Readings must be numbers.")
๐Ÿ–ฅ๏ธ Output Displays the text "Readings must be numbers." on the screen
53
return
๐Ÿงฉ Function Ends the function and goes back to the caller
54
if curr < prev:
๐Ÿ”€ Decision CHECKS whether curr is less than prev. If True, the indented lines below run; otherwise they are skipped
55
print("Invalid reading - current is less than previous.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid reading - current is lessโ€ฆ" on the screen
56
return
๐Ÿงฉ Function Ends the function and goes back to the caller
57
consumers[next_no] = {"name": name, "type": "C" if typ == "C" else "D", "prev": prev, "curr": curr}
๐Ÿงฎ Store / Calculate Puts a dictionary {"name": name, "type": "C" if typ == "C" elseโ€ฆ into consumers[next_no] (item next_no of consumers)
58
print("Consumer no", next_no, "created. Units used:", curr - prev)
๐Ÿ–ฅ๏ธ Output Displays the text "Consumer no", then the value of next_no, then the text "created. Units used:", then the value of curr - prev on the screen
59
next_no += 1
๐Ÿงฎ Store / Calculate Adds 1 to next_no (same as next_no = next_no + 1)
bill_of() - lines 62โ€“80
LineCodeWhat it does
62
def bill_of():
๐Ÿงฉ Function DEFINES a function bill_of(). Python only remembers it here - its body runs later, each time bill_of() is called.
64
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
65
no = int(input("Consumer no: "))
โŒจ๏ธ Input Shows "Consumer no: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable no
66
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
67
return
๐Ÿงฉ Function Ends the function and goes back to the caller
68
if no not in consumers:
๐Ÿ”€ Decision CHECKS whether no is not present in consumers. If True, the indented lines below run; otherwise they are skipped
69
print("Consumer not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Consumer not found." on the screen
70
return
๐Ÿงฉ Function Ends the function and goes back to the caller
71
units, energy, fixed, duty, total, parts = compute(no)
๐Ÿงฎ Store / Calculate Calls our own function compute(no) - returns energy, fixed, duty, total and break-up; the result is stored in variables units, energy, fixed, duty, total, parts
72
c = consumers[no]
๐Ÿงฎ Store / Calculate Stores the item consumers[no] in variable c
73
print("-" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "-" signs on the screen
74
print(f"Consumer {no}: {c['name']} ({'Commercial' if c['type'] == 'C' else 'Domestic'})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Consumer {no}: {c['name']} ({'Commercial' iโ€ฆ with the values filled into { } on the screen
75
print(f"Readings {c['prev']} -> {c['curr']}   Units {units}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Readings {c['prev']} -> {c['curr']} Units {โ€ฆ with the values filled into { } on the screen
76
for a, b, u, r, amt in parts:
๐Ÿ” Loop LOOP: takes each item of parts one-by-one into a, b, u, r, amt and runs the indented block for it
77
print(f"  Units {a:>4}-{b:<4}: {u:>4} x {r:>4} = {amt:>9.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Units {a:>4}-{b:<4}: {u:>4} x {r:>4} = {amโ€ฆ with the values filled into { } on the screen
78
print(f"Energy charge {energy:>10.2f}\nFixed charge  {fixed:>10.2f}\nDuty (5%)     {duty:>10.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Energy charge {energy:>10.2f}\nFixed chargeโ€ฆ with the values filled into { } on the screen
79
print(f"TOTAL BILL    {total:>10.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"TOTAL BILL {total:>10.2f}" with the values filled into { } on the screen
80
print("-" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "-" signs on the screen
all_bills() - lines 83โ€“88
LineCodeWhat it does
83
def all_bills():
๐Ÿงฉ Function DEFINES a function all_bills(). Python only remembers it here - its body runs later, each time all_bills() is called.
85
print(f"{'No':<6}{'Name':<13}{'Type':<5}{'Units':>6}{'Bill':>10}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'No':<6}{'Name':<13}{'Type':<5}{'Units':>6โ€ฆ with the values filled into { } on the screen
86
for no in consumers:
๐Ÿ” Loop LOOP: takes each item of consumers one-by-one into no and runs the indented block for it
87
units, *_, total, _ = compute(no)
๐Ÿงฎ Store / Calculate Calls our own function compute(no) - returns energy, fixed, duty, total and break-up; the result is stored in variables units, *_, total, _
88
print(f"{no:<6}{consumers[no]['name']:<13}{consumers[no]['type']:<5}{units:>6}{total:>10.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{no:<6}{consumers[no]['name']:<13}{consumerโ€ฆ with the values filled into { } on the screen
stats() - lines 91โ€“98
LineCodeWhat it does
91
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
93
all_bills()
๐Ÿงฎ Store / Calculate Calls our own function all_bills() - bills of all consumers
94
top = max(bills, key=bills.get)
๐Ÿงฎ Store / Calculate Finds the largest value among bills; the result is stored in variable top
95
units = [c["curr"] - c["prev"] for c in consumers.values()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [c["curr"] - c["prev"] for c in consumers.valโ€ฆ in variable units
96
print("Highest bill :", consumers[top]["name"], "Rs.", bills[top])
๐Ÿ–ฅ๏ธ Output Displays the text "Highest bill :", then the value of consumers[top]["name"], then the text "Rs.", then the value of bills[top] on the screen
97
print("Average units:", round(statistics.mean(units), 1), "| Median units:", statistics.median(units))
๐Ÿ–ฅ๏ธ Output Displays the text "Average units:", then the value of round(statistics.mean(units), 1), then the text "| Median units:", then the value of statistics.median(units) on the screen
98
print("Total revenue: Rs.", round(sum(bills.values()), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Total revenue: Rs.", then the value of round(sum(bills.values()), 2) on the screen
heavy_users() - lines 101โ€“104
LineCodeWhat it does
101
def heavy_users():
๐Ÿงฉ Function DEFINES a function heavy_users(). Python only remembers it here - its body runs later, each time heavy_users() is called.
103
heavy = [c["name"] for c in consumers.values() if c["curr"] - c["prev"] > 400]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [c["name"] for c in consumers.values() if c["โ€ฆ in variable heavy
104
print("Above 400 units:", heavy or "none")
๐Ÿ–ฅ๏ธ Output Displays the text "Above 400 units:", then the value of heavy or "none" on the screen
late_payment() - lines 107โ€“114
LineCodeWhat it does
107
def late_payment():
๐Ÿงฉ Function DEFINES a function late_payment(). Python only remembers it here - its body runs later, each time late_payment() is called.
109
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
110
no = int(input("Consumer no: "))
โŒจ๏ธ Input Shows "Consumer no: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable no
111
units, e, f, d, total, p = compute(no)
๐Ÿงฎ Store / Calculate Calls our own function compute(no) - returns energy, fixed, duty, total and break-up; the result is stored in variables units, e, f, d, total, p
112
print(f"Bill Rs. {total} + surcharge Rs. {total * 0.02:.2f} = Rs. {total * 1.02:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bill Rs. {total} + surcharge Rs. {total * 0โ€ฆ with the values filled into { } on the screen
113
except (ValueError, KeyError):
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, KeyError) occurs - that error
114
print("Consumer not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Consumer not found." on the screen
tips() - lines 117โ€“123
LineCodeWhat it does
117
def tips():
๐Ÿงฉ Function DEFINES a function tips(). Python only remembers it here - its body runs later, each time tips() is called.
119
for no, c in consumers.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary consumers; no, c get one pair each round
120
u = c["curr"] - c["prev"]
๐Ÿงฎ Store / Calculate Stores the value of c["curr"] - c["prev"] (calculated using -) in variable u
121
tip = ("Excellent - keep it up!" if u <= 100 else "Switch off fans/lights when not in use." if u <= 300
       else "Use 5-star AC, set it to 24 C; consider โ€ฆ
๐Ÿงฎ Store / Calculate Stores either "Excellent - keep it up!" or "Switch off fans/lights when not in use." if โ€ฆ depending on u <= 100 in variable tip
123
print(f"{c['name']:<12}{u:>5} units : {tip}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c['name']:<12}{u:>5} units : {tip}" with the values filled into { } on the screen
Q1. Why are slabs used in electricity tariff?

To charge low rates for basic usage and higher rates for heavy usage, encouraging saving.

Q2. How is the slab calculation done in the program?

A loop goes through (limit, rate) pairs, charging units within each slab until all units are covered.

Q3. How are units calculated?

Units = current meter reading - previous meter reading.

Q4. What is the electricity duty here?

5 % of the energy charge, added to the bill.

Q5. How is the highest bill found?

max(bills, key=bills.get) returns the consumer number with the maximum bill.

07

BMI & Health Tracker

PYTHONList of tuplesfunctionsif-elif categoriesstatistics module (meanmedian)
๐Ÿ“ 128 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 109 output lines๐Ÿ“„ 25+ page report

Calculates BMI of every student, assigns a health category, shows mean/median BMI and lists students who need medical attention.

โœจ Features
  • Health records of students: name, age, gender, weight, height
  • BMI with WHO categories and ideal-weight range for the height
  • Daily water and calorie (BMR) estimate using Mifflin-St Jeor formula
  • Class health report: mean, median, mode of BMI and category counts with bar chart
  • Search, update weight (progress tracking) and delete
  • Personalised fitness tips
โ˜ฐ Main menu
1Add RecordAdds a student's health data
2Health ReportBMI, category and ideal weight of all
3Individual CardBMI, BMR, water intake and tips for one student
4Class StatisticsMean / median / mode of BMI and category chart
5Update WeightNew weight and change in BMI
6Need AttentionStudents not in the normal range
7Delete RecordRemoves a record
0ExitEnds the program
๐ŸŽฏ Objectives
  • Apply the BMI formula in a program
  • Classify values with a function
  • Use statistics.mean() and statistics.median()
๐Ÿ“š Data dictionary
NameTypePurpose
recordsdictName -> {age, gender, weight, height}
bmifloatweight (kg) / height (m) squared
bmrfloatBasal metabolic rate (kcal/day)
CATSlist of tuple(upper limit, category) for BMI
Why it matters: Links data handling with health awareness and demonstrates statistics functions on real data.
# =====================================================================
#   BMI & HEALTH TRACKER
#   Concepts : dictionaries, tuples, functions, statistics module,
#              conditions, formatted reports
# =====================================================================
import statistics

CATS = [(18.5, "Underweight"), (25, "Normal"), (30, "Overweight"), (100, "Obese")]
records = {}


def bmi_of(r):
    return round(r["weight"] / (r["height"] / 100) ** 2, 1)


def category(b):
    for limit, cat in CATS:
        if b < limit:
            return cat
    return "Obese"


def bmr_of(r):
    """Mifflin-St Jeor BMR."""
    base = 10 * r["weight"] + 6.25 * r["height"] - 5 * r["age"]
    return round(base + (5 if r["gender"] == "M" else -161))


def add_record():
    """Adds a health record."""
    name = input("Name   : ").strip().title()
    try:
        age = int(input("Age    : "))
        gender = input("Gender (M/F): ").strip().upper()
        w = float(input("Weight (kg): "))
        h = float(input("Height (cm): "))
    except ValueError:
        print("Enter numbers for age, weight and height.")
        return
    if not 100 <= h <= 220:
        print("Invalid height (100-220 cm).")
        return
    if not 20 <= w <= 200:
        print("Invalid weight (20-200 kg).")
        return
    records[name] = {"age": age, "gender": gender, "weight": w, "height": h}
    print(f"Saved. BMI = {bmi_of(records[name])} ({category(bmi_of(records[name]))})")


def report():
    """BMI report of all students."""
    print(f"{'Name':<9}{'Age':>4}{'Wt':>6}{'Ht':>6}{'BMI':>6}  {'Category':<12}Ideal weight")
    print("-" * 62)
    for n, r in records.items():
        m = r["height"] / 100
        b = bmi_of(r)
        print(f"{n:<9}{r['age']:>4}{r['weight']:>6.0f}{r['height']:>6.0f}{b:>6}  {category(b):<12}{18.5 * m * m:.0f}-{24.9 * m * m:.0f} kg")


def card():
    """Individual health card."""
    n = input("Name: ").strip().title()
    if n not in records:
        print("Record not found.")
        return
    r = records[n]
    b = bmi_of(r)
    print("=" * 40)
    print(f"HEALTH CARD : {n}")
    print(f"BMI {b} - {category(b)}")
    print(f"BMR {bmr_of(r)} kcal/day | Active-day need ~{round(bmr_of(r) * 1.55)} kcal")
    print(f"Water: about {r['weight'] * 0.033:.1f} litres per day")
    tip = {"Underweight": "Add nutritious snacks: nuts, milk, eggs/paneer, bananas.",
           "Normal": "Great! Keep 60 minutes of daily activity.",
           "Overweight": "Reduce sugary drinks and fried food; walk 45 minutes daily.",
           "Obese": "Consult a doctor; start with brisk walking and portion control."}[category(b)]
    print("Tip:", tip)
    print("=" * 40)


def class_stats():
    """Mean, median, mode of BMI and category chart."""
    b = [bmi_of(r) for r in records.values()]
    print(f"Mean BMI   : {statistics.mean(b):.2f}")
    print(f"Median BMI : {statistics.median(b)}")
    print(f"Mode (rounded): {statistics.mode([round(x) for x in b])}")
    print(f"Std dev    : {statistics.pstdev(b):.2f}")
    for _, cat in CATS:
        k = sum(1 for x in b if category(x) == cat)
        print(f"  {cat:<12}{'#' * (k * 4)} {k}")


def update_weight():
    """Progress tracking."""
    n = input("Name: ").strip().title()
    if n not in records:
        print("Record not found.")
        return
    old = bmi_of(records[n])
    records[n]["weight"] = float(input("New weight (kg): "))
    new = bmi_of(records[n])
    print(f"BMI {old} -> {new} ({new - old:+.1f}); now {category(new)}")


def attention():
    """Students outside normal BMI."""
    for n, r in records.items():
        if category(bmi_of(r)) != "Normal":
            print(f"{n:<9} BMI {bmi_of(r):<5} {category(bmi_of(r))}")


def delete():
    n = input("Name: ").strip().title()
    print("Deleted." if records.pop(n, None) else "Record not found.")


menu = {"1": add_record, "2": report, "3": card, "4": class_stats, "5": update_weight, "6": attention, "7": delete}
print("=" * 62)
print("BMI & HEALTH TRACKER (School Health Club)".center(62))
print("=" * 62)
while True:
    print("\n1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Stay fit, stay healthy!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Add? → No: run selected report
  4. Read name, age, gender, weight, height
  5. Values in valid range? → No: show error
  6. BMI, category, ideal weight, BMR
  7. Show card / report / statistics
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1W 50 kg, H 160 cmBMI 19.5 NormalPASS
2W 85, H 165BMI 31.2 ObesePASS
3Height 20 cm'Invalid height'PASS
4Individual cardBMR and water intake shownPASS
5Class statisticsMean, median, mode and chartPASS
6Update weight 85 -> 80BMI change displayedPASS
7Need attentionStudents outside normal listedPASS
8Delete unknown'Record not found'PASS
โš  Limitations
  • BMI does not separate muscle and fat
  • Formulas are general estimates, not medical advice
  • Data not stored permanently
  • Only metric units
๐Ÿš€ Future scope
  • Save monthly records to CSV and plot progress
  • Add step-count / sleep tracking
  • Generate PDF health cards
  • Connect to a fitness band API

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): statistics - mean, median, mode functions are loaded.
  2. Global variables / constants are created: CATS, records.
  3. 10 functions are defined (lines 12โ€“114) - Python stores them but does NOT run them yet.
  4. Main program starts at line 117: menu = {"1": add_record, "2": report, "3": card, "4": class_stats, "5" - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
bmi_of(r)12โ€“13Bmi ofadd_record(), report(), card(), class_stats()
category(b)16โ€“20Categoryadd_record(), report(), card(), class_stats()
bmr_of(r)23โ€“26Mifflin-St Jeor BMR.card()
add_record()29โ€“47Adds a health record.main program (menu)
report()50โ€“57BMI report of all students.main program (menu)
card()60โ€“78Individual health card.main program (menu)
class_stats()81โ€“90Mean, median, mode of BMI and category chart.main program (menu)
update_weight()93โ€“102Progress tracking.main program (menu)
attention()105โ€“109Students outside normal BMI.main program (menu)
delete()112โ€“114Deletemain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
117
menu = {"1": add_record, "2": report, "3": card, "4": class_stats, "5": update_weight, "6": attention, "7": delete}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_record, "2": report, "3": card, "4"โ€ฆ in variable menu
118
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
119
print("BMI & HEALTH TRACKER (School Health Club)".center(62))
๐Ÿ–ฅ๏ธ Output Displays the value of "BMI & HEALTH TRACKER (School Health Club)".cโ€ฆ on the screen
120
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
121
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
122
print("\n1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Report 3.Health Card 4.Stโ€ฆ" on the screen
123
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
124
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
125
print("Stay fit, stay healthy!")
๐Ÿ–ฅ๏ธ Output Displays the text "Stay fit, stay healthy!" on the screen
126
break
๐Ÿ” Loop BREAK - leaves the loop immediately
127
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: BMI & HEALTH TRACKER (School Health Club) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add_record()
  3. You type Aman at Name :
  4. You type 16 at Age :
  5. You type M at Gender (M/F):
  6. You type 50 at Weight (kg):
  7. You type 160 at Height (cm):
    runs: bmi_of() ร—2 โ†’ category()
    shows: Saved. BMI = 19.5 (Normal) (+1 more lines)
  8. You type 1 at Enter choice:
    runs: add_record()
  9. You type Bina at Name :
  10. You type 16 at Age :
  11. You type F at Gender (M/F):
  12. You type 42 at Weight (kg):
  13. You type 158 at Height (cm):
    runs: bmi_of() ร—2 โ†’ category()
    shows: Saved. BMI = 16.8 (Underweight) (+1 more lines)
  14. You type 1 at Enter choice:
    runs: add_record()
  15. You type Chetan at Name :
  16. You type 17 at Age :
  17. You type M at Gender (M/F):
  18. You type 85 at Weight (kg):
  19. You type 165 at Height (cm):
    runs: bmi_of() ร—2 โ†’ category()
    shows: Saved. BMI = 31.2 (Obese) (+1 more lines)
  20. You type 1 at Enter choice:
    runs: add_record()
  21. You type Dolly at Name :
  22. You type 16 at Age :
  23. You type F at Gender (M/F):
  24. You type 58 at Weight (kg):
  25. You type 155 at Height (cm):
    runs: bmi_of() ร—2 โ†’ category()
    shows: Saved. BMI = 24.1 (Normal) (+1 more lines)
  26. You type 1 at Enter choice:
    runs: add_record()
  27. You type Esha at Name :
  28. You type 17 at Age :
  29. You type F at Gender (M/F):
  30. You type 50 at Weight (kg):
  31. You type 20 at Height (cm):
    shows: Invalid height (100-220 cm). (+1 more lines)
  32. You type 1 at Enter choice:
    runs: add_record()
  33. You type Farhan at Name :
  34. You type 17 at Age :
  35. You type M at Gender (M/F):
  36. You type 68 at Weight (kg):
  37. You type 175 at Height (cm):
    runs: bmi_of() ร—2 โ†’ category()
    shows: Saved. BMI = 22.2 (Normal) (+1 more lines)
  38. You type 2 at Enter choice:
    runs: report() โ†’ bmi_of() โ†’ category() โ†’ bmi_of() โ†’ category() โ†’ bmi_of() โ†’ category() โ†’ bmi_of()
    shows: Name Age Wt Ht BMI Category Ideal weight (+6 more lines)
  39. You type 3 at Enter choice:
    runs: card()
  40. You type Chetan at Name:
    runs: bmi_of() โ†’ category() โ†’ bmr_of() ร—2 โ†’ category()
    shows: HEALTH CARD : Chetan (+5 more lines)

โ€ฆ and 8 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
bmi_of() - lines 12โ€“13
LineCodeWhat it does
12
def bmi_of(r):
๐Ÿงฉ Function DEFINES a function bmi_of(r). Python only remembers it here - its body runs later, each time bmi_of() is called.
13
return round(r["weight"] / (r["height"] / 100) ** 2, 1)
๐Ÿงฉ Function Sends back (returns) the result of: rounds r["weight"] / (r["height"] / 100) ** 2 to 1 decimal places to the line that called the function
category() - lines 16โ€“20
LineCodeWhat it does
16
def category(b):
๐Ÿงฉ Function DEFINES a function category(b). Python only remembers it here - its body runs later, each time category() is called.
17
for limit, cat in CATS:
๐Ÿ” Loop LOOP: takes each item of CATS one-by-one into limit, cat and runs the indented block for it
18
if b < limit:
๐Ÿ”€ Decision CHECKS whether b is less than limit. If True, the indented lines below run; otherwise they are skipped
19
return cat
๐Ÿงฉ Function Sends back (returns) the value of cat to the line that called the function
20
return "Obese"
๐Ÿงฉ Function Sends back (returns) the text "Obese" to the line that called the function
bmr_of() - lines 23โ€“26
LineCodeWhat it does
23
def bmr_of(r):
๐Ÿงฉ Function DEFINES a function bmr_of(r). Python only remembers it here - its body runs later, each time bmr_of() is called.
25
base = 10 * r["weight"] + 6.25 * r["height"] - 5 * r["age"]
๐Ÿงฎ Store / Calculate Stores the value of 10 * r["weight"] + 6.25 * r["height"] - 5 * rโ€ฆ (calculated using -) in variable base
26
return round(base + (5 if r["gender"] == "M" else -161))
๐Ÿงฉ Function Sends back (returns) the result of: rounds base + (5 if r["gender"] == "M" else -161) to decimal places to the line that called the function
add_record() - lines 29โ€“47
LineCodeWhat it does
29
def add_record():
๐Ÿงฉ Function DEFINES a function add_record(). Python only remembers it here - its body runs later, each time add_record() is called.
31
name = input("Name   : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
32
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
33
age = int(input("Age    : "))
โŒจ๏ธ Input Shows "Age : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable age
34
gender = input("Gender (M/F): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable gender
35
w = float(input("Weight (kg): "))
โŒจ๏ธ Input Shows "Weight (kg): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable w
36
h = float(input("Height (cm): "))
โŒจ๏ธ Input Shows "Height (cm): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable h
37
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
38
print("Enter numbers for age, weight and height.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter numbers for age, weight andโ€ฆ" on the screen
39
return
๐Ÿงฉ Function Ends the function and goes back to the caller
40
if not 100 <= h <= 220:
๐Ÿ”€ Decision CHECKS whether NOT 100 <= h <= 220 is True. If True, the indented lines below run; otherwise they are skipped
41
print("Invalid height (100-220 cm).")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid height (100-220 cm)." on the screen
42
return
๐Ÿงฉ Function Ends the function and goes back to the caller
43
if not 20 <= w <= 200:
๐Ÿ”€ Decision CHECKS whether NOT 20 <= w <= 200 is True. If True, the indented lines below run; otherwise they are skipped
44
print("Invalid weight (20-200 kg).")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid weight (20-200 kg)." on the screen
45
return
๐Ÿงฉ Function Ends the function and goes back to the caller
46
records[name] = {"age": age, "gender": gender, "weight": w, "height": h}
๐Ÿงฎ Store / Calculate Puts a dictionary {"age": age, "gender": gender, "weight": w, "โ€ฆ into records[name] (item name of records)
47
print(f"Saved. BMI = {bmi_of(records[name])} ({category(bmi_of(records[name]))})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Saved. BMI = {bmi_of(records[name])} ({cateโ€ฆ with the values filled into { } on the screen
report() - lines 50โ€“57
LineCodeWhat it does
50
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
52
print(f"{'Name':<9}{'Age':>4}{'Wt':>6}{'Ht':>6}{'BMI':>6}  {'Category':<12}Ideal weight")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Name':<9}{'Age':>4}{'Wt':>6}{'Ht':>6}{'BMโ€ฆ with the values filled into { } on the screen
53
print("-" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "-" signs on the screen
54
for n, r in records.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary records; n, r get one pair each round
55
m = r["height"] / 100
๐Ÿงฎ Store / Calculate Stores the value of r["height"] / 100 (calculated using รท) in variable m
56
b = bmi_of(r)
๐Ÿงฎ Store / Calculate Calls our own function bmi_of(r); the result is stored in variable b
57
print(f"{n:<9}{r['age']:>4}{r['weight']:>6.0f}{r['height']:>6.0f}{b:>6}  {category(b):<12}{18.5 * m * m:.0f}-{24.9 * m * m:.0f} kg")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<9}{r['age']:>4}{r['weight']:>6.0f}{r['hโ€ฆ with the values filled into { } on the screen
card() - lines 60โ€“78
LineCodeWhat it does
60
def card():
๐Ÿงฉ Function DEFINES a function card(). Python only remembers it here - its body runs later, each time card() is called.
62
n = input("Name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
63
if n not in records:
๐Ÿ”€ Decision CHECKS whether n is not present in records. If True, the indented lines below run; otherwise they are skipped
64
print("Record not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Record not found." on the screen
65
return
๐Ÿงฉ Function Ends the function and goes back to the caller
66
r = records[n]
๐Ÿงฎ Store / Calculate Stores the item records[n] in variable r
67
b = bmi_of(r)
๐Ÿงฎ Store / Calculate Calls our own function bmi_of(r); the result is stored in variable b
68
print("=" * 40)
๐Ÿ–ฅ๏ธ Output Displays a line of 40 "=" signs on the screen
69
print(f"HEALTH CARD : {n}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"HEALTH CARD : {n}" with the values filled into { } on the screen
70
print(f"BMI {b} - {category(b)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"BMI {b} - {category(b)}" with the values filled into { } on the screen
71
print(f"BMR {bmr_of(r)} kcal/day | Active-day need ~{round(bmr_of(r) * 1.55)} kcal")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"BMR {bmr_of(r)} kcal/day | Active-day need โ€ฆ with the values filled into { } on the screen
72
print(f"Water: about {r['weight'] * 0.033:.1f} litres per day")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Water: about {r['weight'] * 0.033:.1f} litrโ€ฆ with the values filled into { } on the screen
73
tip = {"Underweight": "Add nutritious snacks: nuts, milk, eggs/paneer, bananas.",
       "Normal": "Great! Keep 60 minutes of daily activity.",
       "Overwโ€ฆ
๐Ÿงฎ Store / Calculate Stores the item {"Underweight": "Add nutritious snacks: nuts,โ€ฆ in variable tip
77
print("Tip:", tip)
๐Ÿ–ฅ๏ธ Output Displays the text "Tip:", then the value of tip on the screen
78
print("=" * 40)
๐Ÿ–ฅ๏ธ Output Displays a line of 40 "=" signs on the screen
class_stats() - lines 81โ€“90
LineCodeWhat it does
81
def class_stats():
๐Ÿงฉ Function DEFINES a function class_stats(). Python only remembers it here - its body runs later, each time class_stats() is called.
83
b = [bmi_of(r) for r in records.values()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [bmi_of(r) for r in records.values()] in variable b
84
print(f"Mean BMI   : {statistics.mean(b):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Mean BMI : {statistics.mean(b):.2f}" with the values filled into { } on the screen
85
print(f"Median BMI : {statistics.median(b)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Median BMI : {statistics.median(b)}" with the values filled into { } on the screen
86
print(f"Mode (rounded): {statistics.mode([round(x) for x in b])}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Mode (rounded): {statistics.mode([round(x) โ€ฆ with the values filled into { } on the screen
87
print(f"Std dev    : {statistics.pstdev(b):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Std dev : {statistics.pstdev(b):.2f}" with the values filled into { } on the screen
88
for _, cat in CATS:
๐Ÿ” Loop LOOP: takes each item of CATS one-by-one into _, cat and runs the indented block for it
89
k = sum(1 for x in b if category(x) == cat)
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for x in b if category(x) == cat); the result is stored in variable k
90
print(f"  {cat:<12}{'#' * (k * 4)} {k}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {cat:<12}{'#' * (k * 4)} {k}" with the values filled into { } on the screen
update_weight() - lines 93โ€“102
LineCodeWhat it does
93
def update_weight():
๐Ÿงฉ Function DEFINES a function update_weight(). Python only remembers it here - its body runs later, each time update_weight() is called.
95
n = input("Name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
96
if n not in records:
๐Ÿ”€ Decision CHECKS whether n is not present in records. If True, the indented lines below run; otherwise they are skipped
97
print("Record not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Record not found." on the screen
98
return
๐Ÿงฉ Function Ends the function and goes back to the caller
99
old = bmi_of(records[n])
๐Ÿงฎ Store / Calculate Calls our own function bmi_of(records[n]); the result is stored in variable old
100
records[n]["weight"] = float(input("New weight (kg): "))
โŒจ๏ธ Input Shows "New weight (kg): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in records[n]["weight"] (item "weight" of records[n])
101
new = bmi_of(records[n])
๐Ÿงฎ Store / Calculate Calls our own function bmi_of(records[n]); the result is stored in variable new
102
print(f"BMI {old} -> {new} ({new - old:+.1f}); now {category(new)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"BMI {old} -> {new} ({new - old:+.1f}); now โ€ฆ with the values filled into { } on the screen
attention() - lines 105โ€“109
LineCodeWhat it does
105
def attention():
๐Ÿงฉ Function DEFINES a function attention(). Python only remembers it here - its body runs later, each time attention() is called.
107
for n, r in records.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary records; n, r get one pair each round
108
if category(bmi_of(r)) != "Normal":
๐Ÿ”€ Decision CHECKS whether category(bmi_of(r)) is not equal to "Normal". If True, the indented lines below run; otherwise they are skipped
109
print(f"{n:<9} BMI {bmi_of(r):<5} {category(bmi_of(r))}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<9} BMI {bmi_of(r):<5} {category(bmi_of(โ€ฆ with the values filled into { } on the screen
delete() - lines 112โ€“114
LineCodeWhat it does
112
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
113
n = input("Name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
114
print("Deleted." if records.pop(n, None) else "Record not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Deleted." if records.pop(n, None) else "Recoโ€ฆ on the screen
Q1. What is BMI and its formula?

Body Mass Index = weight in kg / (height in metres)^2. It is a simple screening indicator of body weight.

Q2. What is BMR?

Basal Metabolic Rate - calories the body needs at rest. Mifflin-St Jeor: 10W + 6.25H - 5A + 5 (male) or - 161 (female).

Q3. How is the ideal weight range found?

For BMI 18.5 to 24.9: weight = BMI x height^2, using the student's height in metres.

Q4. Which statistics functions are used?

statistics.mean(), median() and mode() on the list of BMI values (mode on rounded values).

Q5. Why is this not medical advice?

BMI and BMR are general formulas; health decisions need a doctor's examination.

08

Hospital Patient Records (SQL Database)

MySQL (SQL)CREATE DATABASE/TABLEINSERTSELECTWHERELIKE
๐Ÿ“ 104 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 343 output lines๐Ÿ“„ 25+ page report

A complete MySQL script that builds a hospital patient table, loads 12 records and answers ten practical queries about wards, bills and admissions.

โœจ Features
  • Three tables: patient, doctor and appointment with primary keys
  • Patient admission data with ward, disease, admission date and bill
  • Doctor list with department and fee; appointments link patients and doctors
  • Reports: ward-wise patients and revenue, month-wise admissions, disease frequency
  • Date functions to find days admitted; discounts with UPDATE; discharge with DELETE
  • Join queries: which doctor treats which patient and doctor-wise income
โ˜ฐ Main menu
M1Create Tablespatient, doctor, appointment with keys and constraints
M2Insert Data12 patients, 5 doctors, 10 appointments
M3Patient QueriesICU patients, age filters, name patterns
M4Billing QueriesBETWEEN, aggregates, ward-wise revenue
M5Date ReportsMonth-wise admissions, days admitted
M6UpdatesChildren discount, bill corrections, discharge
M7Doctor ReportsJoins of appointment with patient and doctor
M8SummaryDisease frequency and remaining patients
M9Views & Sub-queriesICU view, above-average bills, idle doctors
M10Formatted ReportsUPPER, CONCAT, revenue share %
๐ŸŽฏ Objectives
  • Design a table with suitable data types and constraints
  • Use LIKE, BETWEEN, IN and aggregate functions
  • Perform UPDATE and DELETE safely with WHERE
๐Ÿ“š Data dictionary
NameTypePurpose
patientTABLEpid INT PK, pname VARCHAR(30) NOT NULL, age INT, gender CHAR(1), disease VARCHAR(25), ward VARCHAR(10), admit_date DATE, bill DECIMAL(9,2)
doctorTABLEdid INT PK, dname VARCHAR(30), department VARCHAR(20), fee INT
appointmentTABLEapp_id INT PK, pid INT, did INT, app_date DATE
Why it matters: Covers almost every SQL command in the Class XI syllabus in one realistic database.
-- =====================================================================
--   HOSPITAL PATIENT RECORDS  (MySQL)  -  Class XI IP
-- =====================================================================
-- M1 : Create tables
DROP DATABASE IF EXISTS hospital_db;
CREATE DATABASE hospital_db;
USE hospital_db;
CREATE TABLE patient (
    pid INT PRIMARY KEY, pname VARCHAR(30) NOT NULL, age INT, gender CHAR(1),
    disease VARCHAR(25), ward VARCHAR(10), admit_date DATE, bill DECIMAL(9,2));
CREATE TABLE doctor (did INT PRIMARY KEY, dname VARCHAR(30), department VARCHAR(20), fee INT);
CREATE TABLE appointment (app_id INT PRIMARY KEY, pid INT, did INT, app_date DATE);

-- M2 : Insert data
INSERT INTO patient VALUES
(101,'Ramesh Gupta',54,'M','Diabetes','General','2026-07-04',12500.00),
(102,'Sunita Devi',36,'F','Fever','General','2026-07-09',4200.00),
(103,'Aarav Singh',8,'M','Fracture','Children','2026-07-12',18000.00),
(104,'Meena Kapoor',62,'F','Heart Disease','ICU','2026-07-15',96000.00),
(105,'Imran Khan',41,'M','Typhoid','General','2026-08-02',7800.00),
(106,'Kavita Rao',29,'F','Dengue','Private','2026-08-05',21500.00),
(107,'Harpreet Kaur',47,'F','Diabetes','Private','2026-08-11',15200.00),
(108,'Vikas Jain',33,'M','Appendicitis','Private','2026-08-19',45000.00),
(109,'Neha Bansal',5,'F','Fever','Children','2026-09-01',3600.00),
(110,'Suresh Yadav',70,'M','Heart Disease','ICU','2026-09-06',120000.00),
(111,'Anita Das',58,'F','Typhoid','General','2026-09-14',8300.00),
(112,'Rohit Mehra',25,'M','Fracture','Private','2026-09-21',32000.00);
INSERT INTO doctor VALUES (1,'Dr. A. Sharma','Cardiology',1200), (2,'Dr. P. Nair','Orthopaedics',900),
(3,'Dr. S. Khan','General Medicine',600), (4,'Dr. R. Iyer','Paediatrics',700), (5,'Dr. M. Gill','Surgery',1500);
INSERT INTO appointment VALUES (1,104,1,'2026-07-15'), (2,110,1,'2026-09-06'), (3,103,2,'2026-07-12'),
(4,112,2,'2026-09-21'), (5,101,3,'2026-07-04'), (6,105,3,'2026-08-02'), (7,111,3,'2026-09-14'),
(8,109,4,'2026-09-01'), (9,103,4,'2026-07-13'), (10,108,5,'2026-08-19');

-- M3 : Patient queries
SELECT pid, pname, age, disease FROM patient WHERE ward = 'ICU';
SELECT pname, age FROM patient WHERE age > 50 ORDER BY age DESC;
SELECT pname, disease FROM patient WHERE pname LIKE 'S%';
SELECT pname, disease FROM patient WHERE disease IN ('Diabetes','Typhoid');
SELECT pname, age, ward FROM patient WHERE gender = 'F' AND age BETWEEN 30 AND 60;

-- M4 : Billing queries
SELECT pname, bill FROM patient WHERE bill BETWEEN 10000 AND 30000 ORDER BY bill;
SELECT COUNT(*) AS Patients, SUM(bill) AS Total, ROUND(AVG(bill),2) AS Avg_Bill, MAX(bill) AS Max_Bill, MIN(bill) AS Min_Bill FROM patient;
SELECT ward, COUNT(*) AS Patients, SUM(bill) AS Total_Bill FROM patient GROUP BY ward ORDER BY Total_Bill DESC;
SELECT ward, ROUND(AVG(bill),2) AS Avg_Bill FROM patient GROUP BY ward HAVING AVG(bill) > 20000;

-- M5 : Date reports
SELECT MONTHNAME(admit_date) AS Month, COUNT(*) AS Admissions FROM patient GROUP BY MONTHNAME(admit_date), MONTH(admit_date) ORDER BY MONTH(admit_date);
SELECT pname, admit_date, DATEDIFF('2026-09-30', admit_date) AS Days_Admitted FROM patient ORDER BY Days_Admitted DESC LIMIT 5;
SELECT pname, DAYNAME(admit_date) AS Admitted_On FROM patient WHERE ward = 'Private';

-- M6 : Updates
UPDATE patient SET bill = bill * 0.90 WHERE age < 18;
SELECT pname, age, bill FROM patient WHERE age < 18;
UPDATE patient SET ward = 'General' WHERE pid = 106;
DELETE FROM patient WHERE pid = 105;
SELECT COUNT(*) AS Remaining_Patients FROM patient;

-- M7 : Doctor reports (joins)
SELECT a.app_id, p.pname, d.dname, d.department, a.app_date
FROM appointment a, patient p, doctor d
WHERE a.pid = p.pid AND a.did = d.did ORDER BY a.app_date;
SELECT d.dname, COUNT(*) AS Appointments, COUNT(*) * d.fee AS Income
FROM doctor d, appointment a WHERE d.did = a.did GROUP BY d.dname, d.fee ORDER BY Income DESC, d.dname;

-- M8 : Summary
SELECT disease, COUNT(*) AS Cases FROM patient GROUP BY disease ORDER BY Cases DESC, disease;
SELECT gender, COUNT(*) AS Patients, ROUND(AVG(age),1) AS Avg_Age FROM patient GROUP BY gender;

-- M9 : Views and sub-queries
CREATE VIEW icu_patients AS
    SELECT pid, pname, age, bill
    FROM patient
    WHERE ward = 'ICU';
SELECT * FROM icu_patients;
SELECT pname, bill
FROM patient
WHERE bill > (SELECT AVG(bill) FROM patient)
ORDER BY bill DESC;
SELECT pname, age
FROM patient
WHERE age = (SELECT MIN(age) FROM patient)
   OR age = (SELECT MAX(age) FROM patient);
SELECT dname, department
FROM doctor
WHERE did NOT IN (SELECT did FROM appointment WHERE app_date >= '2026-09-01');

-- M10 : Formatted reports with functions
SELECT UPPER(pname) AS Patient,
       CONCAT(age, ' yrs / ', gender) AS Age_Gender,
       ROUND(bill / 1000, 1) AS Bill_in_Thousand
FROM patient
WHERE ward IN ('ICU', 'Private')
ORDER BY bill DESC;
SELECT ward,
       COUNT(*) AS Patients,
       ROUND(SUM(bill) / (SELECT SUM(bill) FROM patient) * 100, 1) AS Revenue_Percent
FROM patient
GROUP BY ward
ORDER BY Revenue_Percent DESC;
SELECT LEFT(pname, LOCATE(' ', pname) - 1) AS First_Name, LENGTH(pname) AS Name_Length
FROM patient
WHERE LENGTH(pname) > 11;

        
  1. Start
  2. Create hospital_db and three tables
  3. Insert patients, doctors and appointments
  4. Run patient and billing queries
  5. Run date-based reports
  6. UPDATE bills and DELETE discharged patient
  7. Run join queries for doctor reports
  8. Stop
#Test case / inputExpected resultStatus
1ICU patientsMeena Kapoor and Suresh YadavPASS
2Age > 50 orderedEldest firstPASS
3Ward-wise revenueTotals per wardPASS
4Bill BETWEEN 10000 AND 30000Matching patientsPASS
5Month-wise admissionsJul, Aug, Sep countsPASS
610 % child discountBills of age < 18 reducedPASS
7Join doctor-patientEach appointment with both namesPASS
8Doctor-wise incomefee x appointmentsPASS
9Delete patient 10511 patients remainPASS
โš  Limitations
  • Sample data only
  • No front-end
  • Foreign keys not enforced to keep the script simple
  • Bills are not itemised
๐Ÿš€ Future scope
  • Python + MySQL front-end for reception desk
  • Pharmacy and lab-test tables
  • Discharge summary printing
  • Bed availability dashboard

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
๐Ÿ“Œ HOSPITAL PATIENT RECORDS (MySQL) - Class XI IP / M1 : Create tables
1
DDL ยท structure
DROP DATABASE IF EXISTS hospital_db;

Deletes the database hospital_db completely (structure + data). It cannot be undone.

โœ” Result: Query OK, 0 rows affected
2
DDL ยท structure
CREATE DATABASE hospital_db;

Creates a new, empty database (a folder for tables) named hospital_db.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
3
Command
USE hospital_db;

Selects the database hospital_db - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
4
DDL ยท structure
CREATE TABLE patient (
    pid INT PRIMARY KEY, pname VARCHAR(30) NOT NULL, age INT, gender CHAR(1),
    disease VARCHAR(25), ward VARCHAR(10), admit_date DATE, bill DECIMAL(9,2));

Creates a new table patient with 8 columns. Each column gets a name and a data type:

  • pid โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • pname โ†’ VARCHAR(30) (text up to 30 characters); NOT NULL - must be filled
  • age โ†’ INT (whole numbers)
  • gender โ†’ CHAR(1) (text up to 1 characters)
  • disease โ†’ VARCHAR(25) (text up to 25 characters)
  • ward โ†’ VARCHAR(10) (text up to 10 characters)
  • admit_date โ†’ DATE (date (YYYY-MM-DD))
  • bill โ†’ DECIMAL(9,2) (decimal number, 9 digits in all with 2 after the point)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
5
DDL ยท structure
CREATE TABLE doctor (did INT PRIMARY KEY, dname VARCHAR(30), department VARCHAR(20), fee INT);

Creates a new table doctor with 4 columns. Each column gets a name and a data type:

  • did โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • dname โ†’ VARCHAR(30) (text up to 30 characters)
  • department โ†’ VARCHAR(20) (text up to 20 characters)
  • fee โ†’ INT (whole numbers)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
6
DDL ยท structure
CREATE TABLE appointment (app_id INT PRIMARY KEY, pid INT, did INT, app_date DATE);

Creates a new table appointment with 4 columns. Each column gets a name and a data type:

  • app_id โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • pid โ†’ INT (whole numbers)
  • did โ†’ INT (whole numbers)
  • app_date โ†’ DATE (date (YYYY-MM-DD))
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
๐Ÿ“Œ M2 : Insert data
7
DML ยท data change
INSERT INTO patient VALUES
(101,'Ramesh Gupta',54,'M','Diabetes','General','2026-07-04',12500.00),
(102,'Sunita Devi',36,'F','Fever','General','2026-07-09',4200.00),
(103,'Aarav Singh',8,'M','Fracture','Children','2026-07-12',18000.00),
(104,'Meena Kapoor',62,'F','Heart Disease','ICU','2026-07-15',96000.00),
(105,'Imran Khan',41,'M','Typhoid','General','2026-08-02',7800.00),
(106,'Kavita Rao',29,'F','Dengue','Private','2026-08-05',21500.00),
(107,'Harpreet Kaur',47,'F','Diabetes','Private','2026-08-11',15200.00),
(108,'Vikas Jain',33,'M','Appendicitis','Private','2026-08-19',45000.00),
(109โ€ฆ

Adds 12 new rows into table patient.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 12 rows affected ยท Records: 12 Duplicates: 0 Warnings: 0
8
DML ยท data change
INSERT INTO doctor VALUES (1,'Dr. A. Sharma','Cardiology',1200), (2,'Dr. P. Nair','Orthopaedics',900),
(3,'Dr. S. Khan','General Medicine',600), (4,'Dr. R. Iyer','Paediatrics',700), (5,'Dr. M. Gill','Surgery',1500);

Adds 5 new rows into table doctor.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 5 rows affected ยท Records: 5 Duplicates: 0 Warnings: 0
9
DML ยท data change
INSERT INTO appointment VALUES (1,104,1,'2026-07-15'), (2,110,1,'2026-09-06'), (3,103,2,'2026-07-12'),
(4,112,2,'2026-09-21'), (5,101,3,'2026-07-04'), (6,105,3,'2026-08-02'), (7,111,3,'2026-09-14'),
(8,109,4,'2026-09-01'), (9,103,4,'2026-07-13'), (10,108,5,'2026-08-19');

Adds 10 new rows into table appointment.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 10 rows affected ยท Records: 10 Duplicates: 0 Warnings: 0
๐Ÿ“Œ M3 : Patient queries
10
Query ยท read only
SELECT pid, pname, age, disease FROM patient WHERE ward = 'ICU';

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE ward = 'ICU' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pid, pname, age, disease โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
11
Query ยท read only
SELECT pname, age FROM patient WHERE age > 50 ORDER BY age DESC;

Fetches rows from patient that satisfy a condition, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE age > 50 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, age โ†’ picks the columns / calculates the values to show.
  4. ORDER BY age DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
12
Query ยท read only
SELECT pname, disease FROM patient WHERE pname LIKE 'S%';

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE pname LIKE 'S%' (starts with "S") โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, disease โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
13
Query ยท read only
SELECT pname, disease FROM patient WHERE disease IN ('Diabetes','Typhoid');

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE disease IN ('Diabetes','Typhoid') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, disease โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
14
Query ยท read only
SELECT pname, age, ward FROM patient WHERE gender = 'F' AND age BETWEEN 30 AND 60;

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE gender = 'F' AND age BETWEEN 30 AND 60 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, age, ward โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 3 rows in set
๐Ÿ“Œ M4 : Billing queries
15
Query ยท read only
SELECT pname, bill FROM patient WHERE bill BETWEEN 10000 AND 30000 ORDER BY bill;

Fetches rows from patient that satisfy a condition, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE bill BETWEEN 10000 AND 30000 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, bill โ†’ picks the columns / calculates the values to show.
  4. ORDER BY bill โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
16
Query ยท read only
SELECT COUNT(*) AS Patients, SUM(bill) AS Total, ROUND(AVG(bill),2) AS Avg_Bill, MAX(bill) AS Max_Bill, MIN(bill) AS Min_Bill FROM patient;

Fetches the summary values from patient.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. SELECT COUNT(*) AS Patients, SUM(bill) AS Total, ROUND(AVG(bill),2) AS Avg_Bill, MAX(bill) AS Max_Bill, MIN(bill) AS Min_Bill โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: COUNT(*) counts all rows; SUM() adds the values; ROUND(x, d) rounds x to d decimal places; AVG() finds the average; MAX() finds the largest value; MIN() finds the smallest value.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 1 row in set
17
Query ยท read only
SELECT ward, COUNT(*) AS Patients, SUM(bill) AS Total_Bill FROM patient GROUP BY ward ORDER BY Total_Bill DESC;

Fetches rows from patient, grouped by ward, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY ward โ†’ makes groups: rows with the same ward go into one group (one output row per group).
  3. SELECT ward, COUNT(*) AS Patients, SUM(bill) AS Total_Bill โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows; SUM() adds the values.
  5. ORDER BY Total_Bill DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
18
Query ยท read only
SELECT ward, ROUND(AVG(bill),2) AS Avg_Bill FROM patient GROUP BY ward HAVING AVG(bill) > 20000;

Fetches rows from patient, grouped by ward.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY ward โ†’ makes groups: rows with the same ward go into one group (one output row per group).
  3. HAVING AVG(bill) > 20000 โ†’ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
  4. SELECT ward, ROUND(AVG(bill),2) AS Avg_Bill โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
๐Ÿ“Œ M5 : Date reports
19
Query ยท read only
SELECT MONTHNAME(admit_date) AS Month, COUNT(*) AS Admissions FROM patient GROUP BY MONTHNAME(admit_date), MONTH(admit_date) ORDER BY MONTH(admit_date);

Fetches rows from patient, grouped by MONTHNAME(admit_date), MONTH(admit_date), in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY MONTHNAME(admit_date), MONTH(admit_date) โ†’ makes groups: rows with the same MONTHNAME(admit_date), MONTH(admit_date) go into one group (one output row per group).
  3. SELECT MONTHNAME(admit_date) AS Month, COUNT(*) AS Admissions โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: MONTHNAME() gives the month name; COUNT(*) counts all rows.
  5. ORDER BY MONTH(admit_date) โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 3 rows in set
20
Query ยท read only
SELECT pname, admit_date, DATEDIFF('2026-09-30', admit_date) AS Days_Admitted FROM patient ORDER BY Days_Admitted DESC LIMIT 5;

Fetches rows from patient, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. SELECT pname, admit_date, DATEDIFF('2026-09-30', admit_date) AS Days_Admitted โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: DATEDIFF(d1, d2) gives days between two dates.
  4. ORDER BY Days_Admitted DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
  5. LIMIT 5 โ†’ shows only the first 5 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 5 rows in set
21
Query ยท read only
SELECT pname, DAYNAME(admit_date) AS Admitted_On FROM patient WHERE ward = 'Private';

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE ward = 'Private' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, DAYNAME(admit_date) AS Admitted_On โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: DAYNAME() gives the weekday name.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
๐Ÿ“Œ M6 : Updates
22
DML ยท data change
UPDATE patient SET bill = bill * 0.90 WHERE age < 18;

Changes existing data in table patient.

  1. UPDATE patient โ†’ picks the table.
  2. WHERE age < 18 โ†’ finds only the rows that match.
  3. SET bill = bill * 0.90 โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE age < 18 โ†’ 2 row(s) matched.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1218000.00โœŽ
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013600.00โœŽ
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: Query OK, 2 rows affected ยท Rows matched: 2 Changed: 2 Warnings: 0
23
Query ยท read only
SELECT pname, age, bill FROM patient WHERE age < 18;

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE age < 18 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, age, bill โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 12 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
24
DML ยท data change
UPDATE patient SET ward = 'General' WHERE pid = 106;

Changes existing data in table patient.

  1. UPDATE patient โ†’ picks the table.
  2. WHERE pid = 106 โ†’ finds only the rows that match.
  3. SET ward = 'General' โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE pid = 106 โ†’ 1 row(s) matched.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00
106Kavita Rao29FDenguePrivate2026-08-0521500.00โœŽ
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: Query OK, 1 row affected ยท Rows matched: 1 Changed: 1 Warnings: 0
25
DML ยท data change
DELETE FROM patient WHERE pid = 105;

Removes rows from table patient.

  1. FROM patient โ†’ picks the table.
  2. WHERE pid = 105 โ†’ finds the matching rows.
  3. Those rows are removed permanently โ†’ "Query OK, n rows affected".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE pid = 105 โ†’ 1 row(s) matched.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
105Imran Khan41MTyphoidGeneral2026-08-027800.00๐Ÿ—‘
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: Query OK, 1 row affected
26
Query ยท read only
SELECT COUNT(*) AS Remaining_Patients FROM patient;

Fetches the summary values from patient.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. SELECT COUNT(*) AS Remaining_Patients โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: COUNT(*) counts all rows.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 1 row in set
๐Ÿ“Œ M7 : Doctor reports (joins)
27
Query ยท read only
SELECT a.app_id, p.pname, d.dname, d.department, a.app_date
FROM appointment a, patient p, doctor d
WHERE a.pid = p.pid AND a.did = d.did ORDER BY a.app_date;

Fetches rows from appointment that satisfy a condition, in sorted order.

  1. FROM appointment a, patient p, doctor d โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE a.pid = p.pid AND a.did = d.did โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT a.app_id, p.pname, d.dname, d.department, a.app_date โ†’ picks the columns / calculates the values to show.
  4. ORDER BY a.app_date โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: The tables are joined: appointment a, patient p, doctor d โ†’ 550 combined rows.

app_idpiddidapp_datepidpnameagegenderdiseasewardadmit_datebilldiddnamedepartmentfee
110412026-07-15101Ramesh Gupta54MDiabetesGeneral2026-07-04125001Dr. A. SharmaCardiology1200
110412026-07-15101Ramesh Gupta54MDiabetesGeneral2026-07-04125002Dr. P. NairOrthopaedics900
110412026-07-15101Ramesh Gupta54MDiabetesGeneral2026-07-04125003Dr. S. KhanGeneral Medicine600
110412026-07-15101Ramesh Gupta54MDiabetesGeneral2026-07-04125004Dr. R. IyerPaediatrics700
110412026-07-15101Ramesh Gupta54MDiabetesGeneral2026-07-04125005Dr. M. GillSurgery1500
110412026-07-15102Sunita Devi36FFeverGeneral2026-07-0942001Dr. A. SharmaCardiology1200
110412026-07-15102Sunita Devi36FFeverGeneral2026-07-0942002Dr. P. NairOrthopaedics900
110412026-07-15102Sunita Devi36FFeverGeneral2026-07-0942003Dr. S. KhanGeneral Medicine600
110412026-07-15102Sunita Devi36FFeverGeneral2026-07-0942004Dr. R. IyerPaediatrics700
110412026-07-15102Sunita Devi36FFeverGeneral2026-07-0942005Dr. M. GillSurgery1500
110412026-07-15103Aarav Singh8MFractureChildren2026-07-12162001Dr. A. SharmaCardiology1200
110412026-07-15103Aarav Singh8MFractureChildren2026-07-12162002Dr. P. NairOrthopaedics900
110412026-07-15103Aarav Singh8MFractureChildren2026-07-12162003Dr. S. KhanGeneral Medicine600
110412026-07-15103Aarav Singh8MFractureChildren2026-07-12162004Dr. R. IyerPaediatrics700
+ 536 more rows
โœ” Result: 9 rows in set
28
Query ยท read only
SELECT d.dname, COUNT(*) AS Appointments, COUNT(*) * d.fee AS Income
FROM doctor d, appointment a WHERE d.did = a.did GROUP BY d.dname, d.fee ORDER BY Income DESC, d.dname;

Fetches rows from doctor that satisfy a condition, grouped by d.dname, d.fee, in sorted order.

  1. FROM doctor d, appointment a โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE d.did = a.did โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. GROUP BY d.dname, d.fee โ†’ makes groups: rows with the same d.dname, d.fee go into one group (one output row per group).
  4. SELECT d.dname, COUNT(*) AS Appointments, COUNT(*) * d.fee AS Income โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: COUNT(*) counts all rows.
  6. ORDER BY Income DESC, d.dname โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: The tables are joined: doctor d, appointment a โ†’ 50 combined rows.

diddnamedepartmentfeeapp_idpiddidapp_date
1Dr. A. SharmaCardiology1200110412026-07-15
1Dr. A. SharmaCardiology1200211012026-09-06
1Dr. A. SharmaCardiology1200310322026-07-12
1Dr. A. SharmaCardiology1200411222026-09-21
1Dr. A. SharmaCardiology1200510132026-07-04
1Dr. A. SharmaCardiology1200610532026-08-02
1Dr. A. SharmaCardiology1200711132026-09-14
1Dr. A. SharmaCardiology1200810942026-09-01
1Dr. A. SharmaCardiology1200910342026-07-13
1Dr. A. SharmaCardiology12001010852026-08-19
2Dr. P. NairOrthopaedics900110412026-07-15
2Dr. P. NairOrthopaedics900211012026-09-06
2Dr. P. NairOrthopaedics900310322026-07-12
2Dr. P. NairOrthopaedics900411222026-09-21
+ 36 more rows
โœ” Result: 5 rows in set
๐Ÿ“Œ M8 : Summary
29
Query ยท read only
SELECT disease, COUNT(*) AS Cases FROM patient GROUP BY disease ORDER BY Cases DESC, disease;

Fetches rows from patient, grouped by disease, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY disease โ†’ makes groups: rows with the same disease go into one group (one output row per group).
  3. SELECT disease, COUNT(*) AS Cases โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
  5. ORDER BY Cases DESC, disease โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 7 rows in set
30
Query ยท read only
SELECT gender, COUNT(*) AS Patients, ROUND(AVG(age),1) AS Avg_Age FROM patient GROUP BY gender;

Fetches rows from patient, grouped by gender.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY gender โ†’ makes groups: rows with the same gender go into one group (one output row per group).
  3. SELECT gender, COUNT(*) AS Patients, ROUND(AVG(age),1) AS Avg_Age โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
๐Ÿ“Œ M9 : Views and sub-queries
31
DDL ยท structure
CREATE VIEW icu_patients AS
    SELECT pid, pname, age, bill
    FROM patient
    WHERE ward = 'ICU';

Creates a VIEW icu_patients - a saved SELECT query that behaves like a virtual table.

  • The query saved inside the view: Fetches rows from patient that satisfy a condition.
  • FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  • WHERE ward = 'ICU' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  • SELECT pid, pname, age, bill โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: Query OK, 0 rows affected
32
Query ยท read only
SELECT * FROM icu_patients;

Fetches rows from icu_patients.

  1. FROM icu_patients โ†’ MySQL first opens table icu_patients and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
โœ” Result: 2 rows in set
33
Query ยท read only
SELECT pname, bill
FROM patient
WHERE bill > (SELECT AVG(bill) FROM patient)
ORDER BY bill DESC;

Fetches rows from patient that satisfy a condition, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE bill > (SELECT AVG(bill) FROM patient) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, bill โ†’ picks the columns / calculates the values to show.
  4. Functions used: AVG() finds the average.
  5. ORDER BY bill DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 3 rows in set
34
Query ยท read only
SELECT pname, age
FROM patient
WHERE age = (SELECT MIN(age) FROM patient)
   OR age = (SELECT MAX(age) FROM patient);

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE age = (SELECT MIN(age) FROM patient) OR age = (SELECT MAX(age) FROM patient) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT pname, age โ†’ picks the columns / calculates the values to show.
  4. Functions used: MIN() finds the smallest value; MAX() finds the largest value.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 2 rows in set
35
Query ยท read only
SELECT dname, department
FROM doctor
WHERE did NOT IN (SELECT did FROM appointment WHERE app_date >= '2026-09-01');

Fetches rows from doctor that satisfy a condition.

  1. FROM doctor โ†’ MySQL first opens table doctor and looks at all its rows.
  2. WHERE did NOT IN (SELECT did FROM appointment WHERE app_date >= '2026-09-01') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT dname, department โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table doctor - all 5 rows are taken.

diddnamedepartmentfee
1Dr. A. SharmaCardiology1200
2Dr. P. NairOrthopaedics900
3Dr. S. KhanGeneral Medicine600
4Dr. R. IyerPaediatrics700
5Dr. M. GillSurgery1500
โœ” Result: 1 row in set
๐Ÿ“Œ M10 : Formatted reports with functions
36
Query ยท read only
SELECT UPPER(pname) AS Patient,
       CONCAT(age, ' yrs / ', gender) AS Age_Gender,
       ROUND(bill / 1000, 1) AS Bill_in_Thousand
FROM patient
WHERE ward IN ('ICU', 'Private')
ORDER BY bill DESC;

Fetches rows from patient that satisfy a condition, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE ward IN ('ICU', 'Private') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT UPPER(pname) AS Patient, CONCAT(age, ' yrs / ', gender) AS Age_Gender, ROUND(bill / 1000, 1) AS Bill_in_Thousand โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: UPPER() changes text to capitals; CONCAT() joins texts together; ROUND(x, d) rounds x to d decimal places.
  5. ORDER BY bill DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 5 rows in set
37
Query ยท read only
SELECT ward,
       COUNT(*) AS Patients,
       ROUND(SUM(bill) / (SELECT SUM(bill) FROM patient) * 100, 1) AS Revenue_Percent
FROM patient
GROUP BY ward
ORDER BY Revenue_Percent DESC;

Fetches rows from patient, grouped by ward, in sorted order.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. GROUP BY ward โ†’ makes groups: rows with the same ward go into one group (one output row per group).
  3. SELECT ward, COUNT(*) AS Patients, ROUND(SUM(bill) / (SELECT SUM(bill) FROM patient) * 100, 1) AS Revenue_Percent โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; SUM() adds the values.
  5. ORDER BY Revenue_Percent DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
38
Query ยท read only
SELECT LEFT(pname, LOCATE(' ', pname) - 1) AS First_Name, LENGTH(pname) AS Name_Length
FROM patient
WHERE LENGTH(pname) > 11;

Fetches rows from patient that satisfy a condition.

  1. FROM patient โ†’ MySQL first opens table patient and looks at all its rows.
  2. WHERE LENGTH(pname) > 11 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT LEFT(pname, LOCATE(' ', pname) - 1) AS First_Name, LENGTH(pname) AS Name_Length โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: LEFT(text, n) takes n characters from the left; LENGTH() counts characters.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table patient - all 11 rows are taken.

pidpnameagegenderdiseasewardadmit_datebill
101Ramesh Gupta54MDiabetesGeneral2026-07-0412500.00
102Sunita Devi36FFeverGeneral2026-07-094200.00
103Aarav Singh8MFractureChildren2026-07-1216200.00
104Meena Kapoor62FHeart DiseaseICU2026-07-1596000.00
106Kavita Rao29FDengueGeneral2026-08-0521500.00
107Harpreet Kaur47FDiabetesPrivate2026-08-1115200.00
108Vikas Jain33MAppendicitisPrivate2026-08-1945000.00
109Neha Bansal5FFeverChildren2026-09-013240.00
110Suresh Yadav70MHeart DiseaseICU2026-09-06120000.00
111Anita Das58FTyphoidGeneral2026-09-148300.00
112Rohit Mehra25MFracturePrivate2026-09-2132000.00
โœ” Result: 4 rows in set
Q1. Why is pid a primary key?

Each patient must be identified uniquely; a primary key cannot be duplicate or NULL.

Q2. What does DATEDIFF() return?

The number of days between two dates, used here to find how long a patient has been admitted.

Q3. How is doctor-wise income calculated?

Join doctor and appointment, then COUNT(*) x fee grouped by doctor.

Q4. What is the use of MONTHNAME()?

It returns the name of the month from a date, used for month-wise admission reports.

Q5. Difference between COUNT(*) and COUNT(column)?

COUNT(*) counts all rows; COUNT(column) counts only rows where that column is not NULL.

09

Employee Payroll Database (SQL)

MySQL (SQL)CREATE TABLEINSERTexpressions in SELECTALTER TABLEUPDATE
๐Ÿ“ 102 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 376 output lines๐Ÿ“„ 25+ page report

A MySQL payroll database that calculates DA, HRA and net salary with SQL expressions and produces department-wise salary reports.

โœจ Features
  • Department and employee tables with keys
  • Salary slip computed in SQL: DA 40 %, HRA 20 %, PF 12 %, net salary
  • Department-wise head count, average and total pay with HAVING filters
  • Bonus column added with ALTER TABLE and filled with UPDATE
  • Experience calculated from date of joining; increments by experience
  • Join of employee and department tables for location-wise report
โ˜ฐ Main menu
M1Create Tablesdept and employee tables
M2Insert Data5 departments and 12 employees
M3Salary SlipsDA, HRA, PF and net salary
M4Department ReportsGROUP BY, HAVING, totals
M5Service RecordsExperience and joining-year queries
M6Pay RevisionALTER, bonus and increment UPDATEs
M7Join ReportsEmployees with department location
M8Search QueriesLIKE, IN, NULL, DISTINCT
M9Views & Sub-queriesSalary register view, above-average pay
M10Formatted ReportsFORMAT, MONTHNAME, share %
๐ŸŽฏ Objectives
  • Use arithmetic expressions in SELECT
  • Apply GROUP BY with HAVING
  • Alter a table and update rows conditionally
๐Ÿ“š Data dictionary
NameTypePurpose
deptTABLEdeptno INT PK, dname VARCHAR(15), location VARCHAR(15)
employeeTABLEempno INT PK, ename VARCHAR(30), deptno INT, designation VARCHAR(20), basic INT, doj DATE, mobile CHAR(10), bonus INT DEFAULT 0
Why it matters: Demonstrates calculated columns, ALTER TABLE and GROUP BY ... HAVING on a business problem.
-- =====================================================================
--   EMPLOYEE PAYROLL DATABASE  (MySQL)  -  Class XI IP
-- =====================================================================
-- M1 : Create tables
DROP DATABASE IF EXISTS payroll_db;
CREATE DATABASE payroll_db;
USE payroll_db;
CREATE TABLE dept (deptno INT PRIMARY KEY, dname VARCHAR(15), location VARCHAR(15));
CREATE TABLE employee (
    empno INT PRIMARY KEY, ename VARCHAR(30) NOT NULL, deptno INT, designation VARCHAR(20),
    basic INT, doj DATE, mobile CHAR(10));

-- M2 : Insert data
INSERT INTO dept VALUES (10,'Accounts','Delhi'), (20,'Sales','Mumbai'), (30,'IT','Bengaluru'), (40,'HR','Delhi'), (50,'Admin','Noida');
INSERT INTO employee VALUES
(1,'Anil Sharma',10,'Manager',55000,'2015-04-01','9810011111'),
(2,'Poonam Arora',10,'Clerk',28000,'2019-07-15',NULL),
(3,'Deepak Verma',20,'Executive',32000,'2018-01-10','9811122222'),
(4,'Rina Das',20,'Manager',60000,'2012-11-05','9812233333'),
(5,'Manoj Kumar',30,'Developer',48000,'2020-06-22','9813344444'),
(6,'Sakshi Jain',30,'Developer',45000,'2021-02-01',NULL),
(7,'Tarun Malik',30,'Team Lead',70000,'2014-08-18','9815566666'),
(8,'Geeta Nair',40,'Officer',36000,'2017-09-09','9816677777'),
(9,'Faisal Ali',20,'Executive',30000,'2022-03-14','9817788888'),
(10,'Lata Mishra',40,'Manager',52000,'2013-12-02','9818899999'),
(11,'Kunal Bose',50,'Clerk',26000,'2023-05-08',NULL),
(12,'Ritu Saxena',30,'Manager',82000,'2011-01-17','9819900000');

-- M3 : Salary slips
SELECT ename, basic, basic*0.40 AS DA, basic*0.20 AS HRA, basic*0.12 AS PF,
       basic + basic*0.40 + basic*0.20 - basic*0.12 AS Net_Salary
FROM employee ORDER BY Net_Salary DESC LIMIT 5;
SELECT ename, ROUND((basic*1.48)*12) AS Annual_Net FROM employee WHERE designation = 'Developer';

-- M4 : Department reports
SELECT deptno, COUNT(*) AS Employees, ROUND(AVG(basic)) AS Avg_Basic, SUM(basic) AS Total_Basic FROM employee GROUP BY deptno;
SELECT deptno, AVG(basic) AS Avg_Basic FROM employee GROUP BY deptno HAVING AVG(basic) > 45000;
SELECT designation, COUNT(*) AS Total FROM employee GROUP BY designation ORDER BY Total DESC, designation;
SELECT MAX(basic) AS Highest, MIN(basic) AS Lowest, MAX(basic) - MIN(basic) AS Difference FROM employee;

-- M5 : Service records
SELECT ename, doj, YEAR('2026-04-01') - YEAR(doj) AS Experience FROM employee ORDER BY doj LIMIT 6;
SELECT ename, doj FROM employee WHERE YEAR(doj) < 2016 ORDER BY doj;
SELECT YEAR(doj) AS Join_Year, COUNT(*) AS Joined FROM employee GROUP BY YEAR(doj) ORDER BY Join_Year;

-- M6 : Pay revision
ALTER TABLE employee ADD bonus INT DEFAULT 0;
UPDATE employee SET bonus = basic * 0.10 WHERE designation = 'Manager';
SELECT ename, designation, bonus FROM employee WHERE bonus > 0;
UPDATE employee SET basic = basic * 1.05 WHERE deptno = 30;
SELECT ename, basic FROM employee WHERE deptno = 30;

-- M7 : Join reports
SELECT e.ename, d.dname, d.location, e.basic FROM employee e, dept d WHERE e.deptno = d.deptno ORDER BY d.location, e.ename;
SELECT d.location, COUNT(*) AS Staff, SUM(e.basic) AS Salary_Bill FROM employee e, dept d WHERE e.deptno = d.deptno GROUP BY d.location;
SELECT d.dname, e.ename AS Manager FROM employee e, dept d WHERE e.deptno = d.deptno AND e.designation = 'Manager';

-- M8 : Search queries
SELECT ename FROM employee WHERE ename LIKE '%a';
SELECT ename, designation FROM employee WHERE designation IN ('Clerk','Officer');
SELECT ename FROM employee WHERE mobile IS NULL;
SELECT DISTINCT designation FROM employee ORDER BY designation;
SELECT ename, basic FROM employee WHERE basic = (SELECT MAX(basic) FROM employee);

-- M9 : Views and sub-queries
CREATE VIEW salary_register AS
    SELECT e.empno, e.ename, d.dname, e.basic,
           e.basic * 0.40 AS DA,
           e.basic * 0.20 AS HRA,
           e.basic * 0.12 AS PF,
           e.basic * 1.48 + e.bonus AS Gross_Pay
    FROM employee e, dept d
    WHERE e.deptno = d.deptno;
SELECT * FROM salary_register ORDER BY Gross_Pay DESC;
SELECT ename, basic
FROM employee
WHERE basic > (SELECT AVG(basic) FROM employee)
ORDER BY basic DESC;
SELECT dname
FROM dept
WHERE deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager');

-- M10 : Formatted reports with functions
SELECT UPPER(ename) AS Employee,
       CONCAT('Rs. ', FORMAT(basic, 0)) AS Basic_Pay,
       MONTHNAME(doj) AS Joined_In,
       DAYNAME(doj) AS Day
FROM employee
WHERE deptno IN (10, 40)
ORDER BY ename;
SELECT designation,
       COUNT(*) AS Staff,
       ROUND(SUM(basic) / (SELECT SUM(basic) FROM employee) * 100, 1) AS Share_Percent
FROM employee
GROUP BY designation
ORDER BY Share_Percent DESC;
SELECT SUBSTR(ename, 1, INSTR(ename, ' ') - 1) AS First_Name,
       RIGHT(mobile, 4) AS Mobile_Last4
FROM employee
WHERE mobile IS NOT NULL
LIMIT 6;

        
  1. Start
  2. Create payroll_db, dept and employee tables
  3. Insert department and employee rows
  4. Salary slip query with computed columns
  5. Department-wise aggregate reports
  6. ALTER TABLE and UPDATE bonus / increment
  7. Join and search queries
  8. Stop
#Test case / inputExpected resultStatus
1Top 5 net salariesComputed DA/HRA/PF columnsPASS
2Dept head countCounts per departmentPASS
3HAVING AVG(basic) > 45000Qualifying departmentsPASS
4Bonus 10 % to managersOnly managers get bonusPASS
5Experience > 10 yearsSenior employees listedPASS
65 % increment for ITIT basic pay increasedPASS
7Join with deptEmployee with locationPASS
8mobile IS NULLEmployees without mobilePASS
โš  Limitations
  • Tax deductions are not included
  • Sample data
  • No attendance-based pay
  • Script only, no front-end
๐Ÿš€ Future scope
  • Python front-end to print salary slips
  • Leave and attendance tables
  • Income-tax calculation
  • Export pay register to Excel

MySQL runs the statements one by one, in order; each ends with ;. A SELECT is written SELECT โ†’ FROM โ†’ WHERE but MySQL runs it in this order:

1 FROMโžœ2 WHEREโžœ3 GROUP BYโžœ4 HAVINGโžœ5 SELECTโžœ6 DISTINCTโžœ7 ORDER BYโžœ8 LIMIT
DDL ยท changes structureDML ยท changes dataQuery ยท only reads
๐Ÿ“Œ EMPLOYEE PAYROLL DATABASE (MySQL) - Class XI IP / M1 : Create tables
1
DDL ยท structure
DROP DATABASE IF EXISTS payroll_db;

Deletes the database payroll_db completely (structure + data). It cannot be undone.

โœ” Result: Query OK, 0 rows affected
2
DDL ยท structure
CREATE DATABASE payroll_db;

Creates a new, empty database (a folder for tables) named payroll_db.

  • MySQL checks that no database with this name already exists (otherwise ERROR 1007)
  • An empty database is created โ†’ "Query OK, 1 row affected".
โœ” Result: Query OK, 1 row affected
3
Command
USE payroll_db;

Selects the database payroll_db - all following commands work inside it.

  • MySQL replies "Database changed".
โœ” Result: Database changed
4
DDL ยท structure
CREATE TABLE dept (deptno INT PRIMARY KEY, dname VARCHAR(15), location VARCHAR(15));

Creates a new table dept with 3 columns. Each column gets a name and a data type:

  • deptno โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • dname โ†’ VARCHAR(15) (text up to 15 characters)
  • location โ†’ VARCHAR(15) (text up to 15 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
5
DDL ยท structure
CREATE TABLE employee (
    empno INT PRIMARY KEY, ename VARCHAR(30) NOT NULL, deptno INT, designation VARCHAR(20),
    basic INT, doj DATE, mobile CHAR(10));

Creates a new table employee with 7 columns. Each column gets a name and a data type:

  • empno โ†’ INT (whole numbers); PRIMARY KEY - unique, cannot be empty
  • ename โ†’ VARCHAR(30) (text up to 30 characters); NOT NULL - must be filled
  • deptno โ†’ INT (whole numbers)
  • designation โ†’ VARCHAR(20) (text up to 20 characters)
  • basic โ†’ INT (whole numbers)
  • doj โ†’ DATE (date (YYYY-MM-DD))
  • mobile โ†’ CHAR(10) (text up to 10 characters)
  • The table is empty now - INSERT adds the rows.
โœ” Result: Query OK, 0 rows affected
๐Ÿ“Œ M2 : Insert data
6
DML ยท data change
INSERT INTO dept VALUES (10,'Accounts','Delhi'), (20,'Sales','Mumbai'), (30,'IT','Bengaluru'), (40,'HR','Delhi'), (50,'Admin','Noida');

Adds 5 new rows into table dept.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 5 rows affected ยท Records: 5 Duplicates: 0 Warnings: 0
7
DML ยท data change
INSERT INTO employee VALUES
(1,'Anil Sharma',10,'Manager',55000,'2015-04-01','9810011111'),
(2,'Poonam Arora',10,'Clerk',28000,'2019-07-15',NULL),
(3,'Deepak Verma',20,'Executive',32000,'2018-01-10','9811122222'),
(4,'Rina Das',20,'Manager',60000,'2012-11-05','9812233333'),
(5,'Manoj Kumar',30,'Developer',48000,'2020-06-22','9813344444'),
(6,'Sakshi Jain',30,'Developer',45000,'2021-02-01',NULL),
(7,'Tarun Malik',30,'Team Lead',70000,'2014-08-18','9815566666'),
(8,'Geeta Nair',40,'Officer',36000,'2017-09-09','9816677777'),
(9,'Faisal Ali',20,'Executive',30000,'2022-03-14','9817788888'),
(10,โ€ฆ

Adds 12 new rows into table employee.

  • No column list is given, so the values must be in the same order as the columns of the table.
  • MySQL checks the data type and keys (e.g. a repeated PRIMARY KEY gives ERROR 1062).
  • Text and dates are written inside quotes 'โ€ฆ'; numbers without quotes.
โœ” Result: Query OK, 12 rows affected ยท Records: 12 Duplicates: 0 Warnings: 0
๐Ÿ“Œ M3 : Salary slips
8
Query ยท read only
SELECT ename, basic, basic*0.40 AS DA, basic*0.20 AS HRA, basic*0.12 AS PF,
       basic + basic*0.40 + basic*0.20 - basic*0.12 AS Net_Salary
FROM employee ORDER BY Net_Salary DESC LIMIT 5;

Fetches rows from employee, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. SELECT ename, basic, basic*0.40 AS DA, basic*0.20 AS HRA, basic*0.12 AS PF, basic + basic*0.40 + basic*0.20 - basic*0.12 AS Net_Salary โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. ORDER BY Net_Salary DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
  4. LIMIT 5 โ†’ shows only the first 5 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 5 rows in set
9
Query ยท read only
SELECT ename, ROUND((basic*1.48)*12) AS Annual_Net FROM employee WHERE designation = 'Developer';

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE designation = 'Developer' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, ROUND((basic*1.48)*12) AS Annual_Net โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: ROUND(x, d) rounds x to d decimal places.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 2 rows in set
๐Ÿ“Œ M4 : Department reports
10
Query ยท read only
SELECT deptno, COUNT(*) AS Employees, ROUND(AVG(basic)) AS Avg_Basic, SUM(basic) AS Total_Basic FROM employee GROUP BY deptno;

Fetches rows from employee, grouped by deptno.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. GROUP BY deptno โ†’ makes groups: rows with the same deptno go into one group (one output row per group).
  3. SELECT deptno, COUNT(*) AS Employees, ROUND(AVG(basic)) AS Avg_Basic, SUM(basic) AS Total_Basic โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average; SUM() adds the values.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 5 rows in set
11
Query ยท read only
SELECT deptno, AVG(basic) AS Avg_Basic FROM employee GROUP BY deptno HAVING AVG(basic) > 45000;

Fetches rows from employee, grouped by deptno.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. GROUP BY deptno โ†’ makes groups: rows with the same deptno go into one group (one output row per group).
  3. HAVING AVG(basic) > 45000 โ†’ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
  4. SELECT deptno, AVG(basic) AS Avg_Basic โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: AVG() finds the average.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 1 row in set
12
Query ยท read only
SELECT designation, COUNT(*) AS Total FROM employee GROUP BY designation ORDER BY Total DESC, designation;

Fetches rows from employee, grouped by designation, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. GROUP BY designation โ†’ makes groups: rows with the same designation go into one group (one output row per group).
  3. SELECT designation, COUNT(*) AS Total โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows.
  5. ORDER BY Total DESC, designation โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 6 rows in set
13
Query ยท read only
SELECT MAX(basic) AS Highest, MIN(basic) AS Lowest, MAX(basic) - MIN(basic) AS Difference FROM employee;

Fetches the summary values from employee.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. SELECT MAX(basic) AS Highest, MIN(basic) AS Lowest, MAX(basic) - MIN(basic) AS Difference โ†’ picks the columns / calculates the values to show; aggregate functions summarise ALL the selected rows into ONE result row; AS gives a heading (alias) to a column.
  3. Functions used: MAX() finds the largest value; MIN() finds the smallest value.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 1 row in set
๐Ÿ“Œ M5 : Service records
14
Query ยท read only
SELECT ename, doj, YEAR('2026-04-01') - YEAR(doj) AS Experience FROM employee ORDER BY doj LIMIT 6;

Fetches rows from employee, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. SELECT ename, doj, YEAR('2026-04-01') - YEAR(doj) AS Experience โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  3. Functions used: YEAR() takes the year from a date.
  4. ORDER BY doj โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
  5. LIMIT 6 โ†’ shows only the first 6 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 6 rows in set
15
Query ยท read only
SELECT ename, doj FROM employee WHERE YEAR(doj) < 2016 ORDER BY doj;

Fetches rows from employee that satisfy a condition, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE YEAR(doj) < 2016 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, doj โ†’ picks the columns / calculates the values to show.
  4. Functions used: YEAR() takes the year from a date.
  5. ORDER BY doj โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 5 rows in set
16
Query ยท read only
SELECT YEAR(doj) AS Join_Year, COUNT(*) AS Joined FROM employee GROUP BY YEAR(doj) ORDER BY Join_Year;

Fetches rows from employee, grouped by YEAR(doj), in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. GROUP BY YEAR(doj) โ†’ makes groups: rows with the same YEAR(doj) go into one group (one output row per group).
  3. SELECT YEAR(doj) AS Join_Year, COUNT(*) AS Joined โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: YEAR() takes the year from a date; COUNT(*) counts all rows.
  5. ORDER BY Join_Year โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobile
1Anil Sharma10Manager550002015-04-019810011111
2Poonam Arora10Clerk280002019-07-15NULL
3Deepak Verma20Executive320002018-01-109811122222
4Rina Das20Manager600002012-11-059812233333
5Manoj Kumar30Developer480002020-06-229813344444
6Sakshi Jain30Developer450002021-02-01NULL
7Tarun Malik30Team Lead700002014-08-189815566666
8Geeta Nair40Officer360002017-09-099816677777
9Faisal Ali20Executive300002022-03-149817788888
10Lata Mishra40Manager520002013-12-029818899999
11Kunal Bose50Clerk260002023-05-08NULL
12Ritu Saxena30Manager820002011-01-179819900000
โœ” Result: 12 rows in set
๐Ÿ“Œ M6 : Pay revision
17
DDL ยท structure
ALTER TABLE employee ADD bonus INT DEFAULT 0;

Changes the STRUCTURE (design) of table employee: adds a new column bonus (existing rows get NULL in it).

  • Data in other columns is not touched.
โœ” Result: Query OK, 0 rows affected ยท Records: 0 Duplicates: 0 Warnings: 0
18
DML ยท data change
UPDATE employee SET bonus = basic * 0.10 WHERE designation = 'Manager';

Changes existing data in table employee.

  1. UPDATE employee โ†’ picks the table.
  2. WHERE designation = 'Manager' โ†’ finds only the rows that match.
  3. SET bonus = basic * 0.10 โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE designation = 'Manager' โ†’ 4 row(s) matched.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111110โœŽ
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333330โœŽ
5Manoj Kumar30Developer480002020-06-2298133444440
6Sakshi Jain30Developer450002021-02-01NULL0
7Tarun Malik30Team Lead700002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999990โœŽ
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager820002011-01-1798199000000โœŽ
โœ” Result: Query OK, 4 rows affected ยท Rows matched: 4 Changed: 4 Warnings: 0
19
Query ยท read only
SELECT ename, designation, bonus FROM employee WHERE bonus > 0;

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE bonus > 0 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, designation, bonus โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer480002020-06-2298133444440
6Sakshi Jain30Developer450002021-02-01NULL0
7Tarun Malik30Team Lead700002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager820002011-01-1798199000008200
โœ” Result: 4 rows in set
20
DML ยท data change
UPDATE employee SET basic = basic * 1.05 WHERE deptno = 30;

Changes existing data in table employee.

  1. UPDATE employee โ†’ picks the table.
  2. WHERE deptno = 30 โ†’ finds only the rows that match.
  3. SET basic = basic * 1.05 โ†’ writes the new value(s) in those rows.
  4. MySQL reports "Rows matched / Changed".
๐ŸŽฌ Watch MySQL execute it
โžœ

FIND: WHERE deptno = 30 โ†’ 4 row(s) matched.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer480002020-06-2298133444440โœŽ
6Sakshi Jain30Developer450002021-02-01NULL0โœŽ
7Tarun Malik30Team Lead700002014-08-1898155666660โœŽ
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager820002011-01-1798199000008200โœŽ
โœ” Result: Query OK, 4 rows affected ยท Rows matched: 4 Changed: 4 Warnings: 0
21
Query ยท read only
SELECT ename, basic FROM employee WHERE deptno = 30;

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE deptno = 30 โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, basic โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 4 rows in set
๐Ÿ“Œ M7 : Join reports
22
Query ยท read only
SELECT e.ename, d.dname, d.location, e.basic FROM employee e, dept d WHERE e.deptno = d.deptno ORDER BY d.location, e.ename;

Fetches rows from employee that satisfy a condition, in sorted order.

  1. FROM employee e, dept d โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE e.deptno = d.deptno โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT e.ename, d.dname, d.location, e.basic โ†’ picks the columns / calculates the values to show.
  4. ORDER BY d.location, e.ename โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order - the 2nd column breaks ties.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: The tables are joined: employee e, dept d โ†’ 60 combined rows.

empnoenamedeptnodesignationbasicdojmobilebonusdeptnodnamelocation
1Anil Sharma10Manager550002015-04-019810011111550010AccountsDelhi
1Anil Sharma10Manager550002015-04-019810011111550020SalesMumbai
1Anil Sharma10Manager550002015-04-019810011111550030ITBengaluru
1Anil Sharma10Manager550002015-04-019810011111550040HRDelhi
1Anil Sharma10Manager550002015-04-019810011111550050AdminNoida
2Poonam Arora10Clerk280002019-07-15NULL010AccountsDelhi
2Poonam Arora10Clerk280002019-07-15NULL020SalesMumbai
2Poonam Arora10Clerk280002019-07-15NULL030ITBengaluru
2Poonam Arora10Clerk280002019-07-15NULL040HRDelhi
2Poonam Arora10Clerk280002019-07-15NULL050AdminNoida
3Deepak Verma20Executive320002018-01-109811122222010AccountsDelhi
3Deepak Verma20Executive320002018-01-109811122222020SalesMumbai
3Deepak Verma20Executive320002018-01-109811122222030ITBengaluru
3Deepak Verma20Executive320002018-01-109811122222040HRDelhi
+ 46 more rows
โœ” Result: 12 rows in set
23
Query ยท read only
SELECT d.location, COUNT(*) AS Staff, SUM(e.basic) AS Salary_Bill FROM employee e, dept d WHERE e.deptno = d.deptno GROUP BY d.location;

Fetches rows from employee that satisfy a condition, grouped by d.location.

  1. FROM employee e, dept d โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE e.deptno = d.deptno โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. GROUP BY d.location โ†’ makes groups: rows with the same d.location go into one group (one output row per group).
  4. SELECT d.location, COUNT(*) AS Staff, SUM(e.basic) AS Salary_Bill โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  5. Functions used: COUNT(*) counts all rows; SUM() adds the values.
๐ŸŽฌ Watch MySQL execute it
โžœโžœโžœ

FROM: The tables are joined: employee e, dept d โ†’ 60 combined rows.

empnoenamedeptnodesignationbasicdojmobilebonusdeptnodnamelocation
1Anil Sharma10Manager550002015-04-019810011111550010AccountsDelhi
1Anil Sharma10Manager550002015-04-019810011111550020SalesMumbai
1Anil Sharma10Manager550002015-04-019810011111550030ITBengaluru
1Anil Sharma10Manager550002015-04-019810011111550040HRDelhi
1Anil Sharma10Manager550002015-04-019810011111550050AdminNoida
2Poonam Arora10Clerk280002019-07-15NULL010AccountsDelhi
2Poonam Arora10Clerk280002019-07-15NULL020SalesMumbai
2Poonam Arora10Clerk280002019-07-15NULL030ITBengaluru
2Poonam Arora10Clerk280002019-07-15NULL040HRDelhi
2Poonam Arora10Clerk280002019-07-15NULL050AdminNoida
3Deepak Verma20Executive320002018-01-109811122222010AccountsDelhi
3Deepak Verma20Executive320002018-01-109811122222020SalesMumbai
3Deepak Verma20Executive320002018-01-109811122222030ITBengaluru
3Deepak Verma20Executive320002018-01-109811122222040HRDelhi
+ 46 more rows
โœ” Result: 4 rows in set
24
Query ยท read only
SELECT d.dname, e.ename AS Manager FROM employee e, dept d WHERE e.deptno = d.deptno AND e.designation = 'Manager';

Fetches rows from employee that satisfy a condition.

  1. FROM employee e, dept d โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  2. WHERE e.deptno = d.deptno AND e.designation = 'Manager' โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT d.dname, e.ename AS Manager โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: The tables are joined: employee e, dept d โ†’ 60 combined rows.

empnoenamedeptnodesignationbasicdojmobilebonusdeptnodnamelocation
1Anil Sharma10Manager550002015-04-019810011111550010AccountsDelhi
1Anil Sharma10Manager550002015-04-019810011111550020SalesMumbai
1Anil Sharma10Manager550002015-04-019810011111550030ITBengaluru
1Anil Sharma10Manager550002015-04-019810011111550040HRDelhi
1Anil Sharma10Manager550002015-04-019810011111550050AdminNoida
2Poonam Arora10Clerk280002019-07-15NULL010AccountsDelhi
2Poonam Arora10Clerk280002019-07-15NULL020SalesMumbai
2Poonam Arora10Clerk280002019-07-15NULL030ITBengaluru
2Poonam Arora10Clerk280002019-07-15NULL040HRDelhi
2Poonam Arora10Clerk280002019-07-15NULL050AdminNoida
3Deepak Verma20Executive320002018-01-109811122222010AccountsDelhi
3Deepak Verma20Executive320002018-01-109811122222020SalesMumbai
3Deepak Verma20Executive320002018-01-109811122222030ITBengaluru
3Deepak Verma20Executive320002018-01-109811122222040HRDelhi
+ 46 more rows
โœ” Result: 4 rows in set
๐Ÿ“Œ M8 : Search queries
25
Query ยท read only
SELECT ename FROM employee WHERE ename LIKE '%a';

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE ename LIKE '%a' (ends with "a") โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 5 rows in set
26
Query ยท read only
SELECT ename, designation FROM employee WHERE designation IN ('Clerk','Officer');

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE designation IN ('Clerk','Officer') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, designation โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 3 rows in set
27
Query ยท read only
SELECT ename FROM employee WHERE mobile IS NULL;

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE mobile IS NULL โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 3 rows in set
28
Query ยท read only
SELECT DISTINCT designation FROM employee ORDER BY designation;

Fetches rows from employee, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. SELECT designation โ†’ picks the columns / calculates the values to show.
  3. DISTINCT โ†’ removes repeated rows, so each value appears only once.
  4. ORDER BY designation โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 6 rows in set
29
Query ยท read only
SELECT ename, basic FROM employee WHERE basic = (SELECT MAX(basic) FROM employee);

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE basic = (SELECT MAX(basic) FROM employee) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, basic โ†’ picks the columns / calculates the values to show.
  4. Functions used: MAX() finds the largest value.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 1 row in set
๐Ÿ“Œ M9 : Views and sub-queries
30
DDL ยท structure
CREATE VIEW salary_register AS
    SELECT e.empno, e.ename, d.dname, e.basic,
           e.basic * 0.40 AS DA,
           e.basic * 0.20 AS HRA,
           e.basic * 0.12 AS PF,
           e.basic * 1.48 + e.bonus AS Gross_Pay
    FROM employee e, dept d
    WHERE e.deptno = d.deptno;

Creates a VIEW salary_register - a saved SELECT query that behaves like a virtual table.

  • The query saved inside the view: Fetches rows from employee that satisfy a condition.
  • FROM employee e, dept d โ†’ takes the tables together (every row of one with every row of the other - Cartesian product).
  • WHERE e.deptno = d.deptno โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  • SELECT e.empno, e.ename, d.dname, e.basic, e.basic * 0.40 AS DA, e.basic * 0.20 AS HRA, e.basic * 0.12 AS PF, e.basic * 1.48 + e.bonus AS Gross_Pay โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
๐ŸŽฌ Watch MySQL execute it
โžœ

FROM: The tables are joined: employee e, dept d โ†’ 60 combined rows.

empnoenamedeptnodesignationbasicdojmobilebonusdeptnodnamelocation
1Anil Sharma10Manager550002015-04-019810011111550010AccountsDelhi
1Anil Sharma10Manager550002015-04-019810011111550020SalesMumbai
1Anil Sharma10Manager550002015-04-019810011111550030ITBengaluru
1Anil Sharma10Manager550002015-04-019810011111550040HRDelhi
1Anil Sharma10Manager550002015-04-019810011111550050AdminNoida
2Poonam Arora10Clerk280002019-07-15NULL010AccountsDelhi
2Poonam Arora10Clerk280002019-07-15NULL020SalesMumbai
2Poonam Arora10Clerk280002019-07-15NULL030ITBengaluru
2Poonam Arora10Clerk280002019-07-15NULL040HRDelhi
2Poonam Arora10Clerk280002019-07-15NULL050AdminNoida
3Deepak Verma20Executive320002018-01-109811122222010AccountsDelhi
3Deepak Verma20Executive320002018-01-109811122222020SalesMumbai
3Deepak Verma20Executive320002018-01-109811122222030ITBengaluru
3Deepak Verma20Executive320002018-01-109811122222040HRDelhi
+ 46 more rows
โœ” Result: Query OK, 0 rows affected
31
Query ยท read only
SELECT * FROM salary_register ORDER BY Gross_Pay DESC;

Fetches rows from salary_register, in sorted order.

  1. FROM salary_register โ†’ MySQL first opens table salary_register and looks at all its rows.
  2. SELECT all the columns (*) โ†’ picks the columns / calculates the values to show.
  3. ORDER BY Gross_Pay DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
โœ” Result: 12 rows in set
32
Query ยท read only
SELECT ename, basic
FROM employee
WHERE basic > (SELECT AVG(basic) FROM employee)
ORDER BY basic DESC;

Fetches rows from employee that satisfy a condition, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE basic > (SELECT AVG(basic) FROM employee) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT ename, basic โ†’ picks the columns / calculates the values to show.
  4. Functions used: AVG() finds the average.
  5. ORDER BY basic DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 6 rows in set
33
Query ยท read only
SELECT dname
FROM dept
WHERE deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager');

Fetches rows from dept that satisfy a condition.

  1. FROM dept โ†’ MySQL first opens table dept and looks at all its rows.
  2. WHERE deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager') โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT dname โ†’ picks the columns / calculates the values to show.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table dept - all 5 rows are taken.

deptnodnamelocation
10AccountsDelhi
20SalesMumbai
30ITBengaluru
40HRDelhi
50AdminNoida
โœ” Result: 1 row in set
๐Ÿ“Œ M10 : Formatted reports with functions
34
Query ยท read only
SELECT UPPER(ename) AS Employee,
       CONCAT('Rs. ', FORMAT(basic, 0)) AS Basic_Pay,
       MONTHNAME(doj) AS Joined_In,
       DAYNAME(doj) AS Day
FROM employee
WHERE deptno IN (10, 40)
ORDER BY ename;

Fetches rows from employee that satisfy a condition, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE deptno IN (10, 40) โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT UPPER(ename) AS Employee, CONCAT('Rs. ', FORMAT(basic, 0)) AS Basic_Pay, MONTHNAME(doj) AS Joined_In, DAYNAME(doj) AS Day โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: UPPER() changes text to capitals; CONCAT() joins texts together; FORMAT(x, d) shows x with commas and d decimals; MONTHNAME() gives the month name; DAYNAME() gives the weekday name.
  5. ORDER BY ename โ†’ sorts the result rows in ascending (small โ†’ big / A โ†’ Z) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 4 rows in set
35
Query ยท read only
SELECT designation,
       COUNT(*) AS Staff,
       ROUND(SUM(basic) / (SELECT SUM(basic) FROM employee) * 100, 1) AS Share_Percent
FROM employee
GROUP BY designation
ORDER BY Share_Percent DESC;

Fetches rows from employee, grouped by designation, in sorted order.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. GROUP BY designation โ†’ makes groups: rows with the same designation go into one group (one output row per group).
  3. SELECT designation, COUNT(*) AS Staff, ROUND(SUM(basic) / (SELECT SUM(basic) FROM employee) * 100, 1) AS Share_Percent โ†’ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group; AS gives a heading (alias) to a column.
  4. Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; SUM() adds the values.
  5. ORDER BY Share_Percent DESC โ†’ sorts the result rows in descending (big โ†’ small / Z โ†’ A) order.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 6 rows in set
36
Query ยท read only
SELECT SUBSTR(ename, 1, INSTR(ename, ' ') - 1) AS First_Name,
       RIGHT(mobile, 4) AS Mobile_Last4
FROM employee
WHERE mobile IS NOT NULL
LIMIT 6;

Fetches rows from employee that satisfy a condition.

  1. FROM employee โ†’ MySQL first opens table employee and looks at all its rows.
  2. WHERE mobile IS NOT NULL โ†’ checks this condition for every row; only the rows where it is TRUE are kept.
  3. SELECT SUBSTR(ename, 1, INSTR(ename, ' ') - 1) AS First_Name, RIGHT(mobile, 4) AS Mobile_Last4 โ†’ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
  4. Functions used: SUBSTR(text, start, n) takes n characters from position start; INSTR(text, sub) gives the position of sub; RIGHT(text, n) takes n characters from the right.
  5. LIMIT 6 โ†’ shows only the first 6 row(s) of the result.
๐ŸŽฌ Watch MySQL execute it
โžœโžœ

FROM: MySQL opens table employee - all 12 rows are taken.

empnoenamedeptnodesignationbasicdojmobilebonus
1Anil Sharma10Manager550002015-04-0198100111115500
2Poonam Arora10Clerk280002019-07-15NULL0
3Deepak Verma20Executive320002018-01-1098111222220
4Rina Das20Manager600002012-11-0598122333336000
5Manoj Kumar30Developer504002020-06-2298133444440
6Sakshi Jain30Developer472502021-02-01NULL0
7Tarun Malik30Team Lead735002014-08-1898155666660
8Geeta Nair40Officer360002017-09-0998166777770
9Faisal Ali20Executive300002022-03-1498177888880
10Lata Mishra40Manager520002013-12-0298188999995200
11Kunal Bose50Clerk260002023-05-08NULL0
12Ritu Saxena30Manager861002011-01-1798199000008200
โœ” Result: 6 rows in set
Q1. How are computed columns shown in SQL?

By writing expressions in SELECT with an alias, e.g. basic*0.40 AS DA.

Q2. What is the purpose of ALTER TABLE ... ADD?

It adds a new column (bonus) to an existing table without deleting data.

Q3. How is experience calculated?

YEAR('2026-04-01') - YEAR(doj) or TIMESTAMPDIFF(YEAR, doj, '2026-04-01') gives completed years.

Q4. What is DEFAULT 0?

If no value is given for bonus while inserting, 0 is stored automatically.

Q5. Why join dept and employee?

Location is stored only once in dept; the join brings it to every employee row without repeating data (normalisation).

10

ATM Simulator

PYTHONDictionary of accountswhile loop with limited attemptslist as mini-statementfunctionsvalidation
๐Ÿ“ 140 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 123 output lines๐Ÿ“„ 25+ page report

PIN-protected ATM with three attempts, balance enquiry, cash withdrawal in multiples of 100, deposit, PIN change and last-five-transactions statement.

โœจ Features
  • Multiple bank accounts with PIN login and 3-attempt card blocking
  • Balance enquiry, cash deposit, fast cash (500 / 1000 / 2000) and withdrawal in multiples of 100
  • Daily withdrawal limit of Rs. 25,000 and minimum balance of Rs. 1,000
  • Fund transfer between accounts
  • Mini statement with the last 6 transactions and running balance
  • Change PIN with validation (4 digits, not same as old)
โ˜ฐ Main menu
1Balance EnquiryShows available balance
2DepositAdds money to the account
3WithdrawCash withdrawal with all checks
4Fast CashOne-touch 500 / 1000 / 2000
5TransferSends money to another account
6Mini StatementLast 6 transactions
7Change PINChanges the 4-digit PIN
8LogoutReturns to card insertion (login)
0Shut DownCloses the ATM
๐ŸŽฏ Objectives
  • Control program flow with attempt counters
  • Validate cash withdrawals
  • Maintain a transaction log in a list
๐Ÿ“š Data dictionary
NameTypePurpose
accountsdictAccount no -> {name, pin, balance, today, statement, blocked}
DAILY_LIMITintRs. 25,000 per day
MIN_BALANCEintRs. 1,000 must remain
statementlistLast transactions of an account (max 6)
Why it matters: Teaches validation, loops with counters and state handling using lists and dictionaries.
# =====================================================================
#   ATM SIMULATOR
#   Concepts : nested dictionaries, lists, loops, conditions,
#              functions, input validation
# =====================================================================

DAILY_LIMIT = 25000
MIN_BALANCE = 1000
accounts = {1001: {"name": "Narender Kumar", "pin": "4321", "balance": 20000.0},
            1002: {"name": "Sunita Sharma", "pin": "1234", "balance": 30000.0},
            1003: {"name": "Rohit Verma", "pin": "8642", "balance": 5000.0}}
for a in accounts.values():
    a.update({"today": 0, "statement": [], "blocked": False})


def log(acc, kind, amt):
    """Adds a statement entry (keeps last 6)."""
    acc["statement"].append(f"{kind:<12}{amt:>10.2f}{acc['balance']:>12.2f}")
    if len(acc["statement"]) > 6:
        acc["statement"].pop(0)


def read_amount(msg):
    try:
        return float(input(msg))
    except ValueError:
        print("Invalid amount.")
        return 0


def withdraw(acc, amt):
    """Withdraws after all checks."""
    if amt <= 0 or amt % 100 != 0:
        print("Amount must be in multiples of 100.")
    elif acc["today"] + amt > DAILY_LIMIT:
        print(f"Daily limit Rs. {DAILY_LIMIT} exceeded. You can withdraw Rs. {DAILY_LIMIT - acc['today']:.0f} more today.")
    elif acc["balance"] - amt < MIN_BALANCE:
        print(f"Insufficient balance. Minimum balance Rs. {MIN_BALANCE} must remain.")
    else:
        acc["balance"] -= amt
        acc["today"] += amt
        log(acc, "WITHDRAW", amt)
        print(f"Please collect cash Rs. {amt:.0f}. Balance Rs. {acc['balance']:.2f}")


def login():
    """Returns the account number after PIN check, or None."""
    try:
        no = int(input("\nInsert card - enter account number (0 = shut down): "))
    except ValueError:
        return None
    if no == 0:
        return -1
    acc = accounts.get(no)
    if acc is None:
        print("Card not recognised.")
        return None
    if acc["blocked"]:
        print("This card is blocked. Contact your branch.")
        return None
    for left in (2, 1, 0):
        if input("Enter 4-digit PIN: ") == acc["pin"]:
            print("Welcome,", acc["name"])
            return no
        print("Wrong PIN!", f"{left} attempt(s) left" if left else "")
    acc["blocked"] = True
    print("Card blocked after 3 wrong attempts.")
    return None


def session(no):
    """ATM menu for a logged-in user. Returns False on shut down."""
    acc = accounts[no]
    while True:
        print("\n1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down")
        ch = input("Enter choice: ").strip()
        if ch == "1":
            print(f"Available balance: Rs. {acc['balance']:.2f}")
        elif ch == "2":
            amt = read_amount("Deposit amount: ")
            if amt > 0:
                acc["balance"] += amt
                log(acc, "DEPOSIT", amt)
                print(f"Deposited. Balance Rs. {acc['balance']:.2f}")
        elif ch == "3":
            withdraw(acc, read_amount("Withdraw amount: "))
        elif ch == "4":
            opt = input("Fast cash 1) 500 2) 1000 3) 2000 : ").strip()
            withdraw(acc, {"1": 500, "2": 1000, "3": 2000}.get(opt, 0))
        elif ch == "5":
            try:
                to = int(input("Transfer to account: "))
            except ValueError:
                to = 0
            amt = read_amount("Amount: ")
            if to == no or to not in accounts:
                print("Invalid beneficiary account.")
            elif acc["balance"] - amt < MIN_BALANCE or amt <= 0:
                print("Insufficient balance for transfer.")
            else:
                acc["balance"] -= amt
                accounts[to]["balance"] += amt
                log(acc, "TRANSFER", amt)
                log(accounts[to], "RECEIVED", amt)
                print(f"Rs. {amt:.0f} sent to {accounts[to]['name']}. Balance Rs. {acc['balance']:.2f}")
        elif ch == "6":
            print(f"{'Type':<12}{'Amount':>10}{'Balance':>12}")
            for s in acc["statement"]:
                print(s)
        elif ch == "7":
            old = input("Old PIN: ")
            new = input("New PIN: ")
            if old != acc["pin"]:
                print("Old PIN incorrect.")
            elif new == old or not (new.isdigit() and len(new) == 4):
                print("New PIN must be 4 digits and different from the old PIN.")
            else:
                acc["pin"] = new
                print("PIN changed successfully.")
        elif ch == "8":
            print("Logged out. Please take your card.")
            return True
        elif ch == "0":
            return False
        else:
            print("Invalid choice")


print("=" * 46)
print("KV BANK ATM".center(46))
print("=" * 46)
running = True
while running:
    no = login()
    if no == -1:
        break
    if no:
        running = session(no)
print("ATM shut down. Thank you for banking with us!")

        
  1. Start
  2. Insert card - read account number
  3. PIN correct within 3 tries? → No: block card
  4. Display ATM menu and read choice
  5. Withdraw allowed (multiple of 100, limit, balance)? → No: show reason
  6. Update balance and statement
  7. Show receipt / balance / statement
  8. Logout? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Wrong PIN 3 timesCard blockedPASS
2Correct PINWelcome messagePASS
3Withdraw 2550'Multiples of 100'PASS
4Withdraw leaving < Rs. 1000'Minimum balance' messagePASS
5Withdraw above daily limit'Daily limit' messagePASS
6Fast cash 2000Balance reduced by 2000PASS
7Transfer 3000 to account 1002Both balances updatedPASS
8Change PIN to same PINRejectedPASS
9Mini statementLast 6 transactionsPASS
โš  Limitations
  • Data is lost after shutdown
  • PIN is stored as plain text
  • No real cash dispenser / receipt printer
  • Single currency denomination check
๐Ÿš€ Future scope
  • Store accounts in MySQL with hashed PINs
  • OTP-based PIN reset
  • Denomination-wise cash dispensing
  • GUI touch-screen interface

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: DAILY_LIMIT, MIN_BALANCE, accounts.
  2. 5 functions are defined (lines 16โ€“126) - Python stores them but does NOT run them yet.
  3. Main program starts at line 12: for a in accounts.values(): - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
log(acc, kind, amt)16โ€“20Adds a statement entry (keeps last 6).withdraw(), session()
read_amount(msg)23โ€“28Read amountsession()
withdraw(acc, amt)31โ€“43Withdraws after all checks.session()
login()46โ€“68Returns the account number after PIN check, or None.main program
session(no)71โ€“126ATM menu for a logged-in user. Returns False on shut down.main program
โ‘ข Main program - line by line
LineCodeWhat it does
12
for a in accounts.values():
๐Ÿ” Loop LOOP: takes each item of accounts.values() one-by-one into a and runs the indented block for it
13
a.update({"today": 0, "statement": [], "blocked": False})
๐Ÿงฎ Store / Calculate Updates a with {"today": 0, "statement": [], "blocked": Falsโ€ฆ
129
print("=" * 46)
๐Ÿ–ฅ๏ธ Output Displays a line of 46 "=" signs on the screen
130
print("KV BANK ATM".center(46))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV BANK ATM".center(46) on the screen
131
print("=" * 46)
๐Ÿ–ฅ๏ธ Output Displays a line of 46 "=" signs on the screen
132
running = True
๐Ÿงฎ Store / Calculate Stores True in variable running
133
while running:
๐Ÿ” Loop LOOP: repeats the indented block as long as running is True (not empty / not zero); checks the condition before every round
134
no = login()
๐Ÿงฎ Store / Calculate Calls our own function login() - returns the account number after pin check, or none; the result is stored in variable no
135
if no == -1:
๐Ÿ”€ Decision CHECKS whether no is equal to -1. If True, the indented lines below run; otherwise they are skipped
136
break
๐Ÿ” Loop BREAK - leaves the loop immediately
137
if no:
๐Ÿ”€ Decision CHECKS whether no is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
138
running = session(no)
๐Ÿงฎ Store / Calculate Calls our own function session(no) - atm menu for a logged-in user. returns false on shut down; the result is stored in variable running
139
print("ATM shut down. Thank you for banking with us!")
๐Ÿ–ฅ๏ธ Output Displays the text "ATM shut down. Thank you for bankโ€ฆ" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: login()
    shows: KV BANK ATM
  2. You type 1001 at Insert card - enter account number (0 = shut down):
  3. You type 1111 at Enter 4-digit PIN:
    shows: Wrong PIN! 2 attempt(s) left
  4. You type 2222 at Enter 4-digit PIN:
    shows: Wrong PIN! 1 attempt(s) left
  5. You type 3333 at Enter 4-digit PIN:
    runs: login()
    shows: Wrong PIN! (+1 more lines)
  6. You type 1001 at Insert card - enter account number (0 = shut down):
    runs: login()
    shows: This card is blocked. Contact your branch.
  7. You type 1002 at Insert card - enter account number (0 = shut down):
  8. You type 1234 at Enter 4-digit PIN:
    runs: session()
    shows: Welcome, Sunita Sharma (+1 more lines)
  9. You type 1 at Enter choice:
    shows: Available balance: Rs. 30000.00 (+1 more lines)
  10. You type 3 at Enter choice:
    runs: read_amount()
  11. You type 2550 at Withdraw amount:
    runs: withdraw()
    shows: Amount must be in multiples of 100. (+1 more lines)
  12. You type 3 at Enter choice:
    runs: read_amount()
  13. You type 29500 at Withdraw amount:
    runs: withdraw()
    shows: Daily limit Rs. 25000 exceeded. You can withdraw Rs. 25000 more today. (+1 more lines)
  14. You type 3 at Enter choice:
    runs: read_amount()
  15. You type 5000 at Withdraw amount:
    runs: withdraw() โ†’ log()
    shows: Please collect cash Rs. 5000. Balance Rs. 25000.00 (+1 more lines)
  16. You type 2 at Enter choice:
    runs: read_amount()
  17. You type 7000 at Deposit amount:
    runs: log()
    shows: Deposited. Balance Rs. 32000.00 (+1 more lines)
  18. You type 3 at Enter choice:
    runs: read_amount()
  19. You type 20000 at Withdraw amount:
    runs: withdraw() โ†’ log()
    shows: Please collect cash Rs. 20000. Balance Rs. 12000.00 (+1 more lines)
  20. You type 3 at Enter choice:
    runs: read_amount()
  21. You type 1000 at Withdraw amount:
    runs: withdraw()
    shows: Daily limit Rs. 25000 exceeded. You can withdraw Rs. 0 more today. (+1 more lines)
  22. You type 4 at Enter choice:
  23. You type 3 at Fast cash 1) 500 2) 1000 3) 2000 :
    runs: withdraw()
    shows: Daily limit Rs. 25000 exceeded. You can withdraw Rs. 0 more today. (+1 more lines)
  24. You type 5 at Enter choice:
  25. You type 1003 at Transfer to account:
    runs: read_amount()
  26. You type 3000 at Amount:
    runs: log() ร—2
    shows: Rs. 3000 sent to Rohit Verma. Balance Rs. 9000.00 (+1 more lines)
  27. You type 5 at Enter choice:
  28. You type 1002 at Transfer to account:
    runs: read_amount()
  29. You type 3000 at Amount:
    shows: Invalid beneficiary account. (+1 more lines)
  30. You type 6 at Enter choice:
    shows: Type Amount Balance (+5 more lines)
  31. You type 7 at Enter choice:
  32. You type 1234 at Old PIN:
  33. You type 1234 at New PIN:
    shows: New PIN must be 4 digits and different from the old PIN. (+1 more lines)
  34. You type 7 at Enter choice:
  35. You type 1234 at Old PIN:
  36. You type 5678 at New PIN:
    shows: PIN changed successfully. (+1 more lines)
  37. You type 1 at Enter choice:
    shows: Available balance: Rs. 9000.00 (+1 more lines)
  38. You type 8 at Enter choice:
    runs: login()
    shows: Logged out. Please take your card.
  39. You type 1003 at Insert card - enter account number (0 = shut down):
  40. You type 8642 at Enter 4-digit PIN:
    runs: session()
    shows: Welcome, Rohit Verma (+1 more lines)

โ€ฆ and 6 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
log() - lines 16โ€“20
LineCodeWhat it does
16
def log(acc, kind, amt):
๐Ÿงฉ Function DEFINES a function log(acc, kind, amt). Python only remembers it here - its body runs later, each time log() is called.
18
acc["statement"].append(f"{kind:<12}{amt:>10.2f}{acc['balance']:>12.2f}")
๐Ÿงฎ Store / Calculate Adds f"{kind:<12}{amt:>10.2f}{acc['balance']:>12.2โ€ฆ at the end of list acc["statement"]
19
if len(acc["statement"]) > 6:
๐Ÿ”€ Decision CHECKS whether len(acc["statement"]) is greater than 6. If True, the indented lines below run; otherwise they are skipped
20
acc["statement"].pop(0)
๐Ÿงฎ Store / Calculate Removes and returns an item at position 0 from acc["statement"]
read_amount() - lines 23โ€“28
LineCodeWhat it does
23
def read_amount(msg):
๐Ÿงฉ Function DEFINES a function read_amount(msg). Python only remembers it here - its body runs later, each time read_amount() is called.
24
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
25
return float(input(msg))
๐Ÿงฉ Function Sends back (returns) the result of: shows msg, reads what the user types, and float() converts that text into a decimal number to the line that called the function
26
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
27
print("Invalid amount.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid amount." on the screen
28
return 0
๐Ÿงฉ Function Sends back (returns) the number 0 to the line that called the function
withdraw() - lines 31โ€“43
LineCodeWhat it does
31
def withdraw(acc, amt):
๐Ÿงฉ Function DEFINES a function withdraw(acc, amt). Python only remembers it here - its body runs later, each time withdraw() is called.
33
if amt <= 0 or amt % 100 != 0:
๐Ÿ”€ Decision CHECKS whether (amt is less than or equal to 0 OR amt % 100 is not equal to 0). If True, the indented lines below run; otherwise Python jumps to the elif/else part
34
print("Amount must be in multiples of 100.")
๐Ÿ–ฅ๏ธ Output Displays the text "Amount must be in multiples of 10โ€ฆ" on the screen
35
elif acc["today"] + amt > DAILY_LIMIT:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether acc["today"] + amt is greater than DAILY_LIMIT
36
print(f"Daily limit Rs. {DAILY_LIMIT} exceeded. You can withdraw Rs. {DAILY_LIMIT - acc['today']:.0f} more today.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Daily limit Rs. {DAILY_LIMIT} exceeded. Youโ€ฆ with the values filled into { } on the screen
37
elif acc["balance"] - amt < MIN_BALANCE:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether acc["balance"] - amt is less than MIN_BALANCE
38
print(f"Insufficient balance. Minimum balance Rs. {MIN_BALANCE} must remain.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Insufficient balance. Minimum balance Rs. {โ€ฆ with the values filled into { } on the screen
39
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
40
acc["balance"] -= amt
๐Ÿงฎ Store / Calculate Subtracts amt from acc["balance"] (same as acc["balance"] = acc["balance"] - amt)
41
acc["today"] += amt
๐Ÿงฎ Store / Calculate Adds amt to acc["today"] (same as acc["today"] = acc["today"] + amt)
42
log(acc, "WITHDRAW", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "WITHDRAW", amt) - adds a statement entry (keeps last 6)
43
print(f"Please collect cash Rs. {amt:.0f}. Balance Rs. {acc['balance']:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Please collect cash Rs. {amt:.0f}. Balance โ€ฆ with the values filled into { } on the screen
login() - lines 46โ€“68
LineCodeWhat it does
46
def login():
๐Ÿงฉ Function DEFINES a function login(). Python only remembers it here - its body runs later, each time login() is called.
48
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
49
no = int(input("\nInsert card - enter account number (0 = shut down): "))
โŒจ๏ธ Input Shows "\nInsert card - enter account number (0 = shut down): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable no
50
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
51
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
52
if no == 0:
๐Ÿ”€ Decision CHECKS whether no is equal to 0. If True, the indented lines below run; otherwise they are skipped
53
return -1
๐Ÿงฉ Function Sends back (returns) -1 to the line that called the function
54
acc = accounts.get(no)
๐Ÿงฎ Store / Calculate Gets the value for key no from accounts; the result is stored in variable acc
55
if acc is None:
๐Ÿ”€ Decision CHECKS whether acc is None. If True, the indented lines below run; otherwise they are skipped
56
print("Card not recognised.")
๐Ÿ–ฅ๏ธ Output Displays the text "Card not recognised." on the screen
57
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
58
if acc["blocked"]:
๐Ÿ”€ Decision CHECKS whether acc["blocked"] is True. If True, the indented lines below run; otherwise they are skipped
59
print("This card is blocked. Contact your branch.")
๐Ÿ–ฅ๏ธ Output Displays the text "This card is blocked. Contact youโ€ฆ" on the screen
60
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
61
for left in (2, 1, 0):
๐Ÿ” Loop LOOP: takes each item of (2, 1, 0) one-by-one into left and runs the indented block for it
62
if input("Enter 4-digit PIN: ") == acc["pin"]:
๐Ÿ”€ Decision CHECKS whether input("Enter 4-digit PIN: ") is equal to acc["pin"]. If True, the indented lines below run; otherwise they are skipped
63
print("Welcome,", acc["name"])
๐Ÿ–ฅ๏ธ Output Displays the text "Welcome,", then the value of acc["name"] on the screen
64
return no
๐Ÿงฉ Function Sends back (returns) the value of no to the line that called the function
65
print("Wrong PIN!", f"{left} attempt(s) left" if left else "")
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong PIN!", then the value of f"{left} attempt(s) left" if left else "" on the screen
66
acc["blocked"] = True
๐Ÿงฎ Store / Calculate Puts True into acc["blocked"] (item "blocked" of acc)
67
print("Card blocked after 3 wrong attempts.")
๐Ÿ–ฅ๏ธ Output Displays the text "Card blocked after 3 wrong attempโ€ฆ" on the screen
68
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
session() - lines 71โ€“126
LineCodeWhat it does
71
def session(no):
๐Ÿงฉ Function DEFINES a function session(no). Python only remembers it here - its body runs later, each time session() is called.
73
acc = accounts[no]
๐Ÿงฎ Store / Calculate Stores the item accounts[no] in variable acc
74
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
75
print("\n1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Balance 2.Deposit 3.Withdraw 4.โ€ฆ" on the screen
76
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
77
if ch == "1":
๐Ÿ”€ Decision CHECKS whether ch is equal to "1". If True, the indented lines below run; otherwise Python jumps to the elif/else part
78
print(f"Available balance: Rs. {acc['balance']:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Available balance: Rs. {acc['balance']:.2f}" with the values filled into { } on the screen
79
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
80
amt = read_amount("Deposit amount: ")
๐Ÿงฎ Store / Calculate Calls our own function read_amount("Deposit amount: "); the result is stored in variable amt
81
if amt > 0:
๐Ÿ”€ Decision CHECKS whether amt is greater than 0. If True, the indented lines below run; otherwise they are skipped
82
acc["balance"] += amt
๐Ÿงฎ Store / Calculate Adds amt to acc["balance"] (same as acc["balance"] = acc["balance"] + amt)
83
log(acc, "DEPOSIT", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "DEPOSIT", amt) - adds a statement entry (keeps last 6)
84
print(f"Deposited. Balance Rs. {acc['balance']:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Deposited. Balance Rs. {acc['balance']:.2f}" with the values filled into { } on the screen
85
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
86
withdraw(acc, read_amount("Withdraw amount: "))
๐Ÿงฎ Store / Calculate Calls our own function withdraw(acc, read_amount("Withdrโ€ฆ) - withdraws after all checks
87
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
88
opt = input("Fast cash 1) 500 2) 1000 3) 2000 : ").strip()
โŒจ๏ธ Input Shows "Fast cash 1) 500 2) 1000 3) 2000 : ", reads the typed text, removes extra spaces (strip) and stores it in variable opt
89
withdraw(acc, {"1": 500, "2": 1000, "3": 2000}.get(opt, 0))
๐Ÿงฎ Store / Calculate Calls our own function withdraw(acc, {"1": 500, "2": 100โ€ฆ) - withdraws after all checks
90
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
91
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
92
to = int(input("Transfer to account: "))
โŒจ๏ธ Input Shows "Transfer to account: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable to
93
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
94
to = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable to
95
amt = read_amount("Amount: ")
๐Ÿงฎ Store / Calculate Calls our own function read_amount("Amount: "); the result is stored in variable amt
96
if to == no or to not in accounts:
๐Ÿ”€ Decision CHECKS whether (to is equal to no OR to is not present in accounts). If True, the indented lines below run; otherwise Python jumps to the elif/else part
97
print("Invalid beneficiary account.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid beneficiary account." on the screen
98
elif acc["balance"] - amt < MIN_BALANCE or amt <= 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (acc["balance"] - amt is less than MIN_BALANCE OR amt is less than or equal to 0)
99
print("Insufficient balance for transfer.")
๐Ÿ–ฅ๏ธ Output Displays the text "Insufficient balance for transfer." on the screen
100
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
101
acc["balance"] -= amt
๐Ÿงฎ Store / Calculate Subtracts amt from acc["balance"] (same as acc["balance"] = acc["balance"] - amt)
102
accounts[to]["balance"] += amt
๐Ÿงฎ Store / Calculate Adds amt to accounts[to]["balance"] (same as accounts[to]["balance"] = accounts[to]["balance"] + amt)
103
log(acc, "TRANSFER", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "TRANSFER", amt) - adds a statement entry (keeps last 6)
104
log(accounts[to], "RECEIVED", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(accounts[to], "RECEIVED", amt) - adds a statement entry (keeps last 6)
105
print(f"Rs. {amt:.0f} sent to {accounts[to]['name']}. Balance Rs. {acc['balance']:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Rs. {amt:.0f} sent to {accounts[to]['name']โ€ฆ with the values filled into { } on the screen
106
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
107
print(f"{'Type':<12}{'Amount':>10}{'Balance':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Type':<12}{'Amount':>10}{'Balance':>12}" with the values filled into { } on the screen
108
for s in acc["statement"]:
๐Ÿ” Loop LOOP: takes each item of acc["statement"] one-by-one into s and runs the indented block for it
109
print(s)
๐Ÿ–ฅ๏ธ Output Displays the value of s on the screen
110
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
111
old = input("Old PIN: ")
โŒจ๏ธ Input Shows the message "Old PIN: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable old
112
new = input("New PIN: ")
โŒจ๏ธ Input Shows the message "New PIN: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable new
113
if old != acc["pin"]:
๐Ÿ”€ Decision CHECKS whether old is not equal to acc["pin"]. If True, the indented lines below run; otherwise Python jumps to the elif/else part
114
print("Old PIN incorrect.")
๐Ÿ–ฅ๏ธ Output Displays the text "Old PIN incorrect." on the screen
115
elif new == old or not (new.isdigit() and len(new) == 4):
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (new is equal to old OR NOT (new.isdigit() is True AND len(new) is equal to 4))
116
print("New PIN must be 4 digits and different from the old PIN.")
๐Ÿ–ฅ๏ธ Output Displays the text "New PIN must be 4 digits and diffโ€ฆ" on the screen
117
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
118
acc["pin"] = new
๐Ÿงฎ Store / Calculate Puts the value of new into acc["pin"] (item "pin" of acc)
119
print("PIN changed successfully.")
๐Ÿ–ฅ๏ธ Output Displays the text "PIN changed successfully." on the screen
120
elif ch == "8":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "8"
121
print("Logged out. Please take your card.")
๐Ÿ–ฅ๏ธ Output Displays the text "Logged out. Please take your card." on the screen
122
return True
๐Ÿงฉ Function Sends back (returns) True to the line that called the function
123
elif ch == "0":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "0"
124
return False
๐Ÿงฉ Function Sends back (returns) False to the line that called the function
125
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
126
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
Q1. How does the program block a card?

A for loop allows 3 attempts; if all are wrong, the account's 'blocked' value is set to True.

Q2. Why must withdrawal be a multiple of 100?

ATMs dispense notes of 100 and above; amount % 100 != 0 means it cannot be dispensed.

Q3. How is the daily limit checked?

The amount withdrawn today is stored; today + amount must not exceed 25,000.

Q4. How is the mini statement limited to 6 entries?

After appending, if the list has more than 6 items, pop(0) removes the oldest.

Q5. How is fund transfer done?

The amount is deducted from the sender and added to the receiver, and both statements are updated.

๐Ÿ“™ Class XII Computer Science (083) โ€” 10 Board Projects 10 projects

01

Library Management System

PYTHONBinary file (pickle)functionssearch/update/deletemenu-driven
๐Ÿ“ 196 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 147 output lines๐Ÿ“„ 25+ page report

Full CRUD system for books (add, issue, return, fine calculation on late return, search by title/author) stored in a binary .dat file so records persist between runs.

โœจ Features
  • Books stored permanently in a binary file (library.dat) using pickle
  • Members stored in a CSV file (members.csv)
  • Issue / return with issue date and due date (datetime module) and fine Rs. 2 per late day
  • Search by ID, title or author; update and delete using a temporary file
  • Reports: issued books, overdue list, category stock and member history
  • Exception handling for wrong input and missing files
โ˜ฐ Main menu
1Add BookAppends a book record to library.dat
2Display BooksReads all records with pickle.load()
3Search BookBy ID, title or author
4Add MemberWrites a member to members.csv
5Issue BookMarks book issued with issue date
6Return BookCalculates late fine and makes the book available
7Update BookChanges title / author / category through a temp file
8Delete BookRemoves a record (not if issued)
9ReportsIssued, overdue and category-wise stock
0ExitCloses the program
๐ŸŽฏ Objectives
  • Store records permanently using a binary file
  • Read, search and rewrite records with pickle.load() and dump()
  • Calculate late-return fine through a function
๐Ÿ“š Data dictionary
NameTypePurpose
library.datbinary fileOne pickled dictionary per book: id, title, author, category, issued_to, issue_date
members.csvCSV filemember_id, name, class
temp.datbinary fileTemporary file used while updating / deleting
FINEintRs. 2 per day after 14 days
TODAYdateDate used for issue / return (fixed for the demo)
Why it matters: One of the most-approved KVS/CBSE Class XII project titles โ€” directly matches Practicals 15-16.
# =====================================================================
#   LIBRARY MANAGEMENT SYSTEM  (Binary file + CSV file)
#   Concepts : pickle, csv, os, datetime, functions, exception handling
# =====================================================================
import pickle, csv, os
from datetime import date, timedelta

FILE, MFILE, FINE = "library.dat", "members.csv", 2
TODAY = date(2026, 7, 25)            # fixed date for the demo report


def read_books():
    """Returns a list of all book dictionaries."""
    books = []
    if os.path.exists(FILE):
        with open(FILE, "rb") as f:
            while True:
                try:
                    books.append(pickle.load(f))
                except EOFError:
                    break
    return books


def write_books(books):
    """Rewrites the file through a temporary file."""
    with open("temp.dat", "wb") as t:
        for b in books:
            pickle.dump(b, t)
    os.replace("temp.dat", FILE)


def read_int(msg):
    try:
        return int(input(msg))
    except ValueError:
        print("Please enter a number.")
        return None


def add_book():
    """Appends a new book."""
    bid = read_int("Book ID  : ")
    if bid is None:
        return
    if any(b["id"] == bid for b in read_books()):
        print("Book ID already exists.")
        return
    book = {"id": bid, "title": input("Title    : ").strip(), "author": input("Author   : ").strip(),
            "category": input("Category : ").strip().title(), "issued_to": None, "issue_date": None}
    with open(FILE, "ab") as f:
        pickle.dump(book, f)
    print("Book added successfully!")


def show(books):
    print(f"{'ID':<4}{'Title':<22}{'Author':<20}{'Category':<11}Status")
    print("-" * 70)
    for b in books:
        st = f"Issued to {b['issued_to']}" if b["issued_to"] else "Available"
        print(f"{b['id']:<4}{b['title'][:21]:<22}{b['author'][:19]:<20}{b['category']:<11}{st}")


def display_books():
    books = read_books()
    show(books) if books else print("No records found.")


def search_book():
    """Search by ID / title / author."""
    key = input("Enter Book ID, title or author: ").strip().lower()
    found = [b for b in read_books() if key == str(b["id"]) or key in b["title"].lower() or key in b["author"].lower()]
    show(found) if found else print("No matching book.")


def add_member():
    """Writes a member to the CSV file."""
    row = [input("Member ID : ").strip().upper(), input("Name      : ").strip().title(), input("Class     : ").strip().upper()]
    with open(MFILE, "a", newline="") as f:
        csv.writer(f).writerow(row)
    print("Member saved:", row[1])


def members():
    if not os.path.exists(MFILE):
        return {}
    with open(MFILE, newline="") as f:
        return {r[0]: r[1] for r in csv.reader(f) if r}


def issue_book():
    """Issues a book to a member."""
    bid = read_int("Book ID to issue: ")
    if bid is None:
        return
    mid = input("Member ID       : ").strip().upper()
    d = input("Issue date (yyyy-mm-dd): ").strip()
    if mid not in members():
        print("Member not registered.")
        return
    books = read_books()
    for b in books:
        if b["id"] == bid:
            if b["issued_to"]:
                print("Book is already issued to", b["issued_to"])
                return
            b["issued_to"], b["issue_date"] = mid, d
            write_books(books)
            due = date.fromisoformat(d) + timedelta(days=14)
            print(f"'{b['title']}' issued to {members()[mid]}. Due date: {due}")
            return
    print("Book not found.")


def return_book():
    """Returns a book and calculates the fine."""
    bid = read_int("Book ID to return: ")
    d = date.fromisoformat(input("Return date (yyyy-mm-dd): ").strip())
    books = read_books()
    for b in books:
        if b["id"] == bid and b["issued_to"]:
            days = (d - date.fromisoformat(b["issue_date"])).days
            fine = max(0, days - 14) * FINE
            print(f"Returned by {b['issued_to']} after {days} days. Fine: Rs. {fine}")
            b["issued_to"] = b["issue_date"] = None
            write_books(books)
            return
    print("This book is not issued.")


def update_book():
    """Updates title / author / category (blank keeps old value)."""
    bid = read_int("Book ID to update: ")
    books = read_books()
    for b in books:
        if b["id"] == bid:
            for k in ("title", "author", "category"):
                v = input(f"New {k} [{b[k]}]: ").strip()
                if v:
                    b[k] = v
            write_books(books)
            print("Record updated.")
            return
    print("Book not found.")


def delete_book():
    """Deletes a book that is not issued."""
    bid = read_int("Book ID to delete: ")
    books = read_books()
    target = [b for b in books if b["id"] == bid]
    if not target:
        print("Book not found.")
    elif target[0]["issued_to"]:
        print("Cannot delete - book is issued.")
    else:
        write_books([b for b in books if b["id"] != bid])
        print("Deleted:", target[0]["title"])


def reports():
    """Issued, overdue and category-wise stock."""
    books, mem = read_books(), members()
    issued = [b for b in books if b["issued_to"]]
    print("Total books:", len(books), "| Issued:", len(issued), "| Available:", len(books) - len(issued))
    for b in issued:
        days = (TODAY - date.fromisoformat(b["issue_date"])).days
        flag = f"OVERDUE by {days - 14} days (fine so far Rs. {(days - 14) * FINE})" if days > 14 else f"{days} days"
        print(f"  {b['title']:<22} -> {mem.get(b['issued_to'], b['issued_to']):<12} {flag}")
    cat = {}
    for b in books:
        cat[b["category"]] = cat.get(b["category"], 0) + 1
    print("Category-wise:", ", ".join(f"{k} {v}" for k, v in sorted(cat.items())))


for f in (FILE, MFILE):
    if os.path.exists(f):
        os.remove(f)                 # start the demo with empty files
menu = {"1": add_book, "2": display_books, "3": search_book, "4": add_member, "5": issue_book,
        "6": return_book, "7": update_book, "8": delete_book, "9": reports}
print("=" * 70)
print("LIBRARY MANAGEMENT SYSTEM".center(70))
print("=" * 70)
while True:
    print("\n1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Library closed.")
        break
    try:
        menu[ch]()
    except KeyError:
        print("Invalid choice")
    except ValueError as e:
        print("Invalid input:", e)

        
  1. Start
  2. Display menu and read choice
  3. Choice is Add / Issue / Return? → No: run the selected report
  4. Open library.dat in append / read mode
  5. Load records one by one with pickle.load() until EOFError
  6. Record found and status valid? → No: show message
  7. Update record and rewrite file through temp.dat
  8. Display result / fine
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Add book 1 'Wings of Fire'Record saved in library.datPASS
2Duplicate Book ID'Book ID already exists'PASS
3Search author 'kalam'Matching books listedPASS
4Issue to member M1Issued with due datePASS
5Issue an issued book'Book is already issued'PASS
6Return after 20 daysFine Rs. 12PASS
7Update titleRecord rewritten through temp filePASS
8Delete issued bookNot allowedPASS
9Overdue reportBooks issued more than 14 daysPASS
10Book ID 'x'ValueError handledPASS
โš  Limitations
  • Single-user file access
  • Issue dates are entered / simulated for the demo
  • Binary file must be rewritten fully for every update
  • No barcode or GUI
๐Ÿš€ Future scope
  • Move data to MySQL tables (books, members, issues)
  • Use the system date and e-mail reminders
  • Tkinter GUI for the librarian
  • QR-code based issue and return

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 5): pickle - writing / reading Python objects in binary files, csv - reading / writing CSV files, os - file and folder operations, date, timedelta are loaded.
  2. Global variables / constants are created: TODAY.
  3. 14 functions are defined (lines 12โ€“173) - Python stores them but does NOT run them yet.
  4. Main program starts at line 8: FILE, MFILE, FINE = "library.dat", "members.csv", 2 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_books()12โ€“22Returns a list of all book dictionaries.add_book(), display_books(), search_book(), issue_book()
write_books(books)25โ€“30Rewrites the file through a temporary file.issue_book(), return_book(), update_book(), delete_book()
read_int(msg)33โ€“38Read intadd_book(), issue_book(), return_book(), update_book()
add_book()41โ€“53Appends a new book.main program (menu)
show(books)56โ€“61Showdisplay_books(), search_book()
display_books()64โ€“66Display booksmain program (menu)
search_book()69โ€“73Search by ID / title / author.main program (menu)
add_member()76โ€“81Writes a member to the CSV file.main program (menu)
members()84โ€“88Membersissue_book(), reports()
issue_book()91โ€“112Issues a book to a member.main program (menu)
return_book()115โ€“128Returns a book and calculates the fine.main program (menu)
update_book()131โ€“144Updates title / author / category (blank keeps old value).main program (menu)
delete_book()147โ€“158Deletes a book that is not issued.main program (menu)
reports()161โ€“173Issued, overdue and category-wise stock.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
8
FILE, MFILE, FINE = "library.dat", "members.csv", 2
๐Ÿงฎ Store / Calculate Stores "library.dat", "members.csv", 2 into FILE, MFILE, FINE respectively
9
TODAY = date(2026, 7, 25)            # fixed date for the demo report
๐Ÿงฎ Store / Calculate Makes a date; the result is stored in variable TODAY
176
for f in (FILE, MFILE):
๐Ÿ” Loop LOOP: takes each item of (FILE, MFILE) one-by-one into f and runs the indented block for it
177
if os.path.exists(f):
๐Ÿ”€ Decision CHECKS whether os.path.exists(f) is True. If True, the indented lines below run; otherwise they are skipped
178
os.remove(f)                 # start the demo with empty files
๐Ÿ“ File Deletes the file f
179
menu = {"1": add_book, "2": display_books, "3": search_book, "4": add_member, "5": issue_book,
        "6": return_book, "7": update_book, "8": delete_book, โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_book, "2": display_books, "3": searโ€ฆ in variable menu
181
print("=" * 70)
๐Ÿ–ฅ๏ธ Output Displays a line of 70 "=" signs on the screen
182
print("LIBRARY MANAGEMENT SYSTEM".center(70))
๐Ÿ–ฅ๏ธ Output Displays the value of "LIBRARY MANAGEMENT SYSTEM".center(70) on the screen
183
print("=" * 70)
๐Ÿ–ฅ๏ธ Output Displays a line of 70 "=" signs on the screen
184
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
185
print("\n1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add Book 2.Display 3.Search 4.Aโ€ฆ" on the screen
186
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
187
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
188
print("Library closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Library closed." on the screen
189
break
๐Ÿ” Loop BREAK - leaves the loop immediately
190
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
191
menu[ch]()
๐Ÿงฎ Store / Calculate Calls menu[ch]()
192
except KeyError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if KeyError occurs - a key that is not in the dictionary
193
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
194
except ValueError as e:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
195
print("Invalid input:", e)
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid input:", then the value of e on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: LIBRARY MANAGEMENT SYSTEM (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  3. You type 1 at Book ID :
    runs: read_books()
  4. You type Wings of Fire at Title :
  5. You type A.P.J. Abdul Kalam at Author :
  6. You type Biography at Category :
    shows: Book added successfully! (+1 more lines)
  7. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  8. You type 2 at Book ID :
    runs: read_books()
  9. You type Python Programming at Title :
  10. You type Sumita Arora at Author :
  11. You type Computer at Category :
    shows: Book added successfully! (+1 more lines)
  12. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  13. You type 3 at Book ID :
    runs: read_books()
  14. You type Ignited Minds at Title :
  15. You type A.P.J. Abdul Kalam at Author :
  16. You type Biography at Category :
    shows: Book added successfully! (+1 more lines)
  17. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  18. You type 4 at Book ID :
    runs: read_books()
  19. You type Godan at Title :
  20. You type Premchand at Author :
  21. You type Hindi at Category :
    shows: Book added successfully! (+1 more lines)
  22. You type 1 at Enter choice:
    runs: add_book() โ†’ read_int()
  23. You type 2 at Book ID :
    runs: read_books()
    shows: Book ID already exists. (+1 more lines)
  24. You type 2 at Enter choice:
    runs: display_books() โ†’ read_books() โ†’ show()
    shows: ID Title Author Category Status (+5 more lines)
  25. You type 3 at Enter choice:
    runs: search_book()
  26. You type kalam at Enter Book ID, title or author:
    runs: read_books() โ†’ show()
    shows: ID Title Author Category Status (+3 more lines)
  27. You type 4 at Enter choice:
    runs: add_member()
  28. You type M1 at Member ID :
  29. You type Riya Sharma at Name :
  30. You type XII-A at Class :
    shows: Member saved: Riya Sharma (+1 more lines)
  31. You type 4 at Enter choice:
    runs: add_member()
  32. You type M2 at Member ID :
  33. You type Kabir Singh at Name :
  34. You type XII-B at Class :
    shows: Member saved: Kabir Singh (+1 more lines)
  35. You type 5 at Enter choice:
    runs: issue_book() โ†’ read_int()
  36. You type 1 at Book ID to issue:
  37. You type M1 at Member ID :
  38. You type 2026-07-01 at Issue date (yyyy-mm-dd):
    runs: members() โ†’ read_books() โ†’ write_books() โ†’ members()
    shows: 'Wings of Fire' issued to Riya Sharma. Due date: 2026-07-15 (+1 more lines)
  39. You type 5 at Enter choice:
    runs: issue_book() โ†’ read_int()
  40. You type 1 at Book ID to issue:

โ€ฆ and 27 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
read_books() - lines 12โ€“22
LineCodeWhat it does
12
def read_books():
๐Ÿงฉ Function DEFINES a function read_books(). Python only remembers it here - its body runs later, each time read_books() is called.
14
books = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable books
15
if os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
16
with open(FILE, "rb") as f:
๐Ÿ“ File Opens the file FILE in "rb" mode - read in binary and calls it f. "with" closes the file automatically when the block ends
17
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
18
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
19
books.append(pickle.load(f))
๐Ÿ“ File Adds pickle.load(f) at the end of list books
20
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
21
break
๐Ÿ” Loop BREAK - leaves the loop immediately
22
return books
๐Ÿงฉ Function Sends back (returns) the value of books to the line that called the function
write_books() - lines 25โ€“30
LineCodeWhat it does
25
def write_books(books):
๐Ÿงฉ Function DEFINES a function write_books(books). Python only remembers it here - its body runs later, each time write_books() is called.
27
with open("temp.dat", "wb") as t:
๐Ÿ“ File Opens the file "temp.dat" in "wb" mode - write in binary (old content is erased) and calls it t. "with" closes the file automatically when the block ends
28
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
29
pickle.dump(b, t)
๐Ÿ“ File Writes (pickles) b into the binary file t
30
os.replace("temp.dat", FILE)
๐Ÿ“ File Replaces "temp.dat" with FILE in os
read_int() - lines 33โ€“38
LineCodeWhat it does
33
def read_int(msg):
๐Ÿงฉ Function DEFINES a function read_int(msg). Python only remembers it here - its body runs later, each time read_int() is called.
34
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
35
return int(input(msg))
๐Ÿงฉ Function Sends back (returns) the result of: shows msg, reads what the user types, and int() converts that text into a whole number to the line that called the function
36
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
37
print("Please enter a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Please enter a number." on the screen
38
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
add_book() - lines 41โ€“53
LineCodeWhat it does
41
def add_book():
๐Ÿงฉ Function DEFINES a function add_book(). Python only remembers it here - its body runs later, each time add_book() is called.
43
bid = read_int("Book ID  : ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID : "); the result is stored in variable bid
44
if bid is None:
๐Ÿ”€ Decision CHECKS whether bid is None. If True, the indented lines below run; otherwise they are skipped
45
return
๐Ÿงฉ Function Ends the function and goes back to the caller
46
if any(b["id"] == bid for b in read_books()):
๐Ÿ”€ Decision CHECKS whether any(b["id"] == bid for b in read_books()) is True. If True, the indented lines below run; otherwise they are skipped
47
print("Book ID already exists.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book ID already exists." on the screen
48
return
๐Ÿงฉ Function Ends the function and goes back to the caller
49
book = {"id": bid, "title": input("Title    : ").strip(), "author": input("Author   : ").strip(),
        "category": input("Category : ").strip().title(), "โ€ฆ
โŒจ๏ธ Input Stores a dictionary {"id": bid, "title": input("Title : ").strip(โ€ฆ in variable book
51
with open(FILE, "ab") as f:
๐Ÿ“ File Opens the file FILE in "ab" mode - append in binary and calls it f. "with" closes the file automatically when the block ends
52
pickle.dump(book, f)
๐Ÿ“ File Writes (pickles) book into the binary file f
53
print("Book added successfully!")
๐Ÿ–ฅ๏ธ Output Displays the text "Book added successfully!" on the screen
show() - lines 56โ€“61
LineCodeWhat it does
56
def show(books):
๐Ÿงฉ Function DEFINES a function show(books). Python only remembers it here - its body runs later, each time show() is called.
57
print(f"{'ID':<4}{'Title':<22}{'Author':<20}{'Category':<11}Status")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'ID':<4}{'Title':<22}{'Author':<20}{'Categโ€ฆ with the values filled into { } on the screen
58
print("-" * 70)
๐Ÿ–ฅ๏ธ Output Displays a line of 70 "-" signs on the screen
59
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
60
st = f"Issued to {b['issued_to']}" if b["issued_to"] else "Available"
๐Ÿงฎ Store / Calculate Stores either f"Issued to {b['issued_to']}" or "Available" depending on b["issued_to"] in variable st
61
print(f"{b['id']:<4}{b['title'][:21]:<22}{b['author'][:19]:<20}{b['category']:<11}{st}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{b['id']:<4}{b['title'][:21]:<22}{b['authorโ€ฆ with the values filled into { } on the screen
display_books() - lines 64โ€“66
LineCodeWhat it does
64
def display_books():
๐Ÿงฉ Function DEFINES a function display_books(). Python only remembers it here - its body runs later, each time display_books() is called.
65
books = read_books()
๐Ÿงฎ Store / Calculate Calls our own function read_books() - returns a list of all book dictionaries; the result is stored in variable books
66
show(books) if books else print("No records found.")
๐Ÿ–ฅ๏ธ Output Evaluates show(books) if books else print("No records fโ€ฆ
search_book() - lines 69โ€“73
LineCodeWhat it does
69
def search_book():
๐Ÿงฉ Function DEFINES a function search_book(). Python only remembers it here - its body runs later, each time search_book() is called.
71
key = input("Enter Book ID, title or author: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
72
found = [b for b in read_books() if key == str(b["id"]) or key in b["title"].lower() or key in b["author"].lower()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [b for b in read_books() if key == str(b["id"โ€ฆ in variable found
73
show(found) if found else print("No matching book.")
๐Ÿ–ฅ๏ธ Output Evaluates show(found) if found else print("No matching โ€ฆ
add_member() - lines 76โ€“81
LineCodeWhat it does
76
def add_member():
๐Ÿงฉ Function DEFINES a function add_member(). Python only remembers it here - its body runs later, each time add_member() is called.
78
row = [input("Member ID : ").strip().upper(), input("Name      : ").strip().title(), input("Class     : ").strip().upper()]
โŒจ๏ธ Input Stores a list [input("Member ID : ").strip().upper(), inputโ€ฆ in variable row
79
with open(MFILE, "a", newline="") as f:
๐Ÿ“ File Opens the file MFILE in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
80
csv.writer(f).writerow(row)
๐Ÿ“ File Writes one row row into the CSV file
81
print("Member saved:", row[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Member saved:", then the value of row[1] on the screen
members() - lines 84โ€“88
LineCodeWhat it does
84
def members():
๐Ÿงฉ Function DEFINES a function members(). Python only remembers it here - its body runs later, each time members() is called.
85
if not os.path.exists(MFILE):
๐Ÿ”€ Decision CHECKS whether NOT os.path.exists(MFILE) is True. If True, the indented lines below run; otherwise they are skipped
86
return {}
๐Ÿงฉ Function Sends back (returns) an empty dictionary {} to the line that called the function
87
with open(MFILE, newline="") as f:
๐Ÿ“ File Opens the file MFILE in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
88
return {r[0]: r[1] for r in csv.reader(f) if r}
๐Ÿงฉ Function Sends back (returns) a new dictionary made by a comprehension to the line that called the function
issue_book() - lines 91โ€“112
LineCodeWhat it does
91
def issue_book():
๐Ÿงฉ Function DEFINES a function issue_book(). Python only remembers it here - its body runs later, each time issue_book() is called.
93
bid = read_int("Book ID to issue: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to issue: "); the result is stored in variable bid
94
if bid is None:
๐Ÿ”€ Decision CHECKS whether bid is None. If True, the indented lines below run; otherwise they are skipped
95
return
๐Ÿงฉ Function Ends the function and goes back to the caller
96
mid = input("Member ID       : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable mid
97
d = input("Issue date (yyyy-mm-dd): ").strip()
โŒจ๏ธ Input Shows "Issue date (yyyy-mm-dd): ", reads the typed text, removes extra spaces (strip) and stores it in variable d
98
if mid not in members():
๐Ÿ”€ Decision CHECKS whether mid is not present in members(). If True, the indented lines below run; otherwise they are skipped
99
print("Member not registered.")
๐Ÿ–ฅ๏ธ Output Displays the text "Member not registered." on the screen
100
return
๐Ÿงฉ Function Ends the function and goes back to the caller
101
books = read_books()
๐Ÿงฎ Store / Calculate Calls our own function read_books() - returns a list of all book dictionaries; the result is stored in variable books
102
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
103
if b["id"] == bid:
๐Ÿ”€ Decision CHECKS whether b["id"] is equal to bid. If True, the indented lines below run; otherwise they are skipped
104
if b["issued_to"]:
๐Ÿ”€ Decision CHECKS whether b["issued_to"] is True. If True, the indented lines below run; otherwise they are skipped
105
print("Book is already issued to", b["issued_to"])
๐Ÿ–ฅ๏ธ Output Displays the text "Book is already issued to", then the value of b["issued_to"] on the screen
106
return
๐Ÿงฉ Function Ends the function and goes back to the caller
107
b["issued_to"], b["issue_date"] = mid, d
๐Ÿงฎ Store / Calculate Stores the tuple mid, d in variables b["issued_to"], b["issue_date"]
108
write_books(books)
๐Ÿงฎ Store / Calculate Calls our own function write_books(books) - rewrites the file through a temporary file
109
due = date.fromisoformat(d) + timedelta(days=14)
๐Ÿงฎ Store / Calculate Stores the value of date.fromisoformat(d) + timedelta(days=14) (calculated using +) in variable due
110
print(f"'{b['title']}' issued to {members()[mid]}. Due date: {due}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"'{b['title']}' issued to {members()[mid]}. โ€ฆ with the values filled into { } on the screen
111
return
๐Ÿงฉ Function Ends the function and goes back to the caller
112
print("Book not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book not found." on the screen
return_book() - lines 115โ€“128
LineCodeWhat it does
115
def return_book():
๐Ÿงฉ Function DEFINES a function return_book(). Python only remembers it here - its body runs later, each time return_book() is called.
117
bid = read_int("Book ID to return: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to return:โ€ฆ); the result is stored in variable bid
118
d = date.fromisoformat(input("Return date (yyyy-mm-dd): ").strip())
โŒจ๏ธ Input Converts text like "2026-01-15" into a date; the result is stored in variable d
119
books = read_books()
๐Ÿงฎ Store / Calculate Calls our own function read_books() - returns a list of all book dictionaries; the result is stored in variable books
120
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
121
if b["id"] == bid and b["issued_to"]:
๐Ÿ”€ Decision CHECKS whether (b["id"] is equal to bid AND b["issued_to"] is True). If True, the indented lines below run; otherwise they are skipped
122
days = (d - date.fromisoformat(b["issue_date"])).days
๐Ÿงฎ Store / Calculate Stores (d - date.fromisoformat(b["issue_date"])).days in variable days
123
fine = max(0, days - 14) * FINE
๐Ÿงฎ Store / Calculate Stores the value of max(0, days - 14) * FINE (calculated using ร—) in variable fine
124
print(f"Returned by {b['issued_to']} after {days} days. Fine: Rs. {fine}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Returned by {b['issued_to']} after {days} dโ€ฆ with the values filled into { } on the screen
125
b["issued_to"] = b["issue_date"] = None
๐Ÿงฎ Store / Calculate Puts None (nothing) into b["issued_to"] (item "issued_to" of b)
126
write_books(books)
๐Ÿงฎ Store / Calculate Calls our own function write_books(books) - rewrites the file through a temporary file
127
return
๐Ÿงฉ Function Ends the function and goes back to the caller
128
print("This book is not issued.")
๐Ÿ–ฅ๏ธ Output Displays the text "This book is not issued." on the screen
update_book() - lines 131โ€“144
LineCodeWhat it does
131
def update_book():
๐Ÿงฉ Function DEFINES a function update_book(). Python only remembers it here - its body runs later, each time update_book() is called.
133
bid = read_int("Book ID to update: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to update:โ€ฆ); the result is stored in variable bid
134
books = read_books()
๐Ÿงฎ Store / Calculate Calls our own function read_books() - returns a list of all book dictionaries; the result is stored in variable books
135
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
136
if b["id"] == bid:
๐Ÿ”€ Decision CHECKS whether b["id"] is equal to bid. If True, the indented lines below run; otherwise they are skipped
137
for k in ("title", "author", "category"):
๐Ÿ” Loop LOOP: takes each item of ("title", "author", "category") one-by-one into k and runs the indented block for it
138
v = input(f"New {k} [{b[k]}]: ").strip()
โŒจ๏ธ Input Shows f"New {k} [{b[k]}]: ", reads the typed text, removes extra spaces (strip) and stores it in variable v
139
if v:
๐Ÿ”€ Decision CHECKS whether v is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
140
b[k] = v
๐Ÿงฎ Store / Calculate Puts the value of v into b[k] (item k of b)
141
write_books(books)
๐Ÿงฎ Store / Calculate Calls our own function write_books(books) - rewrites the file through a temporary file
142
print("Record updated.")
๐Ÿ–ฅ๏ธ Output Displays the text "Record updated." on the screen
143
return
๐Ÿงฉ Function Ends the function and goes back to the caller
144
print("Book not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book not found." on the screen
delete_book() - lines 147โ€“158
LineCodeWhat it does
147
def delete_book():
๐Ÿงฉ Function DEFINES a function delete_book(). Python only remembers it here - its body runs later, each time delete_book() is called.
149
bid = read_int("Book ID to delete: ")
๐Ÿงฎ Store / Calculate Calls our own function read_int("Book ID to delete:โ€ฆ); the result is stored in variable bid
150
books = read_books()
๐Ÿงฎ Store / Calculate Calls our own function read_books() - returns a list of all book dictionaries; the result is stored in variable books
151
target = [b for b in books if b["id"] == bid]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [b for b in books if b["id"] == bid] in variable target
152
if not target:
๐Ÿ”€ Decision CHECKS whether target is False (or empty / zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
153
print("Book not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Book not found." on the screen
154
elif target[0]["issued_to"]:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether target[0]["issued_to"] is True
155
print("Cannot delete - book is issued.")
๐Ÿ–ฅ๏ธ Output Displays the text "Cannot delete - book is issued." on the screen
156
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
157
write_books([b for b in books if b["id"] != bid])
๐Ÿงฎ Store / Calculate Calls our own function write_books([b for b in books iโ€ฆ) - rewrites the file through a temporary file
158
print("Deleted:", target[0]["title"])
๐Ÿ–ฅ๏ธ Output Displays the text "Deleted:", then the value of target[0]["title"] on the screen
reports() - lines 161โ€“173
LineCodeWhat it does
161
def reports():
๐Ÿงฉ Function DEFINES a function reports(). Python only remembers it here - its body runs later, each time reports() is called.
163
books, mem = read_books(), members()
๐Ÿงฎ Store / Calculate Stores read_books(), members() into books, mem respectively
164
issued = [b for b in books if b["issued_to"]]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [b for b in books if b["issued_to"]] in variable issued
165
print("Total books:", len(books), "| Issued:", len(issued), "| Available:", len(books) - len(issued))
๐Ÿ–ฅ๏ธ Output Displays the text "Total books:", then the value of len(books), then the text "| Issued:", then the value of len(issued), then the text "| Available:", then the value of len(books) - len(issued) on the screen
166
for b in issued:
๐Ÿ” Loop LOOP: takes each item of issued one-by-one into b and runs the indented block for it
167
days = (TODAY - date.fromisoformat(b["issue_date"])).days
๐Ÿงฎ Store / Calculate Stores (TODAY - date.fromisoformat(b["issue_date"]))โ€ฆ in variable days
168
flag = f"OVERDUE by {days - 14} days (fine so far Rs. {(days - 14) * FINE})" if days > 14 else f"{days} days"
๐Ÿงฎ Store / Calculate Stores either f"OVERDUE by {days - 14} days (fine so far Rsโ€ฆ or f"{days} days" depending on days > 14 in variable flag
169
print(f"  {b['title']:<22} -> {mem.get(b['issued_to'], b['issued_to']):<12} {flag}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {b['title']:<22} -> {mem.get(b['issued_to'โ€ฆ with the values filled into { } on the screen
170
cat = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable cat
171
for b in books:
๐Ÿ” Loop LOOP: takes each item of books one-by-one into b and runs the indented block for it
172
cat[b["category"]] = cat.get(b["category"], 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of cat.get(b["category"], 0) + 1 (calculated using +) into cat[b["category"]] (item b["category"] of cat)
173
print("Category-wise:", ", ".join(f"{k} {v}" for k, v in sorted(cat.items())))
๐Ÿ–ฅ๏ธ Output Displays the text "Category-wise:", then the value of ", ".join(f"{k} {v}" for k, v in sorted(cat.iโ€ฆ on the screen
Q1. Why is pickle used?

pickle converts Python objects (dictionaries) into a byte stream (dump) and back (load), so records can be stored in a binary file.

Q2. How do you read all records from a binary file?

Call pickle.load() in a loop inside try and stop when EOFError is raised at the end of the file.

Q3. How is a record updated in a binary file?

All records are read; the matching one is changed and every record is written to temp.dat, which then replaces library.dat with os.replace().

Q4. Which modes are used to open the files?

'ab' to append a book, 'rb' to read, 'wb' to rewrite; members.csv is opened with 'a' / 'r' and newline=''.

Q5. How is the late fine calculated?

(return date - issue date).days gives days kept; fine = max(0, days - 14) x 2.

02

Bank Management System (with MySQL)

PYTHON + MySQLPython-MySQL connectivityfunctionstransactions
๐Ÿ“ 167 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 109 output lines๐Ÿ“„ 25+ page report

Open account, deposit, withdraw (with balance check), mini-statement, and search account by account number โ€” backed by a real MySQL 'accounts' table (Practicals 23-25).

โœจ Features
  • Accounts and transactions stored in MySQL tables (bankdb)
  • Open account with KYC details, minimum opening deposit Rs. 1000 and account type (Savings / Current)
  • Deposit, withdraw (minimum balance check) and fund transfer with COMMIT / ROLLBACK
  • Mini statement of the last 5 transactions from the transactions table
  • Interest credit for savings accounts (4 % p.a. for one month)
  • Reports: all accounts, total deposits, richest account; close account
โ˜ฐ Main menu
1Open AccountINSERT into accounts with validation
2DepositUPDATE balance and log transaction
3WithdrawChecks minimum balance before UPDATE
4TransferTwo UPDATEs in one transaction; ROLLBACK on error
5Mini StatementLast 5 rows from transactions
6Account DetailsSELECT one account
7Credit InterestMonthly interest for savings accounts
8Bank ReportAll accounts and totals using aggregate SQL
9Close AccountDELETE after balance withdrawal
0ExitCloses the connection
๐ŸŽฏ Objectives
  • Connect Python to MySQL using mysql.connector
  • Use parameterised INSERT, UPDATE and SELECT queries
  • Protect data with balance checks and commit()
๐Ÿ“š Data dictionary
NameTypePurpose
accountsMySQL tableaccno INT PK AUTO_INCREMENT (from 1001), name, mobile, acc_type, balance DECIMAL(12,2)
transactionsMySQL tabletid INT PK, accno INT, ttype VARCHAR(10), amount DECIMAL(12,2), balance DECIMAL(12,2)
conn / curobjectsMySQL connection and cursor
MIN_BALintRs. 1000 minimum balance
Why it matters: Directly demonstrates Python-Database connectivity, the exact skill CBSE emphasises for the board project.
# =====================================================================
#   BANK MANAGEMENT SYSTEM  (Python + MySQL)
#   Concepts : mysql.connector, SQL DDL/DML, transactions (commit /
#              rollback), functions, exception handling
# =====================================================================
import mysql.connector

MIN_BAL = 1000
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS bankdb")
cur.execute("USE bankdb")
cur.execute("""CREATE TABLE IF NOT EXISTS accounts (
                 accno INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30) NOT NULL,
                 mobile CHAR(10), acc_type CHAR(1), balance DECIMAL(12,2)) AUTO_INCREMENT = 1001""")
cur.execute("""CREATE TABLE IF NOT EXISTS transactions (
                 tid INT PRIMARY KEY AUTO_INCREMENT, accno INT, ttype VARCHAR(10),
                 amount DECIMAL(12,2), balance DECIMAL(12,2))""")


def num(msg, kind=float):
    try:
        return kind(input(msg))
    except ValueError:
        print("Invalid number.")
        return None


def get_balance(accno):
    cur.execute("SELECT balance FROM accounts WHERE accno = %s", (accno,))
    row = cur.fetchone()
    return None if row is None else float(row[0])


def log(accno, ttype, amount):
    cur.execute("INSERT INTO transactions (accno, ttype, amount, balance) VALUES (%s, %s, %s, %s)",
                (accno, ttype, amount, get_balance(accno)))


def open_account():
    """Opens a new account."""
    name = input("Account holder name : ").strip().title()
    mobile = input("Mobile number       : ").strip()
    typ = input("Type S/C (Savings/Current): ").strip().upper()[:1] or "S"
    amt = num("Opening deposit     : ")
    if amt is None or amt < MIN_BAL:
        print(f"Minimum opening deposit is Rs. {MIN_BAL}.")
        return
    cur.execute("INSERT INTO accounts (name, mobile, acc_type, balance) VALUES (%s, %s, %s, %s)", (name, mobile, typ, amt))
    acc = cur.lastrowid
    log(acc, "OPEN", amt)
    conn.commit()
    print("Account opened! Account No:", acc)


def deposit():
    acc, amt = num("Account No: ", int), num("Amount    : ")
    if get_balance(acc) is None or not amt or amt <= 0:
        print("Invalid account or amount.")
        return
    cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (amt, acc))
    log(acc, "DEPOSIT", amt)
    conn.commit()
    print(f"Deposited. New balance Rs. {get_balance(acc):.2f}")


def withdraw():
    acc, amt = num("Account No: ", int), num("Amount    : ")
    bal = get_balance(acc)
    if bal is None:
        print("Account not found.")
    elif amt is None or bal - amt < MIN_BAL:
        print(f"Insufficient balance. Rs. {MIN_BAL} must remain (available Rs. {bal - MIN_BAL:.2f}).")
    else:
        cur.execute("UPDATE accounts SET balance = balance - %s WHERE accno = %s", (amt, acc))
        log(acc, "WITHDRAW", amt)
        conn.commit()
        print(f"Please collect Rs. {amt:.0f}. Balance Rs. {get_balance(acc):.2f}")


def transfer():
    """Fund transfer as one database transaction."""
    a, b, amt = num("From account: ", int), num("To account  : ", int), num("Amount      : ")
    try:
        if get_balance(a) is None or get_balance(b) is None:
            raise ValueError("Account not found")
        if get_balance(a) - amt < MIN_BAL:
            raise ValueError("Insufficient balance")
        cur.execute("UPDATE accounts SET balance = balance - %s WHERE accno = %s", (amt, a))
        cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (amt, b))
        log(a, "TRF-OUT", amt)
        log(b, "TRF-IN", amt)
        conn.commit()
        print(f"Rs. {amt:.0f} transferred from {a} to {b}.")
    except ValueError as e:
        conn.rollback()
        print("Transfer failed:", e, "- no money moved.")


def statement():
    acc = num("Account No: ", int)
    cur.execute("SELECT tid, ttype, amount, balance FROM transactions WHERE accno = %s ORDER BY tid DESC LIMIT 5", (acc,))
    rows = cur.fetchall()
    print(f"{'TID':<5}{'Type':<10}{'Amount':>10}{'Balance':>12}")
    for t in rows[::-1]:
        print(f"{t[0]:<5}{t[1]:<10}{float(t[2]):>10.2f}{float(t[3]):>12.2f}")
    if not rows:
        print("No transactions.")


def details():
    acc = num("Account No: ", int)
    cur.execute("SELECT * FROM accounts WHERE accno = %s", (acc,))
    r = cur.fetchone()
    if r:
        print(f"Account {r[0]} | {r[1]} | Mobile {r[2]} | {'Savings' if r[3] == 'S' else 'Current'} | Balance Rs. {float(r[4]):.2f}")
    else:
        print("Account not found.")


def credit_interest():
    """Monthly interest 4 % p.a. for savings accounts."""
    cur.execute("SELECT accno, balance FROM accounts WHERE acc_type = 'S'")
    for acc, bal in cur.fetchall():
        intr = round(float(bal) * 0.04 / 12, 2)
        cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (intr, acc))
        log(acc, "INTEREST", intr)
        print(f"Account {acc}: interest Rs. {intr}")
    conn.commit()


def report():
    cur.execute("SELECT accno, name, acc_type, balance FROM accounts ORDER BY balance DESC")
    rows = cur.fetchall()
    print(f"{'AccNo':<7}{'Name':<16}{'Type':<6}{'Balance':>12}")
    for r in rows:
        print(f"{r[0]:<7}{r[1]:<16}{r[2]:<6}{float(r[3]):>12.2f}")
    cur.execute("SELECT COUNT(*), SUM(balance), MAX(balance), AVG(balance) FROM accounts")
    n, tot, mx, avg = cur.fetchone()
    print(f"Accounts {n} | Total deposits Rs. {float(tot):.2f} | Highest Rs. {float(mx):.2f} | Average Rs. {float(avg):.2f}")


def close_account():
    acc = num("Account No to close: ", int)
    bal = get_balance(acc)
    if bal is None:
        print("Account not found.")
        return
    cur.execute("DELETE FROM accounts WHERE accno = %s", (acc,))
    conn.commit()
    print(f"Account {acc} closed. Rs. {bal:.2f} paid to the customer. Rows deleted: {cur.rowcount}")


menu = {"1": open_account, "2": deposit, "3": withdraw, "4": transfer, "5": statement,
        "6": details, "7": credit_interest, "8": report, "9": close_account}
print("=" * 60)
print("KV BANK - BANK MANAGEMENT SYSTEM (Python + MySQL)".center(60))
print("=" * 60)
while True:
    print("\n1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Connection closed. Thank you!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Connect to MySQL, create bankdb and tables
  3. Display menu and read choice
  4. Choice is Transfer? → No: run the selected operation
  5. Read from-account, to-account and amount
  6. Both accounts exist and balance enough? → No: show error
  7. Two UPDATEs, log transactions, COMMIT (ROLLBACK on error)
  8. Show statement / report
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Open account with Rs. 5000Account 1001 createdPASS
2Opening deposit Rs. 500'Minimum Rs. 1000'PASS
3Deposit 2000Balance increased; transaction loggedPASS
4Withdraw leaving < 1000RefusedPASS
5Transfer 1500 from 1001 to 1002Both balances updated in one COMMITPASS
6Transfer to 9999'Account not found', nothing changedPASS
7Mini statementLast 5 transactionsPASS
8Credit interestSavings accounts get 4 % / 12PASS
9Bank reportCount, total and highest balancePASS
10Close accountRow deletedPASS
โš  Limitations
  • Password of MySQL is written in the program
  • No login / PIN for customers
  • Interest is a simplified monthly calculation
  • Console interface
๐Ÿš€ Future scope
  • Customer login with hashed passwords
  • Generate PDF passbook
  • Loan and FD modules
  • Web interface with Flask

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): mysql.connector - connecting Python with MySQL are loaded.
  2. Global variables / constants are created: MIN_BAL, conn, cur.
  3. 12 functions are defined (lines 21โ€“151) - Python stores them but does NOT run them yet.
  4. Main program starts at line 11: cur.execute("CREATE DATABASE IF NOT EXISTS bankdb") - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
num(msg, kind)21โ€“26Numopen_account(), deposit(), withdraw(), transfer()
get_balance(accno)29โ€“32Get balancelog(), deposit(), withdraw(), transfer()
log(accno, ttype, amount)35โ€“37Logopen_account(), deposit(), withdraw(), transfer()
open_account()40โ€“53Opens a new account.main program (menu)
deposit()56โ€“64Depositmain program (menu)
withdraw()67โ€“78Withdrawmain program (menu)
transfer()81โ€“97Fund transfer as one database transaction.main program (menu)
statement()100โ€“108Statementmain program (menu)
details()111โ€“118Detailsmain program (menu)
credit_interest()121โ€“129Monthly interest 4 % p.a. for savings accounts.main program (menu)
report()132โ€“140Reportmain program (menu)
close_account()143โ€“151Close accountmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
11
cur.execute("CREATE DATABASE IF NOT EXISTS bankdb")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
12
cur.execute("USE bankdb")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
13
cur.execute("""CREATE TABLE IF NOT EXISTS accounts (
                 accno INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30) NOT NULL,
                 mobilโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
16
cur.execute("""CREATE TABLE IF NOT EXISTS transactions (
                 tid INT PRIMARY KEY AUTO_INCREMENT, accno INT, ttype VARCHAR(10),
                 โ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
154
menu = {"1": open_account, "2": deposit, "3": withdraw, "4": transfer, "5": statement,
        "6": details, "7": credit_interest, "8": report, "9": close_acโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": open_account, "2": deposit, "3": withdrโ€ฆ in variable menu
156
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
157
print("KV BANK - BANK MANAGEMENT SYSTEM (Python + MySQL)".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV BANK - BANK MANAGEMENT SYSTEM (Python + Mโ€ฆ on the screen
158
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
159
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
160
print("\n1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Open 2.Deposit 3.Withdraw 4.Traโ€ฆ" on the screen
161
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
162
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
163
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
164
print("Connection closed. Thank you!")
๐Ÿ–ฅ๏ธ Output Displays the text "Connection closed. Thank you!" on the screen
165
break
๐Ÿ” Loop BREAK - leaves the loop immediately
166
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Inside each function - line by line
num() - lines 21โ€“26
LineCodeWhat it does
21
def num(msg, kind=float):
๐Ÿงฉ Function DEFINES a function num(msg, kind). Python only remembers it here - its body runs later, each time num() is called.
22
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
23
return kind(input(msg))
๐Ÿงฉ Function Sends back (returns) the result of: calls kind(input(msg)) to the line that called the function
24
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
25
print("Invalid number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid number." on the screen
26
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
get_balance() - lines 29โ€“32
LineCodeWhat it does
29
def get_balance(accno):
๐Ÿงฉ Function DEFINES a function get_balance(accno). Python only remembers it here - its body runs later, each time get_balance() is called.
30
cur.execute("SELECT balance FROM accounts WHERE accno = %s", (accno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (accno,)
31
row = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable row
32
return None if row is None else float(row[0])
๐Ÿงฉ Function Sends back (returns) either None or float(row[0]) depending on row is None to the line that called the function
log() - lines 35โ€“37
LineCodeWhat it does
35
def log(accno, ttype, amount):
๐Ÿงฉ Function DEFINES a function log(accno, ttype, amount). Python only remembers it here - its body runs later, each time log() is called.
36
cur.execute("INSERT INTO transactions (accno, ttype, amount, balance) VALUES (%s, %s, %s, %s)",
            (accno, ttype, amount, get_balance(accno)))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (accno, ttype, amount, get_balance(accno))
open_account() - lines 40โ€“53
LineCodeWhat it does
40
def open_account():
๐Ÿงฉ Function DEFINES a function open_account(). Python only remembers it here - its body runs later, each time open_account() is called.
42
name = input("Account holder name : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
43
mobile = input("Mobile number       : ").strip()
โŒจ๏ธ Input Shows "Mobile number : ", reads the typed text, removes extra spaces (strip) and stores it in variable mobile
44
typ = input("Type S/C (Savings/Current): ").strip().upper()[:1] or "S"
โŒจ๏ธ Input Stores the value of input("Type S/C (Savings/Current): ").strip()โ€ฆ, or "S" if the first one is empty / None / 0 in variable typ
45
amt = num("Opening deposit     : ")
๐Ÿงฎ Store / Calculate Calls our own function num("Opening deposit : "); the result is stored in variable amt
46
if amt is None or amt < MIN_BAL:
๐Ÿ”€ Decision CHECKS whether (amt is None OR amt is less than MIN_BAL). If True, the indented lines below run; otherwise they are skipped
47
print(f"Minimum opening deposit is Rs. {MIN_BAL}.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Minimum opening deposit is Rs. {MIN_BAL}." with the values filled into { } on the screen
48
return
๐Ÿงฉ Function Ends the function and goes back to the caller
49
cur.execute("INSERT INTO accounts (name, mobile, acc_type, balance) VALUES (%s, %s, %s, %s)", (name, mobile, typ, amt))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (name, mobile, typ, amt)
50
acc = cur.lastrowid
๐Ÿงฎ Store / Calculate Stores cur.lastrowid in variable acc
51
log(acc, "OPEN", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "OPEN", amt)
52
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
53
print("Account opened! Account No:", acc)
๐Ÿ–ฅ๏ธ Output Displays the text "Account opened! Account No:", then the value of acc on the screen
deposit() - lines 56โ€“64
LineCodeWhat it does
56
def deposit():
๐Ÿงฉ Function DEFINES a function deposit(). Python only remembers it here - its body runs later, each time deposit() is called.
57
acc, amt = num("Account No: ", int), num("Amount    : ")
๐Ÿงฎ Store / Calculate Stores num("Account No: ", int), num("Amount : ") into acc, amt respectively
58
if get_balance(acc) is None or not amt or amt <= 0:
๐Ÿ”€ Decision CHECKS whether (get_balance(acc) is None OR amt is False (or empty / zero) OR amt is less than or equal to 0). If True, the indented lines below run; otherwise they are skipped
59
print("Invalid account or amount.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid account or amount." on the screen
60
return
๐Ÿงฉ Function Ends the function and goes back to the caller
61
cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (amt, acc))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (amt, acc)
62
log(acc, "DEPOSIT", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "DEPOSIT", amt)
63
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
64
print(f"Deposited. New balance Rs. {get_balance(acc):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Deposited. New balance Rs. {get_balance(accโ€ฆ with the values filled into { } on the screen
withdraw() - lines 67โ€“78
LineCodeWhat it does
67
def withdraw():
๐Ÿงฉ Function DEFINES a function withdraw(). Python only remembers it here - its body runs later, each time withdraw() is called.
68
acc, amt = num("Account No: ", int), num("Amount    : ")
๐Ÿงฎ Store / Calculate Stores num("Account No: ", int), num("Amount : ") into acc, amt respectively
69
bal = get_balance(acc)
๐Ÿงฎ Store / Calculate Calls our own function get_balance(acc); the result is stored in variable bal
70
if bal is None:
๐Ÿ”€ Decision CHECKS whether bal is None. If True, the indented lines below run; otherwise Python jumps to the elif/else part
71
print("Account not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Account not found." on the screen
72
elif amt is None or bal - amt < MIN_BAL:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (amt is None OR bal - amt is less than MIN_BAL)
73
print(f"Insufficient balance. Rs. {MIN_BAL} must remain (available Rs. {bal - MIN_BAL:.2f}).")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Insufficient balance. Rs. {MIN_BAL} must reโ€ฆ with the values filled into { } on the screen
74
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
75
cur.execute("UPDATE accounts SET balance = balance - %s WHERE accno = %s", (amt, acc))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (amt, acc)
76
log(acc, "WITHDRAW", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "WITHDRAW", amt)
77
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
78
print(f"Please collect Rs. {amt:.0f}. Balance Rs. {get_balance(acc):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Please collect Rs. {amt:.0f}. Balance Rs. {โ€ฆ with the values filled into { } on the screen
transfer() - lines 81โ€“97
LineCodeWhat it does
81
def transfer():
๐Ÿงฉ Function DEFINES a function transfer(). Python only remembers it here - its body runs later, each time transfer() is called.
83
a, b, amt = num("From account: ", int), num("To account  : ", int), num("Amount      : ")
๐Ÿงฎ Store / Calculate Stores num("From account: ", int), num("To account : ", int), num("Amount : ") into a, b, amt respectively
84
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
85
if get_balance(a) is None or get_balance(b) is None:
๐Ÿ”€ Decision CHECKS whether (get_balance(a) is None OR get_balance(b) is None). If True, the indented lines below run; otherwise they are skipped
86
raise ValueError("Account not found")
๐Ÿ›ก๏ธ Error handling RAISES (creates) an error ValueError("Account not found")
87
if get_balance(a) - amt < MIN_BAL:
๐Ÿ”€ Decision CHECKS whether get_balance(a) - amt is less than MIN_BAL. If True, the indented lines below run; otherwise they are skipped
88
raise ValueError("Insufficient balance")
๐Ÿ›ก๏ธ Error handling RAISES (creates) an error ValueError("Insufficient balance")
89
cur.execute("UPDATE accounts SET balance = balance - %s WHERE accno = %s", (amt, a))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (amt, a)
90
cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (amt, b))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (amt, b)
91
log(a, "TRF-OUT", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(a, "TRF-OUT", amt)
92
log(b, "TRF-IN", amt)
๐Ÿงฎ Store / Calculate Calls our own function log(b, "TRF-IN", amt)
93
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
94
print(f"Rs. {amt:.0f} transferred from {a} to {b}.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Rs. {amt:.0f} transferred from {a} to {b}." with the values filled into { } on the screen
95
except ValueError as e:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
96
conn.rollback()
๐Ÿฌ Database Cancels the changes not yet committed
97
print("Transfer failed:", e, "- no money moved.")
๐Ÿ–ฅ๏ธ Output Displays the text "Transfer failed:", then the value of e, then the text "- no money moved." on the screen
statement() - lines 100โ€“108
LineCodeWhat it does
100
def statement():
๐Ÿงฉ Function DEFINES a function statement(). Python only remembers it here - its body runs later, each time statement() is called.
101
acc = num("Account No: ", int)
๐Ÿงฎ Store / Calculate Calls our own function num("Account No: ", int); the result is stored in variable acc
102
cur.execute("SELECT tid, ttype, amount, balance FROM transactions WHERE accno = %s ORDER BY tid DESC LIMIT 5", (acc,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (acc,)
103
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
104
print(f"{'TID':<5}{'Type':<10}{'Amount':>10}{'Balance':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'TID':<5}{'Type':<10}{'Amount':>10}{'Balanโ€ฆ with the values filled into { } on the screen
105
for t in rows[::-1]:
๐Ÿ” Loop LOOP: takes each item of rows[::-1] one-by-one into t and runs the indented block for it
106
print(f"{t[0]:<5}{t[1]:<10}{float(t[2]):>10.2f}{float(t[3]):>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{t[0]:<5}{t[1]:<10}{float(t[2]):>10.2f}{floโ€ฆ with the values filled into { } on the screen
107
if not rows:
๐Ÿ”€ Decision CHECKS whether rows is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
108
print("No transactions.")
๐Ÿ–ฅ๏ธ Output Displays the text "No transactions." on the screen
details() - lines 111โ€“118
LineCodeWhat it does
111
def details():
๐Ÿงฉ Function DEFINES a function details(). Python only remembers it here - its body runs later, each time details() is called.
112
acc = num("Account No: ", int)
๐Ÿงฎ Store / Calculate Calls our own function num("Account No: ", int); the result is stored in variable acc
113
cur.execute("SELECT * FROM accounts WHERE accno = %s", (acc,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (acc,)
114
r = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable r
115
if r:
๐Ÿ”€ Decision CHECKS whether r is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
116
print(f"Account {r[0]} | {r[1]} | Mobile {r[2]} | {'Savings' if r[3] == 'S' else 'Current'} | Balance Rs. {float(r[4]):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Account {r[0]} | {r[1]} | Mobile {r[2]} | {โ€ฆ with the values filled into { } on the screen
117
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
118
print("Account not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Account not found." on the screen
credit_interest() - lines 121โ€“129
LineCodeWhat it does
121
def credit_interest():
๐Ÿงฉ Function DEFINES a function credit_interest(). Python only remembers it here - its body runs later, each time credit_interest() is called.
123
cur.execute("SELECT accno, balance FROM accounts WHERE acc_type = 'S'")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
124
for acc, bal in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into acc, bal and runs the indented block for it
125
intr = round(float(bal) * 0.04 / 12, 2)
๐Ÿงฎ Store / Calculate Rounds float(bal) * 0.04 / 12 to 2 decimal places; the result is stored in variable intr
126
cur.execute("UPDATE accounts SET balance = balance + %s WHERE accno = %s", (intr, acc))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (intr, acc)
127
log(acc, "INTEREST", intr)
๐Ÿงฎ Store / Calculate Calls our own function log(acc, "INTEREST", intr)
128
print(f"Account {acc}: interest Rs. {intr}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Account {acc}: interest Rs. {intr}" with the values filled into { } on the screen
129
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
report() - lines 132โ€“140
LineCodeWhat it does
132
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
133
cur.execute("SELECT accno, name, acc_type, balance FROM accounts ORDER BY balance DESC")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
134
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
135
print(f"{'AccNo':<7}{'Name':<16}{'Type':<6}{'Balance':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'AccNo':<7}{'Name':<16}{'Type':<6}{'Balancโ€ฆ with the values filled into { } on the screen
136
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
137
print(f"{r[0]:<7}{r[1]:<16}{r[2]:<6}{float(r[3]):>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r[0]:<7}{r[1]:<16}{r[2]:<6}{float(r[3]):>1โ€ฆ with the values filled into { } on the screen
138
cur.execute("SELECT COUNT(*), SUM(balance), MAX(balance), AVG(balance) FROM accounts")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
139
n, tot, mx, avg = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables n, tot, mx, avg
140
print(f"Accounts {n} | Total deposits Rs. {float(tot):.2f} | Highest Rs. {float(mx):.2f} | Average Rs. {float(avg):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Accounts {n} | Total deposits Rs. {float(toโ€ฆ with the values filled into { } on the screen
close_account() - lines 143โ€“151
LineCodeWhat it does
143
def close_account():
๐Ÿงฉ Function DEFINES a function close_account(). Python only remembers it here - its body runs later, each time close_account() is called.
144
acc = num("Account No to close: ", int)
๐Ÿงฎ Store / Calculate Calls our own function num("Account No to closโ€ฆ, int); the result is stored in variable acc
145
bal = get_balance(acc)
๐Ÿงฎ Store / Calculate Calls our own function get_balance(acc); the result is stored in variable bal
146
if bal is None:
๐Ÿ”€ Decision CHECKS whether bal is None. If True, the indented lines below run; otherwise they are skipped
147
print("Account not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Account not found." on the screen
148
return
๐Ÿงฉ Function Ends the function and goes back to the caller
149
cur.execute("DELETE FROM accounts WHERE accno = %s", (acc,))
๐Ÿฌ Database Sends a DELETE query (removes rows) to MySQL through the cursor; the %s places are filled safely with the values (acc,)
150
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
151
print(f"Account {acc} closed. Rs. {bal:.2f} paid to the customer. Rows deleted: {cur.rowcount}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Account {acc} closed. Rs. {bal:.2f} paid toโ€ฆ with the values filled into { } on the screen
Q1. Which module connects Python to MySQL?

mysql.connector; connect() creates the connection and cursor() runs queries.

Q2. Why is commit() necessary?

Changes made by INSERT / UPDATE / DELETE become permanent only after conn.commit().

Q3. What is rollback() used for?

If any step of a transfer fails, rollback() undoes the uncommitted changes so money is not lost.

Q4. Why use %s placeholders instead of string joining?

Parameterised queries are safer (prevent SQL injection) and handle quotes automatically.

Q5. What does cursor.lastrowid give?

The AUTO_INCREMENT value generated by the last INSERT - here the new account number.

03

Hospital Patient Management System

PYTHONCSV/binary file handlingstack-based appointment queuesearch
๐Ÿ“ 181 lines of codeโ˜ฐ 11 menu options๐Ÿ–ฅ๏ธ 150 output lines๐Ÿ“„ 25+ page report

Register patients, maintain appointment queue (using the Stack logic from Practicals 19-21), search patient history, and generate a simple prescription/bill record.

โœจ Features
  • Patients stored in a CSV file (patients.csv) with ID, name, age, gender, symptom, doctor and fee
  • Automatic doctor allotment from the symptom (dictionary of departments)
  • Emergency appointment stack - the latest critical patient is attended first (push / pop / peek)
  • Normal OPD queue served in arrival order (list used as a queue)
  • Search, update and discharge (delete) using csv reader / writer
  • Reports: department-wise patients, age groups and total fee collected
โ˜ฐ Main menu
1Register PatientWrites a row to patients.csv
2Show All PatientsReads the CSV with csv.reader
3Search PatientBy ID or name
4Add to OPD QueueNormal appointment (FIFO)
5Emergency (push)Pushes patient on the emergency stack
6Call Next PatientEmergency stack first (pop), then OPD queue
7Peek / Show WaitingShows top of stack and the queue
8Update PatientChanges symptom / age through rewrite
9DischargeDeletes a record and prints the bill
10ReportsDepartment-wise and age-group statistics
0ExitCloses the program
๐ŸŽฏ Objectives
  • Write and read CSV files with the csv module
  • Implement a stack with append() and pop()
  • Generate bills using arithmetic on user input
๐Ÿ“š Data dictionary
NameTypePurpose
patients.csvCSV filepid, name, age, gender, symptom, doctor, fee
DOCTORSdictsymptom keyword -> (department doctor, consultation fee)
emergencylist (stack)push = append(), pop = pop()
opdlist (queue)append() to add, pop(0) to serve
FIELDSlistHeader row of the CSV
Why it matters: A socially useful project idea that examiners rate highly for originality.
# =====================================================================
#   HOSPITAL PATIENT MANAGEMENT SYSTEM  (CSV file + Stack + Queue)
#   Concepts : csv module, list as stack (push/pop/peek), queue,
#              dictionary, functions, exception handling
# =====================================================================
import csv, os

FILE = "patients.csv"
FIELDS = ["pid", "name", "age", "gender", "symptom", "doctor", "fee"]
DOCTORS = {"fever": ("Dr. Mehta (General)", 300), "cough": ("Dr. Mehta (General)", 300),
           "cold": ("Dr. Mehta (General)", 300), "skin": ("Dr. Kaur (Dermatology)", 500),
           "chest": ("Dr. Rao (Cardiology)", 800), "bone": ("Dr. Iyer (Orthopaedics)", 600),
           "child": ("Dr. Das (Paediatrics)", 400)}
emergency = []          # stack  (LIFO)
opd = []                # queue  (FIFO)


def read_all():
    if not os.path.exists(FILE):
        return []
    with open(FILE, newline="") as f:
        return [r for r in csv.reader(f)][1:]


def write_all(rows):
    with open(FILE, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(FIELDS)
        w.writerows(rows)


def find(pid):
    for r in read_all():
        if r[0] == pid:
            return r
    return None


def allot(symptom, age):
    """Returns (doctor, fee) from the symptom keyword."""
    if age < 12:
        return DOCTORS["child"]
    for key, doc in DOCTORS.items():
        if key in symptom.lower():
            return doc
    return DOCTORS["fever"]


def register():
    pid = input("Patient ID : ").strip().upper()
    if find(pid):
        print("Patient ID already exists.")
        return
    name = input("Name       : ").strip().title()
    try:
        age = int(input("Age        : "))
    except ValueError:
        print("Age must be a number.")
        return
    gender = input("Gender M/F : ").strip().upper()
    symptom = input("Symptom    : ").strip().lower()
    doctor, fee = allot(symptom, age)
    rows = read_all() + [[pid, name, age, gender, symptom, doctor, fee]]
    write_all(rows)
    print(f"Registered. Doctor: {doctor}  Fee: Rs. {fee}")


def show(rows):
    print(f"{'PID':<6}{'Name':<14}{'Age':>4} {'G':<2}{'Symptom':<12}{'Doctor':<24}{'Fee':>5}")
    print("-" * 68)
    for r in rows:
        print(f"{r[0]:<6}{r[1]:<14}{r[2]:>4} {r[3]:<2}{r[4]:<12}{r[5]:<24}{r[6]:>5}")


def show_all():
    rows = read_all()
    show(rows) if rows else print("No patients registered.")


def search():
    key = input("Enter Patient ID or name: ").strip().lower()
    rows = [r for r in read_all() if r[0].lower() == key or key in r[1].lower()]
    show(rows) if rows else print("Not found.")


def add_opd():
    pid = input("Patient ID for OPD: ").strip().upper()
    if find(pid):
        opd.append(pid)
        print("Token", len(opd), "given to", find(pid)[1])
    else:
        print("Register the patient first.")


def push_emergency():
    pid = input("Emergency Patient ID: ").strip().upper()
    if find(pid):
        emergency.append(pid)                     # PUSH
        print("Pushed on emergency stack. Stack size:", len(emergency))
    else:
        print("Register the patient first.")


def call_next():
    """Emergency stack first (pop), otherwise OPD queue."""
    if emergency:
        pid, kind = emergency.pop(), "EMERGENCY"  # POP
    elif opd:
        pid, kind = opd.pop(0), "OPD"
    else:
        print("Underflow! No patient waiting.")
        return
    r = find(pid)
    print(f"[{kind}] Now calling {r[1]} ({pid}) to {r[5]}")


def peek():
    print("Top of emergency stack:", find(emergency[-1])[1] if emergency else "Empty")
    print("Emergency stack (top -> bottom):", emergency[::-1])
    print("OPD queue (front -> rear):", opd)


def update():
    pid = input("Patient ID to update: ").strip().upper()
    rows = read_all()
    for r in rows:
        if r[0] == pid:
            age = input(f"New age [{r[2]}]: ").strip() or r[2]
            sym = input(f"New symptom [{r[4]}]: ").strip().lower() or r[4]
            r[2], r[4] = age, sym
            r[5], r[6] = allot(sym, int(age))
            write_all(rows)
            print("Updated. Doctor now:", r[5])
            return
    print("Patient not found.")


def discharge():
    pid = input("Patient ID to discharge: ").strip().upper()
    r = find(pid)
    if not r:
        print("Patient not found.")
        return
    write_all([x for x in read_all() if x[0] != pid])
    fee = int(r[6]); med = 250
    print("-" * 34)
    print(f"Bill for {r[1]} ({pid})")
    print(f"Consultation : Rs. {fee}\nMedicines    : Rs. {med}\nTotal        : Rs. {fee + med}")
    print("-" * 34)


def reports():
    rows = read_all()
    dept, groups = {}, {"Child (<12)": 0, "Adult (12-59)": 0, "Senior (60+)": 0}
    for r in rows:
        d = r[5].split("(")[1].rstrip(")")
        dept[d] = dept.get(d, 0) + 1
        a = int(r[2])
        groups["Child (<12)" if a < 12 else "Senior (60+)" if a >= 60 else "Adult (12-59)"] += 1
    print("Total patients:", len(rows))
    for d, n in sorted(dept.items()):
        print(f"  {d:<14}: {'*' * n} {n}")
    print("Age groups:", groups)
    print("Fee collected (registered): Rs.", sum(int(r[6]) for r in rows))


if os.path.exists(FILE):
    os.remove(FILE)
menu = {"1": register, "2": show_all, "3": search, "4": add_opd, "5": push_emergency, "6": call_next,
        "7": peek, "8": update, "9": discharge, "10": reports}
print("=" * 68)
print("CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM".center(68))
print("=" * 68)
while True:
    print("\n1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Goodbye!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Call Next? → No: run selected file / stack operation
  4. Emergency stack empty? → No: pop the top patient
  5. OPD queue empty? → No: serve the first patient
  6. Display 'No patient waiting' or patient details
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Register P101 with 'fever'Doctor: Dr. Mehta (General)PASS
2Register with age 'abc''Age must be a number'PASS
3Duplicate P101RefusedPASS
4Search 'sharma'Matching rowsPASS
5Push P103 emergencyStack size increasesPASS
6Call next (stack not empty)Emergency patient first (LIFO)PASS
7Call next with empty stackFirst OPD patient (FIFO)PASS
8Call next - nothing waiting'Underflow'PASS
9Discharge P102Row deleted, bill printedPASS
10ReportsDepartment counts and fee totalPASS
โš  Limitations
  • Stack used for emergency means last critical patient is seen first (as per syllabus stack practice)
  • No login for doctors
  • Data in CSV is not encrypted
  • Single counter only
๐Ÿš€ Future scope
  • Priority queue using heapq by severity
  • MySQL storage with visit history
  • SMS token number to the patient
  • Doctor-wise timetable

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): csv - reading / writing CSV files, os - file and folder operations are loaded.
  2. Global variables / constants are created: FILE, FIELDS, DOCTORS, emergency, opd.
  3. 15 functions are defined (lines 18โ€“164) - Python stores them but does NOT run them yet.
  4. Main program starts at line 167: if os.path.exists(FILE): - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_all()18โ€“22Read allfind(), register(), show_all(), search()
write_all(rows)25โ€“29Write allregister(), update(), discharge()
find(pid)32โ€“36Findregister(), add_opd(), push_emergency(), call_next()
allot(symptom, age)39โ€“46Returns (doctor, fee) from the symptom keyword.register(), update()
register()49โ€“65Registermain program (menu)
show(rows)68โ€“72Showshow_all(), search()
show_all()75โ€“77Show allmain program (menu)
search()80โ€“83Searchmain program (menu)
add_opd()86โ€“92Add opdmain program (menu)
push_emergency()95โ€“101Push emergencymain program (menu)
call_next()104โ€“114Emergency stack first (pop), otherwise OPD queue.main program (menu)
peek()117โ€“120Peekmain program (menu)
update()123โ€“135Updatemain program (menu)
discharge()138โ€“149Dischargemain program (menu)
reports()152โ€“164Reportsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
167
if os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
168
os.remove(FILE)
๐Ÿ“ File Deletes the file FILE
169
menu = {"1": register, "2": show_all, "3": search, "4": add_opd, "5": push_emergency, "6": call_next,
        "7": peek, "8": update, "9": discharge, "10": rโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": register, "2": show_all, "3": search, "โ€ฆ in variable menu
171
print("=" * 68)
๐Ÿ–ฅ๏ธ Output Displays a line of 68 "=" signs on the screen
172
print("CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM".center(68))
๐Ÿ–ฅ๏ธ Output Displays the value of "CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM".cโ€ฆ on the screen
173
print("=" * 68)
๐Ÿ–ฅ๏ธ Output Displays a line of 68 "=" signs on the screen
174
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
175
print("\n1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Register 2.Show 3.Search 4.OPD โ€ฆ" on the screen
176
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
177
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
178
print("Goodbye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Goodbye!" on the screen
179
break
๐Ÿ” Loop BREAK - leaves the loop immediately
180
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM (+1 more lines)
  2. You type 1 at Enter choice:
    runs: register()
  3. You type P101 at Patient ID :
    runs: find() โ†’ read_all()
  4. You type Ravi Kumar at Name :
  5. You type 45 at Age :
  6. You type M at Gender M/F :
  7. You type fever at Symptom :
    runs: allot() โ†’ read_all() โ†’ write_all()
    shows: Registered. Doctor: Dr. Mehta (General) Fee: Rs. 300 (+1 more lines)
  8. You type 1 at Enter choice:
    runs: register()
  9. You type P102 at Patient ID :
    runs: find() โ†’ read_all()
  10. You type Anita Sharma at Name :
  11. You type 32 at Age :
  12. You type F at Gender M/F :
  13. You type skin rash at Symptom :
    runs: allot() โ†’ read_all() โ†’ write_all()
    shows: Registered. Doctor: Dr. Kaur (Dermatology) Fee: Rs. 500 (+1 more lines)
  14. You type 1 at Enter choice:
    runs: register()
  15. You type P103 at Patient ID :
    runs: find() โ†’ read_all()
  16. You type Mohan Lal at Name :
  17. You type 67 at Age :
  18. You type M at Gender M/F :
  19. You type chest pain at Symptom :
    runs: allot() โ†’ read_all() โ†’ write_all()
    shows: Registered. Doctor: Dr. Rao (Cardiology) Fee: Rs. 800 (+1 more lines)
  20. You type 1 at Enter choice:
    runs: register()
  21. You type P104 at Patient ID :
    runs: find() โ†’ read_all()
  22. You type Neha Sharma at Name :
  23. You type abc at Age :
    shows: Age must be a number. (+1 more lines)
  24. You type 1 at Enter choice:
    runs: register()
  25. You type P104 at Patient ID :
    runs: find() โ†’ read_all()
  26. You type Neha Sharma at Name :
  27. You type 9 at Age :
  28. You type F at Gender M/F :
  29. You type cough at Symptom :
    runs: allot() โ†’ read_all() โ†’ write_all()
    shows: Registered. Doctor: Dr. Das (Paediatrics) Fee: Rs. 400 (+1 more lines)
  30. You type 1 at Enter choice:
    runs: register()
  31. You type P101 at Patient ID :
    runs: find() โ†’ read_all()
    shows: Patient ID already exists. (+1 more lines)
  32. You type 2 at Enter choice:
    runs: show_all() โ†’ read_all() โ†’ show()
    shows: PID Name Age G Symptom Doctor Fee (+5 more lines)
  33. You type 3 at Enter choice:
    runs: search()
  34. You type sharma at Enter Patient ID or name:
    runs: read_all() โ†’ show()
    shows: PID Name Age G Symptom Doctor Fee (+3 more lines)
  35. You type 4 at Enter choice:
    runs: add_opd()
  36. You type P101 at Patient ID for OPD:
    runs: find() โ†’ read_all() โ†’ find() โ†’ read_all()
    shows: Token 1 given to Ravi Kumar (+1 more lines)
  37. You type 4 at Enter choice:
    runs: add_opd()
  38. You type P104 at Patient ID for OPD:
    runs: find() โ†’ read_all() โ†’ find() โ†’ read_all()
    shows: Token 2 given to Neha Sharma (+1 more lines)
  39. You type 5 at Enter choice:
    runs: push_emergency()
  40. You type P103 at Emergency Patient ID:
    runs: find() โ†’ read_all()
    shows: Pushed on emergency stack. Stack size: 1 (+1 more lines)

โ€ฆ and 17 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
read_all() - lines 18โ€“22
LineCodeWhat it does
18
def read_all():
๐Ÿงฉ Function DEFINES a function read_all(). Python only remembers it here - its body runs later, each time read_all() is called.
19
if not os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether NOT os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
20
return []
๐Ÿงฉ Function Sends back (returns) an empty list [] to the line that called the function
21
with open(FILE, newline="") as f:
๐Ÿ“ File Opens the file FILE in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
22
return [r for r in csv.reader(f)][1:]
๐Ÿงฉ Function Sends back (returns) a slice [r for r in csv.reader(f)][1:] (part of [r for r in csv.reader(f)]) to the line that called the function
write_all() - lines 25โ€“29
LineCodeWhat it does
25
def write_all(rows):
๐Ÿงฉ Function DEFINES a function write_all(rows). Python only remembers it here - its body runs later, each time write_all() is called.
26
with open(FILE, "w", newline="") as f:
๐Ÿ“ File Opens the file FILE in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
27
w = csv.writer(f)
๐Ÿ“ File Creates a CSV writer object for file f; the result is stored in variable w
28
w.writerow(FIELDS)
๐Ÿ“ File Writes one row FIELDS into the CSV file
29
w.writerows(rows)
๐Ÿ“ File Writes many rows (rows) into the CSV file
find() - lines 32โ€“36
LineCodeWhat it does
32
def find(pid):
๐Ÿงฉ Function DEFINES a function find(pid). Python only remembers it here - its body runs later, each time find() is called.
33
for r in read_all():
๐Ÿ” Loop LOOP: takes each item of read_all() one-by-one into r and runs the indented block for it
34
if r[0] == pid:
๐Ÿ”€ Decision CHECKS whether r[0] is equal to pid. If True, the indented lines below run; otherwise they are skipped
35
return r
๐Ÿงฉ Function Sends back (returns) the value of r to the line that called the function
36
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
allot() - lines 39โ€“46
LineCodeWhat it does
39
def allot(symptom, age):
๐Ÿงฉ Function DEFINES a function allot(symptom, age). Python only remembers it here - its body runs later, each time allot() is called.
41
if age < 12:
๐Ÿ”€ Decision CHECKS whether age is less than 12. If True, the indented lines below run; otherwise they are skipped
42
return DOCTORS["child"]
๐Ÿงฉ Function Sends back (returns) the item DOCTORS["child"] to the line that called the function
43
for key, doc in DOCTORS.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary DOCTORS; key, doc get one pair each round
44
if key in symptom.lower():
๐Ÿ”€ Decision CHECKS whether key is present in symptom.lower(). If True, the indented lines below run; otherwise they are skipped
45
return doc
๐Ÿงฉ Function Sends back (returns) the value of doc to the line that called the function
46
return DOCTORS["fever"]
๐Ÿงฉ Function Sends back (returns) the item DOCTORS["fever"] to the line that called the function
register() - lines 49โ€“65
LineCodeWhat it does
49
def register():
๐Ÿงฉ Function DEFINES a function register(). Python only remembers it here - its body runs later, each time register() is called.
50
pid = input("Patient ID : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable pid
51
if find(pid):
๐Ÿ”€ Decision CHECKS whether find(pid) is True. If True, the indented lines below run; otherwise they are skipped
52
print("Patient ID already exists.")
๐Ÿ–ฅ๏ธ Output Displays the text "Patient ID already exists." on the screen
53
return
๐Ÿงฉ Function Ends the function and goes back to the caller
54
name = input("Name       : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
55
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
56
age = int(input("Age        : "))
โŒจ๏ธ Input Shows "Age : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable age
57
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
58
print("Age must be a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Age must be a number." on the screen
59
return
๐Ÿงฉ Function Ends the function and goes back to the caller
60
gender = input("Gender M/F : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable gender
61
symptom = input("Symptom    : ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable symptom
62
doctor, fee = allot(symptom, age)
๐Ÿงฎ Store / Calculate Calls our own function allot(symptom, age) - returns (doctor, fee) from the symptom keyword; the result is stored in variables doctor, fee
63
rows = read_all() + [[pid, name, age, gender, symptom, doctor, fee]]
๐Ÿงฎ Store / Calculate Stores the value of read_all() + [[pid, name, age, gender, symptoโ€ฆ (calculated using +) in variable rows
64
write_all(rows)
๐Ÿงฎ Store / Calculate Calls our own function write_all(rows)
65
print(f"Registered. Doctor: {doctor}  Fee: Rs. {fee}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Registered. Doctor: {doctor} Fee: Rs. {fee}" with the values filled into { } on the screen
show() - lines 68โ€“72
LineCodeWhat it does
68
def show(rows):
๐Ÿงฉ Function DEFINES a function show(rows). Python only remembers it here - its body runs later, each time show() is called.
69
print(f"{'PID':<6}{'Name':<14}{'Age':>4} {'G':<2}{'Symptom':<12}{'Doctor':<24}{'Fee':>5}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'PID':<6}{'Name':<14}{'Age':>4} {'G':<2}{'โ€ฆ with the values filled into { } on the screen
70
print("-" * 68)
๐Ÿ–ฅ๏ธ Output Displays a line of 68 "-" signs on the screen
71
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
72
print(f"{r[0]:<6}{r[1]:<14}{r[2]:>4} {r[3]:<2}{r[4]:<12}{r[5]:<24}{r[6]:>5}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r[0]:<6}{r[1]:<14}{r[2]:>4} {r[3]:<2}{r[4]โ€ฆ with the values filled into { } on the screen
show_all() - lines 75โ€“77
LineCodeWhat it does
75
def show_all():
๐Ÿงฉ Function DEFINES a function show_all(). Python only remembers it here - its body runs later, each time show_all() is called.
76
rows = read_all()
๐Ÿงฎ Store / Calculate Calls our own function read_all(); the result is stored in variable rows
77
show(rows) if rows else print("No patients registered.")
๐Ÿ–ฅ๏ธ Output Evaluates show(rows) if rows else print("No patients reโ€ฆ
search() - lines 80โ€“83
LineCodeWhat it does
80
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
81
key = input("Enter Patient ID or name: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable key
82
rows = [r for r in read_all() if r[0].lower() == key or key in r[1].lower()]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [r for r in read_all() if r[0].lower() == keyโ€ฆ in variable rows
83
show(rows) if rows else print("Not found.")
๐Ÿ–ฅ๏ธ Output Evaluates show(rows) if rows else print("Not found.")
add_opd() - lines 86โ€“92
LineCodeWhat it does
86
def add_opd():
๐Ÿงฉ Function DEFINES a function add_opd(). Python only remembers it here - its body runs later, each time add_opd() is called.
87
pid = input("Patient ID for OPD: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable pid
88
if find(pid):
๐Ÿ”€ Decision CHECKS whether find(pid) is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
89
opd.append(pid)
๐Ÿงฎ Store / Calculate Adds pid at the end of list opd
90
print("Token", len(opd), "given to", find(pid)[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Token", then the value of len(opd), then the text "given to", then the value of find(pid)[1] on the screen
91
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
92
print("Register the patient first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Register the patient first." on the screen
push_emergency() - lines 95โ€“101
LineCodeWhat it does
95
def push_emergency():
๐Ÿงฉ Function DEFINES a function push_emergency(). Python only remembers it here - its body runs later, each time push_emergency() is called.
96
pid = input("Emergency Patient ID: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable pid
97
if find(pid):
๐Ÿ”€ Decision CHECKS whether find(pid) is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
98
emergency.append(pid)                     # PUSH
๐Ÿงฎ Store / Calculate Adds pid at the end of list emergency
99
print("Pushed on emergency stack. Stack size:", len(emergency))
๐Ÿ–ฅ๏ธ Output Displays the text "Pushed on emergency stack. Stack โ€ฆ", then the value of len(emergency) on the screen
100
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
101
print("Register the patient first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Register the patient first." on the screen
call_next() - lines 104โ€“114
LineCodeWhat it does
104
def call_next():
๐Ÿงฉ Function DEFINES a function call_next(). Python only remembers it here - its body runs later, each time call_next() is called.
106
if emergency:
๐Ÿ”€ Decision CHECKS whether emergency is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
107
pid, kind = emergency.pop(), "EMERGENCY"  # POP
๐Ÿงฎ Store / Calculate Stores emergency.pop(), "EMERGENCY" into pid, kind respectively
108
elif opd:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether opd is True (not empty / not zero)
109
pid, kind = opd.pop(0), "OPD"
๐Ÿงฎ Store / Calculate Stores opd.pop(0), "OPD" into pid, kind respectively
110
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
111
print("Underflow! No patient waiting.")
๐Ÿ–ฅ๏ธ Output Displays the text "Underflow! No patient waiting." on the screen
112
return
๐Ÿงฉ Function Ends the function and goes back to the caller
113
r = find(pid)
๐Ÿงฎ Store / Calculate Calls our own function find(pid); the result is stored in variable r
114
print(f"[{kind}] Now calling {r[1]} ({pid}) to {r[5]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"[{kind}] Now calling {r[1]} ({pid}) to {r[5โ€ฆ with the values filled into { } on the screen
peek() - lines 117โ€“120
LineCodeWhat it does
117
def peek():
๐Ÿงฉ Function DEFINES a function peek(). Python only remembers it here - its body runs later, each time peek() is called.
118
print("Top of emergency stack:", find(emergency[-1])[1] if emergency else "Empty")
๐Ÿ–ฅ๏ธ Output Displays the text "Top of emergency stack:", then the value of find(emergency[-1])[1] if emergency else "Empโ€ฆ on the screen
119
print("Emergency stack (top -> bottom):", emergency[::-1])
๐Ÿ–ฅ๏ธ Output Displays the text "Emergency stack (top -> bottom):", then the value of emergency[::-1] on the screen
120
print("OPD queue (front -> rear):", opd)
๐Ÿ–ฅ๏ธ Output Displays the text "OPD queue (front -> rear):", then the value of opd on the screen
update() - lines 123โ€“135
LineCodeWhat it does
123
def update():
๐Ÿงฉ Function DEFINES a function update(). Python only remembers it here - its body runs later, each time update() is called.
124
pid = input("Patient ID to update: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable pid
125
rows = read_all()
๐Ÿงฎ Store / Calculate Calls our own function read_all(); the result is stored in variable rows
126
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
127
if r[0] == pid:
๐Ÿ”€ Decision CHECKS whether r[0] is equal to pid. If True, the indented lines below run; otherwise they are skipped
128
age = input(f"New age [{r[2]}]: ").strip() or r[2]
โŒจ๏ธ Input Stores the value of input(f"New age [{r[2]}]: ").strip(), or r[2] if the first one is empty / None / 0 in variable age
129
sym = input(f"New symptom [{r[4]}]: ").strip().lower() or r[4]
โŒจ๏ธ Input Stores the value of input(f"New symptom [{r[4]}]: ").strip().loweโ€ฆ, or r[4] if the first one is empty / None / 0 in variable sym
130
r[2], r[4] = age, sym
๐Ÿงฎ Store / Calculate Stores the tuple age, sym in variables r[2], r[4]
131
r[5], r[6] = allot(sym, int(age))
๐Ÿงฎ Store / Calculate Calls our own function allot(sym, int(age)) - returns (doctor, fee) from the symptom keyword; the result is stored in variables r[5], r[6]
132
write_all(rows)
๐Ÿงฎ Store / Calculate Calls our own function write_all(rows)
133
print("Updated. Doctor now:", r[5])
๐Ÿ–ฅ๏ธ Output Displays the text "Updated. Doctor now:", then the value of r[5] on the screen
134
return
๐Ÿงฉ Function Ends the function and goes back to the caller
135
print("Patient not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Patient not found." on the screen
discharge() - lines 138โ€“149
LineCodeWhat it does
138
def discharge():
๐Ÿงฉ Function DEFINES a function discharge(). Python only remembers it here - its body runs later, each time discharge() is called.
139
pid = input("Patient ID to discharge: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable pid
140
r = find(pid)
๐Ÿงฎ Store / Calculate Calls our own function find(pid); the result is stored in variable r
141
if not r:
๐Ÿ”€ Decision CHECKS whether r is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
142
print("Patient not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Patient not found." on the screen
143
return
๐Ÿงฉ Function Ends the function and goes back to the caller
144
write_all([x for x in read_all() if x[0] != pid])
๐Ÿงฎ Store / Calculate Calls our own function write_all([x for x in read_alโ€ฆ)
145
fee = int(r[6]); med = 250
๐Ÿงฎ Store / Calculate Converts r[6] into a whole number (int); the result is stored in variable fee
145
fee = int(r[6]); med = 250
๐Ÿงฎ Store / Calculate Stores the number 250 in variable med
146
print("-" * 34)
๐Ÿ–ฅ๏ธ Output Displays a line of 34 "-" signs on the screen
147
print(f"Bill for {r[1]} ({pid})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bill for {r[1]} ({pid})" with the values filled into { } on the screen
148
print(f"Consultation : Rs. {fee}\nMedicines    : Rs. {med}\nTotal        : Rs. {fee + med}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Consultation : Rs. {fee}\nMedicines : Rs. {โ€ฆ with the values filled into { } on the screen
149
print("-" * 34)
๐Ÿ–ฅ๏ธ Output Displays a line of 34 "-" signs on the screen
reports() - lines 152โ€“164
LineCodeWhat it does
152
def reports():
๐Ÿงฉ Function DEFINES a function reports(). Python only remembers it here - its body runs later, each time reports() is called.
153
rows = read_all()
๐Ÿงฎ Store / Calculate Calls our own function read_all(); the result is stored in variable rows
154
dept, groups = {}, {"Child (<12)": 0, "Adult (12-59)": 0, "Senior (60+)": 0}
๐Ÿงฎ Store / Calculate Stores {}, {"Child (<12)": 0, "Adult (12-59)": 0, "Senior (60+)": 0} into dept, groups respectively
155
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
156
d = r[5].split("(")[1].rstrip(")")
๐Ÿงฎ Store / Calculate Removes spaces/characters from the right of r[5].split("(")[1]; the result is stored in variable d
157
dept[d] = dept.get(d, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of dept.get(d, 0) + 1 (calculated using +) into dept[d] (item d of dept)
158
a = int(r[2])
๐Ÿงฎ Store / Calculate Converts r[2] into a whole number (int); the result is stored in variable a
159
groups["Child (<12)" if a < 12 else "Senior (60+)" if a >= 60 else "Adult (12-59)"] += 1
๐Ÿงฎ Store / Calculate Adds 1 to groups["Child (<12)" if a < 12 else "Senior (โ€ฆ (same as groups["Child (<12)" if a < 12 else "Senior (60+)" if a >= 60 else "Adult (12-59)"] = groups["Child (<12)" if a < 12 else "Senior (60+)" if a >= 60 else "Adult (12-59)"] + 1)
160
print("Total patients:", len(rows))
๐Ÿ–ฅ๏ธ Output Displays the text "Total patients:", then the value of len(rows) on the screen
161
for d, n in sorted(dept.items()):
๐Ÿ” Loop LOOP: takes each item of sorted(dept.items()) one-by-one into d, n and runs the indented block for it
162
print(f"  {d:<14}: {'*' * n} {n}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {d:<14}: {'*' * n} {n}" with the values filled into { } on the screen
163
print("Age groups:", groups)
๐Ÿ–ฅ๏ธ Output Displays the text "Age groups:", then the value of groups on the screen
164
print("Fee collected (registered): Rs.", sum(int(r[6]) for r in rows))
๐Ÿ–ฅ๏ธ Output Displays the text "Fee collected (registered): Rs.", then the value of sum(int(r[6]) for r in rows) on the screen
Q1. What is a stack?

A linear data structure that follows LIFO - Last In First Out; insertion (push) and deletion (pop) happen at one end called top.

Q2. How is a stack implemented in Python?

Using a list: append() for push, pop() for pop and lst[-1] for peek; an empty list means underflow.

Q3. Why is newline='' used with csv files?

It stops Python adding blank lines between rows on Windows, because csv.writer already writes line endings.

Q4. How do you delete a row from a CSV file?

Read all rows, keep those not matching, then rewrite the file with csv.writer().writerows().

Q5. Difference between the OPD queue and emergency stack here?

The queue serves first come first served (pop(0)); the stack serves the latest pushed patient first (pop()).

04

Quiz / Online Exam System

PYTHONDictionary of questionsrandom modulefile handling for scores
๐Ÿ“ 125 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 247 output lines๐Ÿ“„ 25+ page report

MCQ quiz engine that randomly picks questions from a question-bank dictionary, times the quiz, stores each attempt's score in a CSV file, and shows a leaderboard.

โœจ Features
  • Question bank of 15 MCQs in 3 subjects (Python, Networking, SQL) stored in a dictionary
  • Student registration and subject selection; questions shuffled with random.sample()
  • +4 for correct, -1 for wrong, 0 for skipped (negative marking like competitive exams)
  • Scores saved in scores.csv with date and percentage
  • Leaderboard (top 5) with sorting, subject-wise topper and average
  • Admin option to add a new question
โ˜ฐ Main menu
1Take QuizAsks 5 random MCQs of the chosen subject
2LeaderboardTop 5 scores from scores.csv
3My ResultsAll attempts of one student
4Subject StatisticsAttempts, average and topper per subject
5Add Question (Admin)Password-protected question entry
6View Question CountQuestions per subject
0ExitCloses the program
๐ŸŽฏ Objectives
  • Shuffle the question bank using the random module
  • Append and read scores in a CSV file
  • Sort file data to build a leaderboard
๐Ÿ“š Data dictionary
NameTypePurpose
BANKdict of listssubject -> list of (question, options, answer)
scores.csvCSV filename, subject, score, max, percent
CORRECT / WRONGint+4 / -1 marking scheme
ADMIN_PWDstrPassword for adding questions
Why it matters: Practical for the school's own subject-enrichment quizzes; strong viva talking points on randomisation & file handling.
# =====================================================================
#   ONLINE QUIZ / EXAM SYSTEM
#   Concepts : dictionary, list, tuple, random, csv file, sorting with
#              lambda, functions, input validation
# =====================================================================
import random, csv, os

CORRECT, WRONG, ADMIN_PWD, FILE = 4, -1, "kv@123", "scores.csv"
BANK = {
 "python": [("Output of 2**3?", ["6", "8", "9", "5"], "b"),
            ("Keyword to define a function?", ["def", "fun", "define", "func"], "a"),
            ("Which is immutable?", ["list", "dict", "tuple", "set"], "c"),
            ("Result of 7 // 2?", ["3.5", "3", "4", "1"], "b"),
            ("Which module gives random numbers?", ["math", "os", "random", "sys"], "c")],
 "networking": [("Full form of LAN?", ["Large Area Net", "Local Area Network", "Long Access Node", "Line Area Net"], "b"),
            ("Device that connects different networks?", ["Hub", "Repeater", "Router", "Switch"], "c"),
            ("Protocol used to send e-mail?", ["SMTP", "FTP", "HTTP", "PPP"], "a"),
            ("Topology with a central device?", ["Bus", "Star", "Ring", "Mesh"], "b"),
            ("IPv4 address length in bits?", ["16", "64", "32", "128"], "c")],
 "sql": [("Command to remove a table?", ["DROP", "DELETE", "REMOVE", "CUT"], "a"),
         ("Clause to filter groups?", ["WHERE", "HAVING", "ORDER BY", "LIKE"], "b"),
         ("Which is a DDL command?", ["SELECT", "UPDATE", "CREATE", "INSERT"], "c"),
         ("Aggregate that counts rows?", ["SUM()", "COUNT()", "MAX()", "AVG()"], "b"),
         ("Wildcard for any characters in LIKE?", ["%", "_", "*", "#"], "a")]}


def take_quiz():
    """Conducts a 5-question quiz with negative marking."""
    name = input("Student name: ").strip().title()
    sub = input("Subject (python / networking / sql): ").strip().lower()
    if sub not in BANK:
        print("Invalid subject.")
        return
    qs = random.sample(BANK[sub], 5)
    score = right = wrong = 0
    for i, (q, opts, ans) in enumerate(qs, 1):
        print(f"\nQ{i}. {q}")
        for letter, o in zip("abcd", opts):
            print(f"   ({letter}) {o}")
        while True:
            u = input("Your answer (a-d, s=skip): ").strip().lower()
            if u in ("a", "b", "c", "d", "s"):
                break
            print("Invalid option, try again.")
        if u == ans:
            score += CORRECT; right += 1
            print("Correct! +4")
        elif u == "s":
            print("Skipped. Answer:", opts["abcd".index(ans)])
        else:
            score += WRONG; wrong += 1
            print("Wrong! -1. Correct answer:", opts["abcd".index(ans)])
    maxm = 5 * CORRECT
    pct = round(score * 100 / maxm, 1)
    with open(FILE, "a", newline="") as f:
        csv.writer(f).writerow([name, sub, score, maxm, pct])
    remark = "Excellent" if pct >= 80 else "Good" if pct >= 50 else "Needs practice"
    print(f"\n{name}: Right {right}, Wrong {wrong}, Score {score}/{maxm} ({pct}%) - {remark}")


def rows():
    if not os.path.exists(FILE):
        return []
    with open(FILE, newline="") as f:
        return list(csv.reader(f))


def leaderboard():
    data = sorted(rows(), key=lambda r: float(r[4]), reverse=True)[:5]
    print(f"{'Rank':<6}{'Name':<10}{'Subject':<12}{'Score':>7}{'%':>8}")
    for i, r in enumerate(data, 1):
        print(f"{i:<6}{r[0]:<10}{r[1]:<12}{r[2] + '/' + r[3]:>7}{r[4]:>8}")


def my_results():
    n = input("Enter your name: ").strip().lower()
    mine = [r for r in rows() if r[0].lower() == n]
    for r in mine:
        print(f"  {r[1]:<12} {r[2]}/{r[3]}  ({r[4]}%)")
    print("Attempts:", len(mine), "| Best:", max((float(r[4]) for r in mine), default=0), "%")


def stats():
    for sub in BANK:
        s = [r for r in rows() if r[1] == sub]
        if s:
            top = max(s, key=lambda r: float(r[4]))
            avg = sum(float(r[4]) for r in s) / len(s)
            print(f"{sub:<11} attempts {len(s)}  average {avg:.1f}%  topper {top[0]} ({top[4]}%)")
        else:
            print(f"{sub:<11} no attempts yet")


def add_question():
    if input("Admin password: ") != ADMIN_PWD:
        print("Access denied.")
        return
    sub = input("Subject: ").strip().lower()
    q = input("Question: ").strip()
    opts = [input(f"Option {c}: ").strip() for c in "abcd"]
    ans = input("Correct option (a-d): ").strip().lower()
    BANK.setdefault(sub, []).append((q, opts, ans))
    print("Question added to", sub)


def count():
    for sub, qs in BANK.items():
        print(f"{sub:<11}: {len(qs)} questions")


random.seed(7)
if os.path.exists(FILE):
    os.remove(FILE)
menu = {"1": take_quiz, "2": leaderboard, "3": my_results, "4": stats, "5": add_question, "6": count}
print("=" * 56)
print("KV ONLINE QUIZ SYSTEM  (+4 correct / -1 wrong)".center(56))
print("=" * 56)
while True:
    print("\n1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("All the best for your exams!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Take Quiz? → No: run report option
  4. Read name and subject
  5. Pick 5 random questions
  6. Ask each question and read option a-d / s
  7. Add +4, -1 or 0
  8. Save score in scores.csv
  9. Show score and remark
  10. Choice is 0? → No: show menu
  11. Stop
#Test case / inputExpected resultStatus
1Correct answer 'b'+4 marksPASS
2Wrong answer-1 marks, correct answer shownPASS
3Answer 's'Skipped, 0 marksPASS
4Invalid option 'z'Asked againPASS
5Unknown subject'Invalid subject'PASS
6LeaderboardTop 5 sorted by percentagePASS
7My results for 'Riya'All her attemptsPASS
8Wrong admin passwordAccess deniedPASS
9Add questionQuestion count increasesPASS
โš  Limitations
  • Question bank lives in the program (lost on restart except added in session)
  • No timer per question
  • Console based
  • One correct option only
๐Ÿš€ Future scope
  • Store questions in MySQL / CSV
  • Timer using time module
  • Tkinter GUI with radio buttons
  • Certificate generation for toppers

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): random - random number functions, csv - reading / writing CSV files, os - file and folder operations are loaded.
  2. Global variables / constants are created: BANK.
  3. 7 functions are defined (lines 27โ€“108) - Python stores them but does NOT run them yet.
  4. Main program starts at line 8: CORRECT, WRONG, ADMIN_PWD, FILE = 4, -1, "kv@123", "scores.csv" - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
take_quiz()27โ€“58Conducts a 5-question quiz with negative marking.main program (menu)
rows()61โ€“65Rowsleaderboard(), my_results(), stats()
leaderboard()68โ€“72Leaderboardmain program (menu)
my_results()75โ€“80My resultsmain program (menu)
stats()83โ€“91Statsmain program (menu)
add_question()94โ€“103Add questionmain program (menu)
count()106โ€“108Countmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
8
CORRECT, WRONG, ADMIN_PWD, FILE = 4, -1, "kv@123", "scores.csv"
๐Ÿงฎ Store / Calculate Stores 4, -1, "kv@123", "scores.csv" into CORRECT, WRONG, ADMIN_PWD, FILE respectively
9
BANK = {
 "python": [("Output of 2**3?", ["6", "8", "9", "5"], "b"),
            ("Keyword to define a function?", ["def", "fun", "define", "func"], "a"),
  โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary { "python": [("Output of 2**3?", ["6", "8", "โ€ฆ in variable BANK
111
random.seed(7)
๐Ÿงฎ Store / Calculate Fixes the starting point of random numbers (7) so results repeat
112
if os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
113
os.remove(FILE)
๐Ÿ“ File Deletes the file FILE
114
menu = {"1": take_quiz, "2": leaderboard, "3": my_results, "4": stats, "5": add_question, "6": count}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": take_quiz, "2": leaderboard, "3": my_reโ€ฆ in variable menu
115
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
116
print("KV ONLINE QUIZ SYSTEM  (+4 correct / -1 wrong)".center(56))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV ONLINE QUIZ SYSTEM (+4 correct / -1 wrongโ€ฆ on the screen
117
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
118
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
119
print("\n1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Take Quiz 2.Leaderboard 3.My Reโ€ฆ" on the screen
120
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
121
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
122
print("All the best for your exams!")
๐Ÿ–ฅ๏ธ Output Displays the text "All the best for your exams!" on the screen
123
break
๐Ÿ” Loop BREAK - leaves the loop immediately
124
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: KV ONLINE QUIZ SYSTEM (+4 correct / -1 wrong) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: take_quiz()
  3. You type Riya at Student name:
  4. You type python at Subject (python / networking / sql):
    shows: Q1. Which is immutable? (+4 more lines)
  5. You type c at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  6. You type a at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  7. You type s at Your answer (a-d, s=skip):
    shows: Skipped. Answer: 3 (+5 more lines)
  8. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  9. You type z at Your answer (a-d, s=skip):
    shows: Invalid option, try again.
  10. You type c at Your answer (a-d, s=skip):
    shows: Correct! +4 (+2 more lines)
  11. You type 1 at Enter choice:
    runs: take_quiz()
  12. You type Kabir at Student name:
  13. You type sql at Subject (python / networking / sql):
    shows: Q1. Wildcard for any characters in LIKE? (+4 more lines)
  14. You type a at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  15. You type a at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  16. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  17. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  18. You type a at Your answer (a-d, s=skip):
    shows: Wrong! -1. Correct answer: CREATE (+2 more lines)
  19. You type 1 at Enter choice:
    runs: take_quiz()
  20. You type Aman at Student name:
  21. You type maths at Subject (python / networking / sql):
    shows: Invalid subject. (+1 more lines)
  22. You type 1 at Enter choice:
    runs: take_quiz()
  23. You type Aman at Student name:
  24. You type networking at Subject (python / networking / sql):
    shows: Q1. Full form of LAN? (+4 more lines)
  25. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  26. You type c at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  27. You type c at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  28. You type a at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  29. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+2 more lines)
  30. You type 1 at Enter choice:
    runs: take_quiz()
  31. You type Riya at Student name:
  32. You type sql at Subject (python / networking / sql):
    shows: Q1. Clause to filter groups? (+4 more lines)
  33. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  34. You type a at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  35. You type c at Your answer (a-d, s=skip):
    shows: Correct! +4 (+5 more lines)
  36. You type c at Your answer (a-d, s=skip):
    shows: Wrong! -1. Correct answer: % (+5 more lines)
  37. You type b at Your answer (a-d, s=skip):
    shows: Correct! +4 (+2 more lines)
  38. You type 2 at Enter choice:
    runs: leaderboard() โ†’ rows()
    shows: Rank Name Subject Score % (+5 more lines)
  39. You type 3 at Enter choice:
    runs: my_results()
  40. You type riya at Enter your name:
    runs: rows()
    shows: python 16/20 (80.0%) (+3 more lines)

โ€ฆ and 14 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
take_quiz() - lines 27โ€“58
LineCodeWhat it does
27
def take_quiz():
๐Ÿงฉ Function DEFINES a function take_quiz(). Python only remembers it here - its body runs later, each time take_quiz() is called.
29
name = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
30
sub = input("Subject (python / networking / sql): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable sub
31
if sub not in BANK:
๐Ÿ”€ Decision CHECKS whether sub is not present in BANK. If True, the indented lines below run; otherwise they are skipped
32
print("Invalid subject.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid subject." on the screen
33
return
๐Ÿงฉ Function Ends the function and goes back to the caller
34
qs = random.sample(BANK[sub], 5)
๐Ÿงฎ Store / Calculate Picks 5 random items from BANK[sub]; the result is stored in variable qs
35
score = right = wrong = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable score
36
for i, (q, opts, ans) in enumerate(qs, 1):
๐Ÿ” Loop LOOP over qs with position: in each round i, (q, opts, ans) get (position, item)
37
print(f"\nQ{i}. {q}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nQ{i}. {q}" with the values filled into { } on the screen
38
for letter, o in zip("abcd", opts):
๐Ÿ” Loop LOOP that walks through "abcd", opts together; letter, o get one item from each
39
print(f"   ({letter}) {o}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" ({letter}) {o}" with the values filled into { } on the screen
40
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
41
u = input("Your answer (a-d, s=skip): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable u
42
if u in ("a", "b", "c", "d", "s"):
๐Ÿ”€ Decision CHECKS whether u is present in ("a", "b", "c", "d", "s"). If True, the indented lines below run; otherwise they are skipped
43
break
๐Ÿ” Loop BREAK - leaves the loop immediately
44
print("Invalid option, try again.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid option, try again." on the screen
45
if u == ans:
๐Ÿ”€ Decision CHECKS whether u is equal to ans. If True, the indented lines below run; otherwise Python jumps to the elif/else part
46
score += CORRECT; right += 1
๐Ÿงฎ Store / Calculate Adds CORRECT to score (same as score = score + CORRECT)
46
score += CORRECT; right += 1
๐Ÿงฎ Store / Calculate Adds 1 to right (same as right = right + 1)
47
print("Correct! +4")
๐Ÿ–ฅ๏ธ Output Displays the text "Correct! +4" on the screen
48
elif u == "s":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether u is equal to "s"
49
print("Skipped. Answer:", opts["abcd".index(ans)])
๐Ÿ–ฅ๏ธ Output Displays the text "Skipped. Answer:", then the value of opts["abcd".index(ans)] on the screen
50
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
51
score += WRONG; wrong += 1
๐Ÿงฎ Store / Calculate Adds WRONG to score (same as score = score + WRONG)
51
score += WRONG; wrong += 1
๐Ÿงฎ Store / Calculate Adds 1 to wrong (same as wrong = wrong + 1)
52
print("Wrong! -1. Correct answer:", opts["abcd".index(ans)])
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong! -1. Correct answer:", then the value of opts["abcd".index(ans)] on the screen
53
maxm = 5 * CORRECT
๐Ÿงฎ Store / Calculate Stores the value of 5 * CORRECT (calculated using ร—) in variable maxm
54
pct = round(score * 100 / maxm, 1)
๐Ÿงฎ Store / Calculate Rounds score * 100 / maxm to 1 decimal places; the result is stored in variable pct
55
with open(FILE, "a", newline="") as f:
๐Ÿ“ File Opens the file FILE in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
56
csv.writer(f).writerow([name, sub, score, maxm, pct])
๐Ÿ“ File Writes one row [name, sub, score, maxm, pct] into the CSV file
57
remark = "Excellent" if pct >= 80 else "Good" if pct >= 50 else "Needs practice"
๐Ÿงฎ Store / Calculate Stores either "Excellent" or "Good" if pct >= 50 else "Needs practice" depending on pct >= 80 in variable remark
58
print(f"\n{name}: Right {right}, Wrong {wrong}, Score {score}/{maxm} ({pct}%) - {remark}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\n{name}: Right {right}, Wrong {wrong}, Scoโ€ฆ with the values filled into { } on the screen
rows() - lines 61โ€“65
LineCodeWhat it does
61
def rows():
๐Ÿงฉ Function DEFINES a function rows(). Python only remembers it here - its body runs later, each time rows() is called.
62
if not os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether NOT os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
63
return []
๐Ÿงฉ Function Sends back (returns) an empty list [] to the line that called the function
64
with open(FILE, newline="") as f:
๐Ÿ“ File Opens the file FILE in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
65
return list(csv.reader(f))
๐Ÿงฉ Function Sends back (returns) the result of: makes a list from csv.reader(f) to the line that called the function
leaderboard() - lines 68โ€“72
LineCodeWhat it does
68
def leaderboard():
๐Ÿงฉ Function DEFINES a function leaderboard(). Python only remembers it here - its body runs later, each time leaderboard() is called.
69
data = sorted(rows(), key=lambda r: float(r[4]), reverse=True)[:5]
๐Ÿงฎ Store / Calculate Stores a slice sorted(rows(), key=lambda r: float(r[4]), revโ€ฆ (part of sorted(rows(), key=lambda r: float(r[4]), revโ€ฆ) in variable data
70
print(f"{'Rank':<6}{'Name':<10}{'Subject':<12}{'Score':>7}{'%':>8}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Rank':<6}{'Name':<10}{'Subject':<12}{'Scoโ€ฆ with the values filled into { } on the screen
71
for i, r in enumerate(data, 1):
๐Ÿ” Loop LOOP over data with position: in each round i, r get (position, item)
72
print(f"{i:<6}{r[0]:<10}{r[1]:<12}{r[2] + '/' + r[3]:>7}{r[4]:>8}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i:<6}{r[0]:<10}{r[1]:<12}{r[2] + '/' + r[3โ€ฆ with the values filled into { } on the screen
my_results() - lines 75โ€“80
LineCodeWhat it does
75
def my_results():
๐Ÿงฉ Function DEFINES a function my_results(). Python only remembers it here - its body runs later, each time my_results() is called.
76
n = input("Enter your name: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable n
77
mine = [r for r in rows() if r[0].lower() == n]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [r for r in rows() if r[0].lower() == n] in variable mine
78
for r in mine:
๐Ÿ” Loop LOOP: takes each item of mine one-by-one into r and runs the indented block for it
79
print(f"  {r[1]:<12} {r[2]}/{r[3]}  ({r[4]}%)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {r[1]:<12} {r[2]}/{r[3]} ({r[4]}%)" with the values filled into { } on the screen
80
print("Attempts:", len(mine), "| Best:", max((float(r[4]) for r in mine), default=0), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Attempts:", then the value of len(mine), then the text "| Best:", then the value of max((float(r[4]) for r in mine), default=0), then the text "%" on the screen
stats() - lines 83โ€“91
LineCodeWhat it does
83
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
84
for sub in BANK:
๐Ÿ” Loop LOOP: takes each item of BANK one-by-one into sub and runs the indented block for it
85
s = [r for r in rows() if r[1] == sub]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [r for r in rows() if r[1] == sub] in variable s
86
if s:
๐Ÿ”€ Decision CHECKS whether s is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
87
top = max(s, key=lambda r: float(r[4]))
๐Ÿงฎ Store / Calculate Finds the largest value among s; the result is stored in variable top
88
avg = sum(float(r[4]) for r in s) / len(s)
๐Ÿงฎ Store / Calculate Stores the value of sum(float(r[4]) for r in s) / len(s) (calculated using รท) in variable avg
89
print(f"{sub:<11} attempts {len(s)}  average {avg:.1f}%  topper {top[0]} ({top[4]}%)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{sub:<11} attempts {len(s)} average {avg:.1โ€ฆ with the values filled into { } on the screen
90
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
91
print(f"{sub:<11} no attempts yet")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{sub:<11} no attempts yet" with the values filled into { } on the screen
add_question() - lines 94โ€“103
LineCodeWhat it does
94
def add_question():
๐Ÿงฉ Function DEFINES a function add_question(). Python only remembers it here - its body runs later, each time add_question() is called.
95
if input("Admin password: ") != ADMIN_PWD:
๐Ÿ”€ Decision CHECKS whether input("Admin password: ") is not equal to ADMIN_PWD. If True, the indented lines below run; otherwise they are skipped
96
print("Access denied.")
๐Ÿ–ฅ๏ธ Output Displays the text "Access denied." on the screen
97
return
๐Ÿงฉ Function Ends the function and goes back to the caller
98
sub = input("Subject: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable sub
99
q = input("Question: ").strip()
โŒจ๏ธ Input Shows "Question: ", reads the typed text, removes extra spaces (strip) and stores it in variable q
100
opts = [input(f"Option {c}: ").strip() for c in "abcd"]
โŒจ๏ธ Input Stores a new list made by a list comprehension [input(f"Option {c}: ").strip() for c in "abcโ€ฆ in variable opts
101
ans = input("Correct option (a-d): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable ans
102
BANK.setdefault(sub, []).append((q, opts, ans))
๐Ÿงฎ Store / Calculate Adds (q, opts, ans) at the end of list BANK.setdefault(sub, [])
103
print("Question added to", sub)
๐Ÿ–ฅ๏ธ Output Displays the text "Question added to", then the value of sub on the screen
count() - lines 106โ€“108
LineCodeWhat it does
106
def count():
๐Ÿงฉ Function DEFINES a function count(). Python only remembers it here - its body runs later, each time count() is called.
107
for sub, qs in BANK.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary BANK; sub, qs get one pair each round
108
print(f"{sub:<11}: {len(qs)} questions")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{sub:<11}: {len(qs)} questions" with the values filled into { } on the screen
Q1. Why is random.sample() used?

It picks k unique items from a list in random order, so questions do not repeat in one attempt.

Q2. How is the leaderboard sorted?

Rows are read from scores.csv and sorted with sorted(rows, key=lambda r: float(r[4]), reverse=True).

Q3. Why is the score file opened in 'a' mode?

Append mode keeps earlier results and adds the new attempt at the end.

Q4. What is a lambda function?

A small anonymous one-line function, e.g. lambda r: r[4], used here as the sort key.

Q5. How is negative marking applied?

score += 4 for a correct option, score -= 1 for a wrong option, nothing for a skipped question.

05

GST Invoice / Book-Shop Billing System

PYTHON + MySQLCSV filePython-SQLreal local business problem
๐Ÿ“ 160 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 164 output lines๐Ÿ“„ 25+ page report

Exactly the example CBSE gives in the syllabus โ€” take raw transaction data, group by category, apply GST rate, and generate a proper invoice, storing every sale in MySQL.

โœจ Features
  • Item master table with HSN category, price, stock and GST slab (5 % / 12 % / 18 %)
  • Multi-item invoice: CGST and SGST split (half each), 5 % discount above Rs. 2000
  • Stock reduces automatically after billing; low-stock alert below 5 units
  • Invoice and invoice items stored in MySQL; invoices also exported to invoices.csv
  • Search invoice by number; day sales report with GST collected (GROUP BY)
  • Stock purchase entry to add quantity
โ˜ฐ Main menu
1Add ItemINSERT into items
2Show ItemsItem list with stock
3New InvoiceMulti-item bill with CGST / SGST
4Find InvoiceRe-prints an old invoice
5Sales ReportCategory-wise sales and GST (GROUP BY)
6Purchase StockUPDATE stock = stock + qty
7Low Stock AlertItems with stock < 5
8Export CSVWrites invoices to invoices.csv
0ExitCloses connection
๐ŸŽฏ Objectives
  • Store sales permanently in a MySQL table
  • Calculate GST by category with conditional logic
  • Use GROUP BY with SUM() in a report
๐Ÿ“š Data dictionary
NameTypePurpose
itemsMySQL tablecode PK, name, category, price, gst, stock
invoiceMySQL tableinv_no PK AUTO_INCREMENT, customer, subtotal, discount, gst_amt, total
inv_itemsMySQL tableinv_no, code, qty, rate, gst
invoices.csvCSV fileExported invoice summary
GSTdictCategory -> GST rate
Why it matters: Ready-made answer when a student is asked in viva 'what real-world problem does your project solve?'
# =====================================================================
#   GST INVOICE / BOOK-SHOP BILLING SYSTEM  (Python + MySQL + CSV)
#   Concepts : mysql.connector, executemany, GROUP BY, csv export,
#              dictionary, functions, validation
# =====================================================================
import mysql.connector, csv

GST = {"Books": 5, "Stationery": 12, "Electronics": 18}
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS shopdb")
cur.execute("USE shopdb")
cur.execute("""CREATE TABLE IF NOT EXISTS items (code CHAR(3) PRIMARY KEY, name VARCHAR(30),
               category VARCHAR(15), price DECIMAL(8,2), gst INT, stock INT)""")
cur.execute("""CREATE TABLE IF NOT EXISTS invoice (inv_no INT PRIMARY KEY AUTO_INCREMENT,
               customer VARCHAR(30), subtotal DECIMAL(10,2), discount DECIMAL(10,2),
               gst_amt DECIMAL(10,2), total DECIMAL(10,2))""")
cur.execute("""CREATE TABLE IF NOT EXISTS inv_items (inv_no INT, code CHAR(3), qty INT,
               rate DECIMAL(8,2), gst INT)""")


def add_item():
    code = input("Item code : ").strip().upper()
    name = input("Item name : ").strip()
    cat = input("Category (Books/Stationery/Electronics): ").strip().title()
    price, stock = float(input("Price     : ")), int(input("Stock     : "))
    if cat not in GST:
        print("Unknown category.")
        return
    cur.execute("INSERT INTO items VALUES (%s,%s,%s,%s,%s,%s)", (code, name, cat, price, GST[cat], stock))
    conn.commit()
    print(f"{name} added with GST {GST[cat]}%.")


def show_items():
    cur.execute("SELECT * FROM items ORDER BY category, code")
    print(f"{'Code':<5}{'Name':<23}{'Category':<12}{'Price':>8}{'GST':>5}{'Stock':>6}")
    for r in cur.fetchall():
        print(f"{r[0]:<5}{r[1]:<23}{r[2]:<12}{float(r[3]):>8.2f}{r[4]:>4}%{r[5]:>6}")


def print_invoice(no):
    cur.execute("SELECT * FROM invoice WHERE inv_no = %s", (no,))
    inv = cur.fetchone()
    if not inv:
        print("Invoice not found.")
        return
    cur.execute("""SELECT i.name, t.qty, t.rate, t.gst FROM inv_items t JOIN items i
                   ON t.code = i.code WHERE t.inv_no = %s""", (no,))
    print("=" * 58)
    print("KV BOOK & STATIONERY HOUSE  -  TAX INVOICE".center(58))
    print(f"Invoice No: {inv[0]:<10} Customer: {inv[1]}")
    print("-" * 58)
    print(f"{'Item':<23}{'Qty':>4}{'Rate':>9}{'GST':>5}{'Amount':>11}")
    for n, q, r, g in cur.fetchall():
        print(f"{n:<23}{q:>4}{float(r):>9.2f}{g:>4}%{q * float(r):>11.2f}")
    print("-" * 58)
    gst = float(inv[4])
    print(f"{'Sub total':<40}{float(inv[2]):>12.2f}")
    print(f"{'Discount (5% above Rs. 2000)':<40}{-float(inv[3]):>12.2f}")
    print(f"{'CGST':<40}{gst / 2:>12.2f}\n{'SGST':<40}{gst / 2:>12.2f}")
    print(f"{'GRAND TOTAL':<40}{float(inv[5]):>12.2f}")
    print("=" * 58)


def new_invoice():
    cust = input("Customer name: ").strip().title()
    cart = []
    while True:
        code = input("Item code (blank to finish): ").strip().upper()
        if not code:
            break
        qty = int(input("Quantity : "))
        cur.execute("SELECT name, price, gst, stock FROM items WHERE code = %s", (code,))
        it = cur.fetchone()
        if not it:
            print("Item not found.")
        elif qty > it[3]:
            print(f"Only {it[3]} in stock.")
        else:
            cart.append((code, qty, float(it[1]), it[2]))
            print(f"  Added {qty} x {it[0]}")
    if not cart:
        print("Empty cart - no invoice.")
        return
    sub = sum(q * r for _, q, r, _ in cart)
    disc = round(sub * 0.05, 2) if sub > 2000 else 0
    factor = (sub - disc) / sub
    gst = round(sum(q * r * g / 100 for _, q, r, g in cart) * factor, 2)
    total = round(sub - disc + gst, 2)
    cur.execute("INSERT INTO invoice (customer, subtotal, discount, gst_amt, total) VALUES (%s,%s,%s,%s,%s)",
                (cust, sub, disc, gst, total))
    no = cur.lastrowid
    cur.executemany("INSERT INTO inv_items VALUES (%s,%s,%s,%s,%s)", [(no,) + c for c in cart])
    for code, q, _, _ in cart:
        cur.execute("UPDATE items SET stock = stock - %s WHERE code = %s", (q, code))
    conn.commit()
    print_invoice(no)


def find_invoice():
    print_invoice(int(input("Invoice number: ")))


def sales_report():
    cur.execute("""SELECT i.category, SUM(t.qty), SUM(t.qty * t.rate), SUM(t.qty * t.rate * t.gst / 100)
                   FROM inv_items t JOIN items i ON t.code = i.code GROUP BY i.category""")
    print(f"{'Category':<13}{'Qty':>5}{'Sales':>11}{'GST':>10}")
    for c, q, s, g in cur.fetchall():
        print(f"{c:<13}{int(q):>5}{float(s):>11.2f}{float(g):>10.2f}")
    cur.execute("SELECT COUNT(*), SUM(total) FROM invoice")
    n, t = cur.fetchone()
    print(f"Invoices: {n} | Net collection Rs. {float(t):.2f}")


def purchase():
    code, qty = input("Item code: ").strip().upper(), int(input("Quantity purchased: "))
    cur.execute("UPDATE items SET stock = stock + %s WHERE code = %s", (qty, code))
    conn.commit()
    print("Stock updated." if cur.rowcount else "Item not found.")


def low_stock():
    cur.execute("SELECT code, name, stock FROM items WHERE stock < 5")
    rows = cur.fetchall()
    for r in rows:
        print(f"  LOW: {r[0]} {r[1]} - only {r[2]} left")
    if not rows:
        print("All items have sufficient stock.")


def export_csv():
    cur.execute("SELECT * FROM invoice")
    rows = cur.fetchall()
    with open("invoices.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["inv_no", "customer", "subtotal", "discount", "gst", "total"])
        w.writerows(rows)
    print(len(rows), "invoices exported to invoices.csv")
    with open("invoices.csv") as f:
        print(f.read().strip())


menu = {"1": add_item, "2": show_items, "3": new_invoice, "4": find_invoice, "5": sales_report,
        "6": purchase, "7": low_stock, "8": export_csv}
print("=" * 58)
print("GST BILLING SYSTEM (Python + MySQL)".center(58))
print("=" * 58)
while True:
    print("\n1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Thank you, visit again!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except (ValueError, mysql.connector.Error) as e:
        print("Error:", e)

        
  1. Start
  2. Connect to MySQL and create tables
  3. Display menu and read choice
  4. Choice is New Invoice? → No: run selected option
  5. Read item code and quantity (blank to finish)
  6. Item exists and stock enough? → No: show message
  7. Add to cart, compute GST
  8. Apply discount, save invoice, reduce stock, COMMIT
  9. Print invoice
  10. Choice is 0? → No: show menu
  11. Stop
#Test case / inputExpected resultStatus
1Add item B01 BookGST 5 % autoPASS
2Bill 2 books + 1 bagCGST + SGST correctPASS
3Quantity more than stock'Only n in stock'PASS
4Wrong item code'Item not found'PASS
5Bill above Rs. 20005 % discountPASS
6Find invoice 1Old bill reprintedPASS
7Sales reportCategory totals with GROUP BYPASS
8Purchase 10 pensStock updatedPASS
9Low stockItems < 5 listedPASS
10Export CSVFile writtenPASS
โš  Limitations
  • GST slabs fixed in the program
  • No customer GSTIN / HSN printing
  • Single counter
  • No returns module
๐Ÿš€ Future scope
  • Print PDF invoice with QR code (UPI)
  • Customer loyalty points
  • GSTR-1 monthly summary
  • Barcode scanner input

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): mysql.connector - connecting Python with MySQL, csv - reading / writing CSV files are loaded.
  2. Global variables / constants are created: GST, conn, cur.
  3. 9 functions are defined (lines 22โ€“141) - Python stores them but does NOT run them yet.
  4. Main program starts at line 11: cur.execute("CREATE DATABASE IF NOT EXISTS shopdb") - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
add_item()22โ€“32Add itemmain program (menu)
show_items()35โ€“39Show itemsmain program (menu)
print_invoice(no)42โ€“63Print invoicenew_invoice(), find_invoice()
new_invoice()66โ€“98New invoicemain program (menu)
find_invoice()101โ€“102Find invoicemain program (menu)
sales_report()105โ€“113Sales reportmain program (menu)
purchase()116โ€“120Purchasemain program (menu)
low_stock()123โ€“129Low stockmain program (menu)
export_csv()132โ€“141Export csvmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
11
cur.execute("CREATE DATABASE IF NOT EXISTS shopdb")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
12
cur.execute("USE shopdb")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
13
cur.execute("""CREATE TABLE IF NOT EXISTS items (code CHAR(3) PRIMARY KEY, name VARCHAR(30),
               category VARCHAR(15), price DECIMAL(8,2), gst INTโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
15
cur.execute("""CREATE TABLE IF NOT EXISTS invoice (inv_no INT PRIMARY KEY AUTO_INCREMENT,
               customer VARCHAR(30), subtotal DECIMAL(10,2), discouโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
18
cur.execute("""CREATE TABLE IF NOT EXISTS inv_items (inv_no INT, code CHAR(3), qty INT,
               rate DECIMAL(8,2), gst INT)""")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
144
menu = {"1": add_item, "2": show_items, "3": new_invoice, "4": find_invoice, "5": sales_report,
        "6": purchase, "7": low_stock, "8": export_csv}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add_item, "2": show_items, "3": new_invโ€ฆ in variable menu
146
print("=" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "=" signs on the screen
147
print("GST BILLING SYSTEM (Python + MySQL)".center(58))
๐Ÿ–ฅ๏ธ Output Displays the value of "GST BILLING SYSTEM (Python + MySQL)".center(โ€ฆ on the screen
148
print("=" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "=" signs on the screen
149
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
150
print("\n1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add Item 2.Items 3.New Invoice โ€ฆ" on the screen
151
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
152
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
153
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
154
print("Thank you, visit again!")
๐Ÿ–ฅ๏ธ Output Displays the text "Thank you, visit again!" on the screen
155
break
๐Ÿ” Loop BREAK - leaves the loop immediately
156
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
157
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
158
except (ValueError, mysql.connector.Error) as e:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, mysql.connector.Error) occurs - that error
159
print("Error:", e)
๐Ÿ–ฅ๏ธ Output Displays the text "Error:", then the value of e on the screen
โ‘ฃ Inside each function - line by line
add_item() - lines 22โ€“32
LineCodeWhat it does
22
def add_item():
๐Ÿงฉ Function DEFINES a function add_item(). Python only remembers it here - its body runs later, each time add_item() is called.
23
code = input("Item code : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
24
name = input("Item name : ").strip()
โŒจ๏ธ Input Shows "Item name : ", reads the typed text, removes extra spaces (strip) and stores it in variable name
25
cat = input("Category (Books/Stationery/Electronics): ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cat
26
price, stock = float(input("Price     : ")), int(input("Stock     : "))
โŒจ๏ธ Input Stores float(input("Price : ")), int(input("Stock : ")) into price, stock respectively
27
if cat not in GST:
๐Ÿ”€ Decision CHECKS whether cat is not present in GST. If True, the indented lines below run; otherwise they are skipped
28
print("Unknown category.")
๐Ÿ–ฅ๏ธ Output Displays the text "Unknown category." on the screen
29
return
๐Ÿงฉ Function Ends the function and goes back to the caller
30
cur.execute("INSERT INTO items VALUES (%s,%s,%s,%s,%s,%s)", (code, name, cat, price, GST[cat], stock))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (code, name, cat, price, GST[cat], stock)
31
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
32
print(f"{name} added with GST {GST[cat]}%.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name} added with GST {GST[cat]}%." with the values filled into { } on the screen
show_items() - lines 35โ€“39
LineCodeWhat it does
35
def show_items():
๐Ÿงฉ Function DEFINES a function show_items(). Python only remembers it here - its body runs later, each time show_items() is called.
36
cur.execute("SELECT * FROM items ORDER BY category, code")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
37
print(f"{'Code':<5}{'Name':<23}{'Category':<12}{'Price':>8}{'GST':>5}{'Stock':>6}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Code':<5}{'Name':<23}{'Category':<12}{'Prโ€ฆ with the values filled into { } on the screen
38
for r in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into r and runs the indented block for it
39
print(f"{r[0]:<5}{r[1]:<23}{r[2]:<12}{float(r[3]):>8.2f}{r[4]:>4}%{r[5]:>6}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r[0]:<5}{r[1]:<23}{r[2]:<12}{float(r[3]):>โ€ฆ with the values filled into { } on the screen
print_invoice() - lines 42โ€“63
LineCodeWhat it does
42
def print_invoice(no):
๐Ÿงฉ Function DEFINES a function print_invoice(no). Python only remembers it here - its body runs later, each time print_invoice() is called.
43
cur.execute("SELECT * FROM invoice WHERE inv_no = %s", (no,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (no,)
44
inv = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable inv
45
if not inv:
๐Ÿ”€ Decision CHECKS whether inv is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
46
print("Invoice not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invoice not found." on the screen
47
return
๐Ÿงฉ Function Ends the function and goes back to the caller
48
cur.execute("""SELECT i.name, t.qty, t.rate, t.gst FROM inv_items t JOIN items i
               ON t.code = i.code WHERE t.inv_no = %s""", (no,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (no,)
50
print("=" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "=" signs on the screen
51
print("KV BOOK & STATIONERY HOUSE  -  TAX INVOICE".center(58))
๐Ÿ–ฅ๏ธ Output Displays the value of "KV BOOK & STATIONERY HOUSE - TAX INVOICE".ceโ€ฆ on the screen
52
print(f"Invoice No: {inv[0]:<10} Customer: {inv[1]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Invoice No: {inv[0]:<10} Customer: {inv[1]}" with the values filled into { } on the screen
53
print("-" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "-" signs on the screen
54
print(f"{'Item':<23}{'Qty':>4}{'Rate':>9}{'GST':>5}{'Amount':>11}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Item':<23}{'Qty':>4}{'Rate':>9}{'GST':>5}โ€ฆ with the values filled into { } on the screen
55
for n, q, r, g in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into n, q, r, g and runs the indented block for it
56
print(f"{n:<23}{q:>4}{float(r):>9.2f}{g:>4}%{q * float(r):>11.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<23}{q:>4}{float(r):>9.2f}{g:>4}%{q * flโ€ฆ with the values filled into { } on the screen
57
print("-" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "-" signs on the screen
58
gst = float(inv[4])
๐Ÿงฎ Store / Calculate Converts inv[4] into a decimal number (float); the result is stored in variable gst
59
print(f"{'Sub total':<40}{float(inv[2]):>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Sub total':<40}{float(inv[2]):>12.2f}" with the values filled into { } on the screen
60
print(f"{'Discount (5% above Rs. 2000)':<40}{-float(inv[3]):>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Discount (5% above Rs. 2000)':<40}{-floatโ€ฆ with the values filled into { } on the screen
61
print(f"{'CGST':<40}{gst / 2:>12.2f}\n{'SGST':<40}{gst / 2:>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'CGST':<40}{gst / 2:>12.2f}\n{'SGST':<40}{โ€ฆ with the values filled into { } on the screen
62
print(f"{'GRAND TOTAL':<40}{float(inv[5]):>12.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'GRAND TOTAL':<40}{float(inv[5]):>12.2f}" with the values filled into { } on the screen
63
print("=" * 58)
๐Ÿ–ฅ๏ธ Output Displays a line of 58 "=" signs on the screen
new_invoice() - lines 66โ€“98
LineCodeWhat it does
66
def new_invoice():
๐Ÿงฉ Function DEFINES a function new_invoice(). Python only remembers it here - its body runs later, each time new_invoice() is called.
67
cust = input("Customer name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable cust
68
cart = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable cart
69
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
70
code = input("Item code (blank to finish): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
71
if not code:
๐Ÿ”€ Decision CHECKS whether code is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
72
break
๐Ÿ” Loop BREAK - leaves the loop immediately
73
qty = int(input("Quantity : "))
โŒจ๏ธ Input Shows "Quantity : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable qty
74
cur.execute("SELECT name, price, gst, stock FROM items WHERE code = %s", (code,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (code,)
75
it = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable it
76
if not it:
๐Ÿ”€ Decision CHECKS whether it is False (or empty / zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
77
print("Item not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Item not found." on the screen
78
elif qty > it[3]:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether qty is greater than it[3]
79
print(f"Only {it[3]} in stock.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Only {it[3]} in stock." with the values filled into { } on the screen
80
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
81
cart.append((code, qty, float(it[1]), it[2]))
๐Ÿงฎ Store / Calculate Adds (code, qty, float(it[1]), it[2]) at the end of list cart
82
print(f"  Added {qty} x {it[0]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Added {qty} x {it[0]}" with the values filled into { } on the screen
83
if not cart:
๐Ÿ”€ Decision CHECKS whether cart is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
84
print("Empty cart - no invoice.")
๐Ÿ–ฅ๏ธ Output Displays the text "Empty cart - no invoice." on the screen
85
return
๐Ÿงฉ Function Ends the function and goes back to the caller
86
sub = sum(q * r for _, q, r, _ in cart)
๐Ÿงฎ Store / Calculate Adds up all the values in (q * r for _, q, r, _ in cart); the result is stored in variable sub
87
disc = round(sub * 0.05, 2) if sub > 2000 else 0
๐Ÿงฎ Store / Calculate Stores either round(sub * 0.05, 2) or 0 depending on sub > 2000 in variable disc
88
factor = (sub - disc) / sub
๐Ÿงฎ Store / Calculate Stores the value of (sub - disc) / sub (calculated using รท) in variable factor
89
gst = round(sum(q * r * g / 100 for _, q, r, g in cart) * factor, 2)
๐Ÿงฎ Store / Calculate Rounds sum(q * r * g / 100 for _, q, r, g in cart) *โ€ฆ to 2 decimal places; the result is stored in variable gst
90
total = round(sub - disc + gst, 2)
๐Ÿงฎ Store / Calculate Rounds sub - disc + gst to 2 decimal places; the result is stored in variable total
91
cur.execute("INSERT INTO invoice (customer, subtotal, discount, gst_amt, total) VALUES (%s,%s,%s,%s,%s)",
            (cust, sub, disc, gst, total))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (cust, sub, disc, gst, total)
93
no = cur.lastrowid
๐Ÿงฎ Store / Calculate Stores cur.lastrowid in variable no
94
cur.executemany("INSERT INTO inv_items VALUES (%s,%s,%s,%s,%s)", [(no,) + c for c in cart])
๐Ÿฌ Database Runs the same SQL for every row of [(no,) + c for c in cart]
95
for code, q, _, _ in cart:
๐Ÿ” Loop LOOP: takes each item of cart one-by-one into code, q, _, _ and runs the indented block for it
96
cur.execute("UPDATE items SET stock = stock - %s WHERE code = %s", (q, code))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (q, code)
97
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
98
print_invoice(no)
๐Ÿงฎ Store / Calculate Calls our own function print_invoice(no)
find_invoice() - lines 101โ€“102
LineCodeWhat it does
101
def find_invoice():
๐Ÿงฉ Function DEFINES a function find_invoice(). Python only remembers it here - its body runs later, each time find_invoice() is called.
102
print_invoice(int(input("Invoice number: ")))
โŒจ๏ธ Input Calls our own function print_invoice(int(input("Invoice โ€ฆ)
sales_report() - lines 105โ€“113
LineCodeWhat it does
105
def sales_report():
๐Ÿงฉ Function DEFINES a function sales_report(). Python only remembers it here - its body runs later, each time sales_report() is called.
106
cur.execute("""SELECT i.category, SUM(t.qty), SUM(t.qty * t.rate), SUM(t.qty * t.rate * t.gst / 100)
               FROM inv_items t JOIN items i ON t.code =โ€ฆ
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
108
print(f"{'Category':<13}{'Qty':>5}{'Sales':>11}{'GST':>10}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Category':<13}{'Qty':>5}{'Sales':>11}{'GSโ€ฆ with the values filled into { } on the screen
109
for c, q, s, g in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into c, q, s, g and runs the indented block for it
110
print(f"{c:<13}{int(q):>5}{float(s):>11.2f}{float(g):>10.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c:<13}{int(q):>5}{float(s):>11.2f}{float(gโ€ฆ with the values filled into { } on the screen
111
cur.execute("SELECT COUNT(*), SUM(total) FROM invoice")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
112
n, t = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables n, t
113
print(f"Invoices: {n} | Net collection Rs. {float(t):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Invoices: {n} | Net collection Rs. {float(tโ€ฆ with the values filled into { } on the screen
purchase() - lines 116โ€“120
LineCodeWhat it does
116
def purchase():
๐Ÿงฉ Function DEFINES a function purchase(). Python only remembers it here - its body runs later, each time purchase() is called.
117
code, qty = input("Item code: ").strip().upper(), int(input("Quantity purchased: "))
โŒจ๏ธ Input Stores input("Item code: ").strip().upper(), int(input("Quantity purchased: ")) into code, qty respectively
118
cur.execute("UPDATE items SET stock = stock + %s WHERE code = %s", (qty, code))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (qty, code)
119
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
120
print("Stock updated." if cur.rowcount else "Item not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Stock updated." if cur.rowcount else "Item nโ€ฆ on the screen
low_stock() - lines 123โ€“129
LineCodeWhat it does
123
def low_stock():
๐Ÿงฉ Function DEFINES a function low_stock(). Python only remembers it here - its body runs later, each time low_stock() is called.
124
cur.execute("SELECT code, name, stock FROM items WHERE stock < 5")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
125
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
126
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
127
print(f"  LOW: {r[0]} {r[1]} - only {r[2]} left")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" LOW: {r[0]} {r[1]} - only {r[2]} left" with the values filled into { } on the screen
128
if not rows:
๐Ÿ”€ Decision CHECKS whether rows is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
129
print("All items have sufficient stock.")
๐Ÿ–ฅ๏ธ Output Displays the text "All items have sufficient stock." on the screen
export_csv() - lines 132โ€“141
LineCodeWhat it does
132
def export_csv():
๐Ÿงฉ Function DEFINES a function export_csv(). Python only remembers it here - its body runs later, each time export_csv() is called.
133
cur.execute("SELECT * FROM invoice")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
134
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
135
with open("invoices.csv", "w", newline="") as f:
๐Ÿ“ File Opens the file "invoices.csv" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
136
w = csv.writer(f)
๐Ÿ“ File Creates a CSV writer object for file f; the result is stored in variable w
137
w.writerow(["inv_no", "customer", "subtotal", "discount", "gst", "total"])
๐Ÿ“ File Writes one row ["inv_no", "customer", "subtotal", "discount"โ€ฆ into the CSV file
138
w.writerows(rows)
๐Ÿ“ File Writes many rows (rows) into the CSV file
139
print(len(rows), "invoices exported to invoices.csv")
๐Ÿ–ฅ๏ธ Output Displays the value of len(rows), then the text "invoices exported to invoices.csv" on the screen
140
with open("invoices.csv") as f:
๐Ÿ“ File Opens the file "invoices.csv" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
141
print(f.read().strip())
๐Ÿ“ File Displays the value of f.read().strip() on the screen
Q1. Why is GST split into CGST and SGST?

For sales within a state, half the GST goes to the Centre (CGST) and half to the State (SGST).

Q2. How are multiple rows inserted at once?

cursor.executemany(query, list_of_tuples) inserts all invoice items in one call.

Q3. Which SQL clause gives category-wise totals?

GROUP BY category with SUM(qty*rate).

Q4. What happens if commit() is missed?

The invoice and stock changes stay uncommitted and are lost when the connection closes.

Q5. How is the CSV export done?

Rows fetched with fetchall() are written using csv.writer(f).writerows(rows).

06

Student Management System (Python + MySQL)

PYTHON + MySQLPython-MySQL connectivityparameterised queriesCRUD operationsfetchall()/fetchone()aggregate functions
๐Ÿ“ 130 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 152 output lines๐Ÿ“„ 25+ page report

Admit, display, search, update marks, delete and rank students stored in a MySQL table; the database and table are created automatically on first run.

โœจ Features
  • Student table in MySQL with roll no, name, class, section, stream and marks in 5 subjects
  • Total, percentage and grade (CBSE style A1-E) calculated in SQL / Python
  • CRUD: add, display, search (roll / name with LIKE), update marks, delete
  • Class result: topper, average, pass percentage using aggregate functions
  • Section-wise analysis with GROUP BY and HAVING
  • Merit list using ORDER BY and LIMIT; parameterised queries everywhere
โ˜ฐ Main menu
1Add StudentINSERT with marks validation 0-100
2Display AllSELECT * with total and grade
3SearchBy roll number or name (LIKE)
4Update MarksUPDATE one subject
5Delete StudentDELETE by roll number
6Merit ListTop 3 using ORDER BY ... LIMIT
7Class ResultCOUNT, AVG, MAX and pass %
8Section AnalysisGROUP BY section HAVING
0ExitCloses the connection
๐ŸŽฏ Objectives
  • Perform CRUD operations through mysql.connector
  • Use fetchone(), fetchall() and rowcount
  • Rank records using ORDER BY and LIMIT
๐Ÿ“š Data dictionary
NameTypePurpose
studentMySQL tableroll INT PK, name, section, stream, eng, maths, phy, chem, cs (INT)
SUBJlistSubject column names
grade()functionReturns A1..E from percentage
cur.rowcountintRows affected by UPDATE / DELETE
Why it matters: The classic CBSE board project - complete CRUD operations through mysql.connector with clean menu-driven code.
# =====================================================================
#   STUDENT MANAGEMENT SYSTEM  (Python + MySQL)
#   Concepts : mysql.connector, CRUD, parameterised queries, LIKE,
#              aggregate functions, GROUP BY / HAVING, ORDER BY / LIMIT
# =====================================================================
import mysql.connector
from mysql.connector import IntegrityError

SUBJ = ["eng", "maths", "phy", "chem", "cs"]
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS sms_db")
cur.execute("USE sms_db")
cur.execute("""CREATE TABLE IF NOT EXISTS student (roll INT PRIMARY KEY, name VARCHAR(25) NOT NULL,
               section CHAR(1), stream VARCHAR(10), eng INT, maths INT, phy INT, chem INT, cs INT)""")
TOTAL = "(eng + maths + phy + chem + cs)"


def grade(p):
    for cut, g in ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"), (41, "C2"), (33, "D")):
        if p >= cut:
            return g
    return "E"


def add():
    roll = int(input("Roll no : "))
    name = input("Name    : ").strip().title()
    sec = input("Section : ").strip().upper()
    stream = input("Stream  : ").strip().title()
    marks = []
    for s in SUBJ:
        m = int(input(f"{s.upper():<6}marks: "))
        if not 0 <= m <= 100:
            print("Marks must be 0-100. Record not saved.")
            return
        marks.append(m)
    try:
        cur.execute("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)", (roll, name, sec, stream, *marks))
        conn.commit()
        print("Student added.")
    except IntegrityError:
        print("Roll number", roll, "already exists.")


def show(rows):
    print(f"{'Roll':<5}{'Name':<15}{'Sec':<4}{'ENG':>4}{'MAT':>4}{'PHY':>4}{'CHE':>4}{'CS':>4}{'Total':>6}{'%':>6} Grade")
    print("-" * 66)
    for r in rows:
        tot = sum(r[4:9])
        print(f"{r[0]:<5}{r[1]:<15}{r[2]:<4}" + "".join(f"{m:>4}" for m in r[4:9]) + f"{tot:>6}{tot / 5:>6.1f} {grade(tot / 5)}")


def display():
    cur.execute("SELECT * FROM student ORDER BY roll")
    show(cur.fetchall())


def search():
    key = input("Roll no or part of name: ").strip()
    if key.isdigit():
        cur.execute("SELECT * FROM student WHERE roll = %s", (int(key),))
    else:
        cur.execute("SELECT * FROM student WHERE name LIKE %s", ("%" + key + "%",))
    rows = cur.fetchall()
    show(rows) if rows else print("No match.")


def update():
    roll = int(input("Roll no : "))
    sub = input("Subject (eng/maths/phy/chem/cs): ").strip().lower()
    m = int(input("New marks: "))
    if sub not in SUBJ or not 0 <= m <= 100:
        print("Invalid subject or marks.")
        return
    cur.execute(f"UPDATE student SET {sub} = %s WHERE roll = %s", (m, roll))
    conn.commit()
    print(cur.rowcount, "row updated.")


def delete():
    roll = int(input("Roll no to delete: "))
    cur.execute("DELETE FROM student WHERE roll = %s", (roll,))
    conn.commit()
    print("Deleted." if cur.rowcount else "No such student.")


def merit():
    cur.execute(f"SELECT roll, name, {TOTAL} AS total FROM student ORDER BY total DESC LIMIT 3")
    for i, (r, n, t) in enumerate(cur.fetchall(), 1):
        print(f"  Rank {i}: {n:<15} (Roll {r})  Total {t}/500  {t / 5:.1f}%")


def result():
    cur.execute(f"SELECT COUNT(*), AVG({TOTAL}) / 5, MAX({TOTAL}), MIN({TOTAL}) FROM student")
    n, avg, mx, mn = cur.fetchone()
    cur.execute("SELECT COUNT(*) FROM student WHERE LEAST(eng, maths, phy, chem, cs) >= 33")
    passed = cur.fetchone()[0]
    print(f"Students: {n} | Class average: {float(avg):.2f}% | Highest: {mx} | Lowest: {mn}")
    print(f"Passed in all subjects: {passed}/{n}  -> Pass percentage {passed * 100 / n:.1f}%")
    for s in SUBJ:
        cur.execute(f"SELECT AVG({s}), MAX({s}) FROM student")
        a, m = cur.fetchone()
        print(f"  {s.upper():<6} average {float(a):6.2f}  highest {m}")


def section_analysis():
    cur.execute(f"""SELECT section, COUNT(*), ROUND(AVG({TOTAL}) / 5, 2) FROM student
                    GROUP BY section HAVING AVG({TOTAL}) / 5 > 65""")
    print("Sections with average above 65 %:")
    for s, c, a in cur.fetchall():
        print(f"  Section {s}: {c} students, average {a}%")


menu = {"1": add, "2": display, "3": search, "4": update, "5": delete, "6": merit, "7": result, "8": section_analysis}
print("=" * 66)
print("STUDENT MANAGEMENT SYSTEM  (Python + MySQL)".center(66))
print("=" * 66)
while True:
    print("\n1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Bye!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Please enter numbers correctly.")

        
  1. Start
  2. Connect and create sms_db.student
  3. Display menu and read choice
  4. Valid choice? → No: show 'Invalid choice'
  5. Build parameterised SQL query
  6. cursor.execute(), fetchall() / commit()
  7. Display rows / result
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Add roll 1 with marksRow insertedPASS
2Duplicate rollIntegrityError handledPASS
3Marks 105'Marks must be 0-100'PASS
4Search 'aan'Aanya and Ishaan listedPASS
5Update CS of roll 3 to 951 row updatedPASS
6Delete roll 99'No such student'PASS
7Merit listTop 3 by totalPASS
8Class resultAverage and pass %PASS
9Section analysisOnly sections with avg > 65 (B filtered out)PASS
โš  Limitations
  • MySQL password stored in code
  • Only 5 fixed subjects
  • No report-card printing
  • Console only
๐Ÿš€ Future scope
  • Export report cards to PDF
  • Attendance table with JOIN
  • Graphs of result with Matplotlib
  • Login for class teachers

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): mysql.connector - connecting Python with MySQL, IntegrityError are loaded.
  2. Global variables / constants are created: SUBJ, conn, cur, TOTAL.
  3. 10 functions are defined (lines 19โ€“112) - Python stores them but does NOT run them yet.
  4. Main program starts at line 12: cur.execute("CREATE DATABASE IF NOT EXISTS sms_db") - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
grade(p)19โ€“23Gradeshow()
add()26โ€“43Addmain program (menu)
show(rows)46โ€“51Showdisplay(), search()
display()54โ€“56Displaymain program (menu)
search()59โ€“66Searchmain program (menu)
update()69โ€“78Updatemain program (menu)
delete()81โ€“85Deletemain program (menu)
merit()88โ€“91Meritmain program (menu)
result()94โ€“104Resultmain program (menu)
section_analysis()107โ€“112Section analysismain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
12
cur.execute("CREATE DATABASE IF NOT EXISTS sms_db")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
13
cur.execute("USE sms_db")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
14
cur.execute("""CREATE TABLE IF NOT EXISTS student (roll INT PRIMARY KEY, name VARCHAR(25) NOT NULL,
               section CHAR(1), stream VARCHAR(10), eng Iโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
16
TOTAL = "(eng + maths + phy + chem + cs)"
๐Ÿงฎ Store / Calculate Stores the text "(eng + maths + phy + chem + cs)" in variable TOTAL
115
menu = {"1": add, "2": display, "3": search, "4": update, "5": delete, "6": merit, "7": result, "8": section_analysis}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add, "2": display, "3": search, "4": upโ€ฆ in variable menu
116
print("=" * 66)
๐Ÿ–ฅ๏ธ Output Displays a line of 66 "=" signs on the screen
117
print("STUDENT MANAGEMENT SYSTEM  (Python + MySQL)".center(66))
๐Ÿ–ฅ๏ธ Output Displays the value of "STUDENT MANAGEMENT SYSTEM (Python + MySQL)".โ€ฆ on the screen
118
print("=" * 66)
๐Ÿ–ฅ๏ธ Output Displays a line of 66 "=" signs on the screen
119
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
120
print("\n1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Display 3.Search 4.Updateโ€ฆ" on the screen
121
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
122
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
123
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
124
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
125
break
๐Ÿ” Loop BREAK - leaves the loop immediately
126
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
127
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
128
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
129
print("Please enter numbers correctly.")
๐Ÿ–ฅ๏ธ Output Displays the text "Please enter numbers correctly." on the screen
โ‘ฃ Inside each function - line by line
grade() - lines 19โ€“23
LineCodeWhat it does
19
def grade(p):
๐Ÿงฉ Function DEFINES a function grade(p). Python only remembers it here - its body runs later, each time grade() is called.
20
for cut, g in ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"), (41, "C2"), (33, "D")):
๐Ÿ” Loop LOOP: takes each item of ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2โ€ฆ one-by-one into cut, g and runs the indented block for it
21
if p >= cut:
๐Ÿ”€ Decision CHECKS whether p is greater than or equal to cut. If True, the indented lines below run; otherwise they are skipped
22
return g
๐Ÿงฉ Function Sends back (returns) the value of g to the line that called the function
23
return "E"
๐Ÿงฉ Function Sends back (returns) the text "E" to the line that called the function
add() - lines 26โ€“43
LineCodeWhat it does
26
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
27
roll = int(input("Roll no : "))
โŒจ๏ธ Input Shows "Roll no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
28
name = input("Name    : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
29
sec = input("Section : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable sec
30
stream = input("Stream  : ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable stream
31
marks = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable marks
32
for s in SUBJ:
๐Ÿ” Loop LOOP: takes each item of SUBJ one-by-one into s and runs the indented block for it
33
m = int(input(f"{s.upper():<6}marks: "))
โŒจ๏ธ Input Shows f"{s.upper():<6}marks: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable m
34
if not 0 <= m <= 100:
๐Ÿ”€ Decision CHECKS whether NOT 0 <= m <= 100 is True. If True, the indented lines below run; otherwise they are skipped
35
print("Marks must be 0-100. Record not saved.")
๐Ÿ–ฅ๏ธ Output Displays the text "Marks must be 0-100. Record not sโ€ฆ" on the screen
36
return
๐Ÿงฉ Function Ends the function and goes back to the caller
37
marks.append(m)
๐Ÿงฎ Store / Calculate Adds m at the end of list marks
38
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
39
cur.execute("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)", (roll, name, sec, stream, *marks))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (roll, name, sec, stream, *marks)
40
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
41
print("Student added.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student added." on the screen
42
except IntegrityError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if IntegrityError occurs - that error
43
print("Roll number", roll, "already exists.")
๐Ÿ–ฅ๏ธ Output Displays the text "Roll number", then the value of roll, then the text "already exists." on the screen
show() - lines 46โ€“51
LineCodeWhat it does
46
def show(rows):
๐Ÿงฉ Function DEFINES a function show(rows). Python only remembers it here - its body runs later, each time show() is called.
47
print(f"{'Roll':<5}{'Name':<15}{'Sec':<4}{'ENG':>4}{'MAT':>4}{'PHY':>4}{'CHE':>4}{'CS':>4}{'Total':>6}{'%':>6} Grade")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Roll':<5}{'Name':<15}{'Sec':<4}{'ENG':>4}โ€ฆ with the values filled into { } on the screen
48
print("-" * 66)
๐Ÿ–ฅ๏ธ Output Displays a line of 66 "-" signs on the screen
49
for r in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into r and runs the indented block for it
50
tot = sum(r[4:9])
๐Ÿงฎ Store / Calculate Adds up all the values in r[4:9]; the result is stored in variable tot
51
print(f"{r[0]:<5}{r[1]:<15}{r[2]:<4}" + "".join(f"{m:>4}" for m in r[4:9]) + f"{tot:>6}{tot / 5:>6.1f} {grade(tot / 5)}")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{r[0]:<5}{r[1]:<15}{r[2]:<4}" + "".join(f"{โ€ฆ on the screen
display() - lines 54โ€“56
LineCodeWhat it does
54
def display():
๐Ÿงฉ Function DEFINES a function display(). Python only remembers it here - its body runs later, each time display() is called.
55
cur.execute("SELECT * FROM student ORDER BY roll")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
56
show(cur.fetchall())
๐Ÿฌ Database Calls our own function show(cur.fetchall())
search() - lines 59โ€“66
LineCodeWhat it does
59
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
60
key = input("Roll no or part of name: ").strip()
โŒจ๏ธ Input Shows "Roll no or part of name: ", reads the typed text, removes extra spaces (strip) and stores it in variable key
61
if key.isdigit():
๐Ÿ”€ Decision CHECKS whether key.isdigit() is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
62
cur.execute("SELECT * FROM student WHERE roll = %s", (int(key),))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (int(key),)
63
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
64
cur.execute("SELECT * FROM student WHERE name LIKE %s", ("%" + key + "%",))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values ("%" + key + "%",)
65
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
66
show(rows) if rows else print("No match.")
๐Ÿ–ฅ๏ธ Output Evaluates show(rows) if rows else print("No match.")
update() - lines 69โ€“78
LineCodeWhat it does
69
def update():
๐Ÿงฉ Function DEFINES a function update(). Python only remembers it here - its body runs later, each time update() is called.
70
roll = int(input("Roll no : "))
โŒจ๏ธ Input Shows "Roll no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
71
sub = input("Subject (eng/maths/phy/chem/cs): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable sub
72
m = int(input("New marks: "))
โŒจ๏ธ Input Shows "New marks: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable m
73
if sub not in SUBJ or not 0 <= m <= 100:
๐Ÿ”€ Decision CHECKS whether (sub is not present in SUBJ OR NOT 0 <= m <= 100 is True). If True, the indented lines below run; otherwise they are skipped
74
print("Invalid subject or marks.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid subject or marks." on the screen
75
return
๐Ÿงฉ Function Ends the function and goes back to the caller
76
cur.execute(f"UPDATE student SET {sub} = %s WHERE roll = %s", (m, roll))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (m, roll)
77
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
78
print(cur.rowcount, "row updated.")
๐Ÿ–ฅ๏ธ Output Displays the value of cur.rowcount, then the text "row updated." on the screen
delete() - lines 81โ€“85
LineCodeWhat it does
81
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
82
roll = int(input("Roll no to delete: "))
โŒจ๏ธ Input Shows "Roll no to delete: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable roll
83
cur.execute("DELETE FROM student WHERE roll = %s", (roll,))
๐Ÿฌ Database Sends a DELETE query (removes rows) to MySQL through the cursor; the %s places are filled safely with the values (roll,)
84
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
85
print("Deleted." if cur.rowcount else "No such student.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Deleted." if cur.rowcount else "No such studโ€ฆ on the screen
merit() - lines 88โ€“91
LineCodeWhat it does
88
def merit():
๐Ÿงฉ Function DEFINES a function merit(). Python only remembers it here - its body runs later, each time merit() is called.
89
cur.execute(f"SELECT roll, name, {TOTAL} AS total FROM student ORDER BY total DESC LIMIT 3")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
90
for i, (r, n, t) in enumerate(cur.fetchall(), 1):
๐Ÿ” Loop LOOP over cur.fetchall() with position: in each round i, (r, n, t) get (position, item)
91
print(f"  Rank {i}: {n:<15} (Roll {r})  Total {t}/500  {t / 5:.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Rank {i}: {n:<15} (Roll {r}) Total {t}/500โ€ฆ with the values filled into { } on the screen
result() - lines 94โ€“104
LineCodeWhat it does
94
def result():
๐Ÿงฉ Function DEFINES a function result(). Python only remembers it here - its body runs later, each time result() is called.
95
cur.execute(f"SELECT COUNT(*), AVG({TOTAL}) / 5, MAX({TOTAL}), MIN({TOTAL}) FROM student")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
96
n, avg, mx, mn = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables n, avg, mx, mn
97
cur.execute("SELECT COUNT(*) FROM student WHERE LEAST(eng, maths, phy, chem, cs) >= 33")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
98
passed = cur.fetchone()[0]
๐Ÿฌ Database Stores the item cur.fetchone()[0] in variable passed
99
print(f"Students: {n} | Class average: {float(avg):.2f}% | Highest: {mx} | Lowest: {mn}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Students: {n} | Class average: {float(avg):โ€ฆ with the values filled into { } on the screen
100
print(f"Passed in all subjects: {passed}/{n}  -> Pass percentage {passed * 100 / n:.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Passed in all subjects: {passed}/{n} -> Pasโ€ฆ with the values filled into { } on the screen
101
for s in SUBJ:
๐Ÿ” Loop LOOP: takes each item of SUBJ one-by-one into s and runs the indented block for it
102
cur.execute(f"SELECT AVG({s}), MAX({s}) FROM student")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
103
a, m = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables a, m
104
print(f"  {s.upper():<6} average {float(a):6.2f}  highest {m}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {s.upper():<6} average {float(a):6.2f} higโ€ฆ with the values filled into { } on the screen
section_analysis() - lines 107โ€“112
LineCodeWhat it does
107
def section_analysis():
๐Ÿงฉ Function DEFINES a function section_analysis(). Python only remembers it here - its body runs later, each time section_analysis() is called.
108
cur.execute(f"""SELECT section, COUNT(*), ROUND(AVG({TOTAL}) / 5, 2) FROM student
                GROUP BY section HAVING AVG({TOTAL}) / 5 > 65""")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
110
print("Sections with average above 65 %:")
๐Ÿ–ฅ๏ธ Output Displays the text "Sections with average above 65 %:" on the screen
111
for s, c, a in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into s, c, a and runs the indented block for it
112
print(f"  Section {s}: {c} students, average {a}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Section {s}: {c} students, average {a}%" with the values filled into { } on the screen
Q1. What does fetchall() return?

A list of tuples - one tuple for every row of the result set.

Q2. Difference between fetchone() and fetchall()?

fetchone() returns the next single row (or None); fetchall() returns all remaining rows.

Q3. What is the use of LIKE '%an%'?

It matches names that contain 'an' anywhere; % means any number of characters.

Q4. Difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after GROUP BY.

Q5. What is IntegrityError?

An error raised when a constraint like PRIMARY KEY is violated, e.g. inserting a duplicate roll number.

07

Employee Payroll System (Binary File)

PYTHONBinary file handling (pickle)seek/telltemporary-file updateos.replacefunctions
๐Ÿ“ 158 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 135 output lines๐Ÿ“„ 25+ page report

Stores employees in a binary file; add, display, search, modify basic pay, delete and print a formatted salary slip with DA, HRA, PF and net pay.

โœจ Features
  • Employee records (dictionary) stored in a binary file employee.dat with pickle
  • Salary slip: Basic + DA 46 % + HRA (X/Y/Z city 24/16/8 %) - PF 12 % - Professional tax
  • Annual income tax estimate using new-regime slabs (simplified)
  • Search by code / department, increment (update) using seek() and tell() in place
  • Delete through a temporary file and os.replace()
  • Department-wise payroll report and highest-paid employee
โ˜ฐ Main menu
1Add Employeepickle.dump() in append mode
2Display AllGross and net pay table
3Salary SlipDetailed payslip of one employee
4Search by DeptLists employees of a department
5Give IncrementUpdates basic in place with seek()/tell()
6Delete EmployeeTemp file + os.replace()
7Payroll ReportDepartment totals and highest paid
8Tax EstimateAnnual tax using slabs
0ExitCloses the program
๐ŸŽฏ Objectives
  • Use pickle for binary file handling
  • Update records with a temporary file and os.replace()
  • Compute salary components in a program
๐Ÿ“š Data dictionary
NameTypePurpose
employee.datbinary filePickled dict: code, name, dept, desig, basic, city
HRAdictCity class -> HRA percent
DA, PFfloat0.46 and 0.12 of basic
posintFile position from tell() before reading a record
temp.datbinary fileUsed while deleting
Why it matters: Demonstrates all binary-file operations required by CBSE (append, read, search, update, delete) in one project.
# =====================================================================
#   EMPLOYEE PAYROLL SYSTEM  (Binary file)
#   Concepts : pickle, rb+ mode, seek() / tell(), temporary file,
#              os.replace(), dictionary, lambda, functions
# =====================================================================
import pickle, os

FILE = "employee.dat"
HRA = {"X": 0.24, "Y": 0.16, "Z": 0.08}
DA, PF, PTAX = 0.46, 0.12, 200


def records():
    out = []
    if os.path.exists(FILE):
        with open(FILE, "rb") as f:
            try:
                while True:
                    out.append(pickle.load(f))
            except EOFError:
                pass
    return out


def pay(e):
    """Returns dict of salary components."""
    b = e["basic"]
    s = {"Basic": b, "DA (46%)": b * DA, f"HRA ({int(HRA[e['city']] * 100)}%)": b * HRA[e["city"]]}
    gross = sum(s.values())
    s["Gross"], s["PF (12%)"], s["Prof. Tax"] = gross, b * PF, PTAX
    s["Net Pay"] = gross - b * PF - PTAX
    return s


def add():
    code = input("Emp code   : ").strip().upper()
    if any(e["code"] == code for e in records()):
        print("Employee code already exists.")
        return
    e = {"code": code, "name": input("Name       : ").strip().title(), "dept": input("Department : ").strip().upper(),
         "desig": input("Designation: ").strip().title(), "basic": float(input("Basic pay  : ")),
         "city": input("City class X/Y/Z: ").strip().upper()}
    with open(FILE, "ab") as f:
        pickle.dump(e, f)
    print("Employee saved.")


def display():
    print(f"{'Code':<5}{'Name':<14}{'Dept':<9}{'Designation':<12}{'Basic':>9}{'Gross':>10}{'Net':>10}")
    print("-" * 69)
    for e in records():
        p = pay(e)
        print(f"{e['code']:<5}{e['name']:<14}{e['dept']:<9}{e['desig']:<12}{e['basic']:>9.0f}{p['Gross']:>10.0f}{p['Net Pay']:>10.0f}")


def slip():
    code = input("Emp code: ").strip().upper()
    for e in records():
        if e["code"] == code:
            print("=" * 38)
            print("SALARY SLIP - JULY 2026".center(38))
            print(f"{e['name']} ({e['code']}) - {e['desig']}, {e['dept']}")
            print("-" * 38)
            for k, v in pay(e).items():
                print(f"{k:<20}Rs. {v:>11,.2f}")
            print("=" * 38)
            return
    print("Not found.")


def search_dept():
    d = input("Department: ").strip().upper()
    for e in records():
        if e["dept"] == d:
            print(f"  {e['code']} {e['name']:<14} {e['desig']:<12} Net Rs. {pay(e)['Net Pay']:,.0f}")


def increment():
    """In-place update using seek() and tell()."""
    code = input("Emp code: ").strip().upper()
    pct = float(input("Increment %: "))
    with open(FILE, "rb+") as f:
        try:
            while True:
                pos = f.tell()
                e = pickle.load(f)
                if e["code"] == code:
                    old = e["basic"]
                    e["basic"] = round(old * (1 + pct / 100), 0)
                    rest = f.read()                 # records after this one
                    f.seek(pos)
                    pickle.dump(e, f)
                    f.write(rest)
                    f.truncate()
                    print(f"Basic of {e['name']} raised from {old:.0f} to {e['basic']:.0f} (record at byte {pos})")
                    return
        except EOFError:
            print("Not found.")


def delete():
    code = input("Emp code to delete: ").strip().upper()
    found = False
    with open(FILE, "rb") as f, open("temp.dat", "wb") as t:
        try:
            while True:
                e = pickle.load(f)
                if e["code"] == code:
                    found = True
                else:
                    pickle.dump(e, t)
        except EOFError:
            pass
    os.replace("temp.dat", FILE)
    print("Deleted." if found else "Not found.")


def report():
    emps, dept = records(), {}
    for e in emps:
        dept.setdefault(e["dept"], []).append(pay(e)["Net Pay"])
    print(f"{'Department':<12}{'Staff':>6}{'Total Net':>14}{'Average':>12}")
    for d, v in sorted(dept.items()):
        print(f"{d:<12}{len(v):>6}{sum(v):>14,.0f}{sum(v) / len(v):>12,.0f}")
    top = max(emps, key=lambda e: pay(e)["Net Pay"])
    print(f"Monthly payroll: Rs. {sum(pay(e)['Net Pay'] for e in emps):,.0f} | Highest paid: {top['name']}")


def tax():
    """Simplified new-regime annual tax with standard deduction."""
    code = input("Emp code: ").strip().upper()
    e = [x for x in records() if x["code"] == code][0]
    income = pay(e)["Gross"] * 12 - 75000
    slabs = [(400000, 0), (800000, .05), (1200000, .10), (1600000, .15), (2000000, .20), (2400000, .25), (float("inf"), .30)]
    t, low = 0, 0
    for up, r in slabs:
        if income > low:
            t += (min(income, up) - low) * r
        low = up
    if income <= 1200000:
        t = 0                                    # rebate u/s 87A
    print(f"Taxable income Rs. {income:,.0f} -> Tax Rs. {t:,.0f} + 4% cess = Rs. {t * 1.04:,.0f} per year")


if os.path.exists(FILE):
    os.remove(FILE)
menu = {"1": add, "2": display, "3": slip, "4": search_dept, "5": increment, "6": delete, "7": report, "8": tax}
print("=" * 69)
print("EMPLOYEE PAYROLL SYSTEM  (Binary File)".center(69))
print("=" * 69)
while True:
    print("\n1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Payroll closed.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Increment? → No: run selected option
  4. Open employee.dat in rb+ mode
  5. pos = f.tell(); rec = pickle.load(f)
  6. rec code matches? → No: read next record
  7. f.seek(pos); pickle.dump(updated rec)
  8. Show new salary
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Add E01 basic 45000 city XSavedPASS
2Duplicate E01RefusedPASS
3Salary slip E01DA, HRA, PF and net shownPASS
4Search dept 'IT'IT employees listedPASS
5Increment 10 % to E02Basic updated in placePASS
6Delete E04Record removedPASS
7Delete E99'Not found'PASS
8Payroll reportDept totalsPASS
9Tax estimate E01Tax as per slabsPASS
โš  Limitations
  • seek() update works because the pickled size stays same only for numbers of same length - so a full rewrite is used as fallback
  • Simplified tax rules
  • No attendance / leave
  • Single user
๐Ÿš€ Future scope
  • Attendance-based salary
  • Payslip PDF and e-mail
  • MySQL backend
  • Form 16 generation

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): pickle - writing / reading Python objects in binary files, os - file and folder operations are loaded.
  2. Global variables / constants are created: FILE, HRA.
  3. 10 functions are defined (lines 13โ€“142) - Python stores them but does NOT run them yet.
  4. Main program starts at line 10: DA, PF, PTAX = 0.46, 0.12, 200 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
records()13โ€“22Recordsadd(), display(), slip(), search_dept()
pay(e)25โ€“32Returns dict of salary components.display(), slip(), search_dept(), report()
add()35โ€“45Addmain program (menu)
display()48โ€“53Displaymain program (menu)
slip()56โ€“68Slipmain program (menu)
search_dept()71โ€“75Search deptmain program (menu)
increment()78โ€“98In-place update using seek() and tell().main program (menu)
delete()101โ€“115Deletemain program (menu)
report()118โ€“126Reportmain program (menu)
tax()129โ€“142Simplified new-regime annual tax with standard deduction.main program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
10
DA, PF, PTAX = 0.46, 0.12, 200
๐Ÿงฎ Store / Calculate Stores 0.46, 0.12, 200 into DA, PF, PTAX respectively
145
if os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
146
os.remove(FILE)
๐Ÿ“ File Deletes the file FILE
147
menu = {"1": add, "2": display, "3": slip, "4": search_dept, "5": increment, "6": delete, "7": report, "8": tax}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": add, "2": display, "3": slip, "4": searโ€ฆ in variable menu
148
print("=" * 69)
๐Ÿ–ฅ๏ธ Output Displays a line of 69 "=" signs on the screen
149
print("EMPLOYEE PAYROLL SYSTEM  (Binary File)".center(69))
๐Ÿ–ฅ๏ธ Output Displays the value of "EMPLOYEE PAYROLL SYSTEM (Binary File)".centeโ€ฆ on the screen
150
print("=" * 69)
๐Ÿ–ฅ๏ธ Output Displays a line of 69 "=" signs on the screen
151
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
152
print("\n1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Display 3.Salary Slip 4.Sโ€ฆ" on the screen
153
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
154
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
155
print("Payroll closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Payroll closed." on the screen
156
break
๐Ÿ” Loop BREAK - leaves the loop immediately
157
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: EMPLOYEE PAYROLL SYSTEM (Binary File) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add()
  3. You type E01 at Emp code :
    runs: records()
  4. You type Sanjay Verma at Name :
  5. You type IT at Department :
  6. You type Manager at Designation:
  7. You type 65000 at Basic pay :
  8. You type X at City class X/Y/Z:
    shows: Employee saved. (+1 more lines)
  9. You type 1 at Enter choice:
    runs: add()
  10. You type E02 at Emp code :
    runs: records()
  11. You type Pooja Rani at Name :
  12. You type Accounts at Department :
  13. You type Accountant at Designation:
  14. You type 42000 at Basic pay :
  15. You type Y at City class X/Y/Z:
    shows: Employee saved. (+1 more lines)
  16. You type 1 at Enter choice:
    runs: add()
  17. You type E03 at Emp code :
    runs: records()
  18. You type Imran Ali at Name :
  19. You type IT at Department :
  20. You type Developer at Designation:
  21. You type 52000 at Basic pay :
  22. You type X at City class X/Y/Z:
    shows: Employee saved. (+1 more lines)
  23. You type 1 at Enter choice:
    runs: add()
  24. You type E04 at Emp code :
    runs: records()
  25. You type Kiran Bala at Name :
  26. You type HR at Department :
  27. You type Executive at Designation:
  28. You type 35000 at Basic pay :
  29. You type Z at City class X/Y/Z:
    shows: Employee saved. (+1 more lines)
  30. You type 1 at Enter choice:
    runs: add()
  31. You type E01 at Emp code :
    runs: records()
    shows: Employee code already exists. (+1 more lines)
  32. You type 2 at Enter choice:
    runs: display() โ†’ records() โ†’ pay() ร—4
    shows: Code Name Dept Designation Basic Gross Net (+5 more lines)
  33. You type 3 at Enter choice:
    runs: slip()
  34. You type E01 at Emp code:
    runs: records() โ†’ pay()
    shows: SALARY SLIP - JULY 2026 (+9 more lines)
  35. You type 4 at Enter choice:
    runs: search_dept()
  36. You type it at Department:
    runs: records() โ†’ pay() ร—2
    shows: E01 Sanjay Verma Manager Net Rs. 102,500 (+2 more lines)
  37. You type 5 at Enter choice:
    runs: increment()
  38. You type E02 at Emp code:
  39. You type 10 at Increment %:
    shows: Basic of Pooja Rani raised from 42000 to 46200 (record at byte 109) (+1 more lines)
  40. You type 3 at Enter choice:
    runs: slip()

โ€ฆ and 10 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
records() - lines 13โ€“22
LineCodeWhat it does
13
def records():
๐Ÿงฉ Function DEFINES a function records(). Python only remembers it here - its body runs later, each time records() is called.
14
out = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable out
15
if os.path.exists(FILE):
๐Ÿ”€ Decision CHECKS whether os.path.exists(FILE) is True. If True, the indented lines below run; otherwise they are skipped
16
with open(FILE, "rb") as f:
๐Ÿ“ File Opens the file FILE in "rb" mode - read in binary and calls it f. "with" closes the file automatically when the block ends
17
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
18
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
19
out.append(pickle.load(f))
๐Ÿ“ File Adds pickle.load(f) at the end of list out
20
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
21
pass
๐Ÿงฎ Store / Calculate Does nothing (empty placeholder)
22
return out
๐Ÿงฉ Function Sends back (returns) the value of out to the line that called the function
pay() - lines 25โ€“32
LineCodeWhat it does
25
def pay(e):
๐Ÿงฉ Function DEFINES a function pay(e). Python only remembers it here - its body runs later, each time pay() is called.
27
b = e["basic"]
๐Ÿงฎ Store / Calculate Stores the item e["basic"] in variable b
28
s = {"Basic": b, "DA (46%)": b * DA, f"HRA ({int(HRA[e['city']] * 100)}%)": b * HRA[e["city"]]}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Basic": b, "DA (46%)": b * DA, f"HRA ({int(โ€ฆ in variable s
29
gross = sum(s.values())
๐Ÿงฎ Store / Calculate Adds up all the values in s.values(); the result is stored in variable gross
30
s["Gross"], s["PF (12%)"], s["Prof. Tax"] = gross, b * PF, PTAX
๐Ÿงฎ Store / Calculate Stores the tuple gross, b * PF, PTAX in variables s["Gross"], s["PF (12%)"], s["Prof. Tax"]
31
s["Net Pay"] = gross - b * PF - PTAX
๐Ÿงฎ Store / Calculate Puts the value of gross - b * PF - PTAX (calculated using -) into s["Net Pay"] (item "Net Pay" of s)
32
return s
๐Ÿงฉ Function Sends back (returns) the value of s to the line that called the function
add() - lines 35โ€“45
LineCodeWhat it does
35
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
36
code = input("Emp code   : ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
37
if any(e["code"] == code for e in records()):
๐Ÿ”€ Decision CHECKS whether any(e["code"] == code for e in records()) is True. If True, the indented lines below run; otherwise they are skipped
38
print("Employee code already exists.")
๐Ÿ–ฅ๏ธ Output Displays the text "Employee code already exists." on the screen
39
return
๐Ÿงฉ Function Ends the function and goes back to the caller
40
e = {"code": code, "name": input("Name       : ").strip().title(), "dept": input("Department : ").strip().upper(),
     "desig": input("Designation: ").stripโ€ฆ
โŒจ๏ธ Input Stores a dictionary {"code": code, "name": input("Name : ").stripโ€ฆ in variable e
43
with open(FILE, "ab") as f:
๐Ÿ“ File Opens the file FILE in "ab" mode - append in binary and calls it f. "with" closes the file automatically when the block ends
44
pickle.dump(e, f)
๐Ÿ“ File Writes (pickles) e into the binary file f
45
print("Employee saved.")
๐Ÿ–ฅ๏ธ Output Displays the text "Employee saved." on the screen
display() - lines 48โ€“53
LineCodeWhat it does
48
def display():
๐Ÿงฉ Function DEFINES a function display(). Python only remembers it here - its body runs later, each time display() is called.
49
print(f"{'Code':<5}{'Name':<14}{'Dept':<9}{'Designation':<12}{'Basic':>9}{'Gross':>10}{'Net':>10}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Code':<5}{'Name':<14}{'Dept':<9}{'Designaโ€ฆ with the values filled into { } on the screen
50
print("-" * 69)
๐Ÿ–ฅ๏ธ Output Displays a line of 69 "-" signs on the screen
51
for e in records():
๐Ÿ” Loop LOOP: takes each item of records() one-by-one into e and runs the indented block for it
52
p = pay(e)
๐Ÿงฎ Store / Calculate Calls our own function pay(e) - returns dict of salary components; the result is stored in variable p
53
print(f"{e['code']:<5}{e['name']:<14}{e['dept']:<9}{e['desig']:<12}{e['basic']:>9.0f}{p['Gross']:>10.0f}{p['Net Pay']:>10.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{e['code']:<5}{e['name']:<14}{e['dept']:<9}โ€ฆ with the values filled into { } on the screen
slip() - lines 56โ€“68
LineCodeWhat it does
56
def slip():
๐Ÿงฉ Function DEFINES a function slip(). Python only remembers it here - its body runs later, each time slip() is called.
57
code = input("Emp code: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
58
for e in records():
๐Ÿ” Loop LOOP: takes each item of records() one-by-one into e and runs the indented block for it
59
if e["code"] == code:
๐Ÿ”€ Decision CHECKS whether e["code"] is equal to code. If True, the indented lines below run; otherwise they are skipped
60
print("=" * 38)
๐Ÿ–ฅ๏ธ Output Displays a line of 38 "=" signs on the screen
61
print("SALARY SLIP - JULY 2026".center(38))
๐Ÿ–ฅ๏ธ Output Displays the value of "SALARY SLIP - JULY 2026".center(38) on the screen
62
print(f"{e['name']} ({e['code']}) - {e['desig']}, {e['dept']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{e['name']} ({e['code']}) - {e['desig']}, {โ€ฆ with the values filled into { } on the screen
63
print("-" * 38)
๐Ÿ–ฅ๏ธ Output Displays a line of 38 "-" signs on the screen
64
for k, v in pay(e).items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary pay(e); k, v get one pair each round
65
print(f"{k:<20}Rs. {v:>11,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{k:<20}Rs. {v:>11,.2f}" with the values filled into { } on the screen
66
print("=" * 38)
๐Ÿ–ฅ๏ธ Output Displays a line of 38 "=" signs on the screen
67
return
๐Ÿงฉ Function Ends the function and goes back to the caller
68
print("Not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Not found." on the screen
search_dept() - lines 71โ€“75
LineCodeWhat it does
71
def search_dept():
๐Ÿงฉ Function DEFINES a function search_dept(). Python only remembers it here - its body runs later, each time search_dept() is called.
72
d = input("Department: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable d
73
for e in records():
๐Ÿ” Loop LOOP: takes each item of records() one-by-one into e and runs the indented block for it
74
if e["dept"] == d:
๐Ÿ”€ Decision CHECKS whether e["dept"] is equal to d. If True, the indented lines below run; otherwise they are skipped
75
print(f"  {e['code']} {e['name']:<14} {e['desig']:<12} Net Rs. {pay(e)['Net Pay']:,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {e['code']} {e['name']:<14} {e['desig']:<1โ€ฆ with the values filled into { } on the screen
increment() - lines 78โ€“98
LineCodeWhat it does
78
def increment():
๐Ÿงฉ Function DEFINES a function increment(). Python only remembers it here - its body runs later, each time increment() is called.
80
code = input("Emp code: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
81
pct = float(input("Increment %: "))
โŒจ๏ธ Input Shows "Increment %: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable pct
82
with open(FILE, "rb+") as f:
๐Ÿ“ File Opens the file FILE in "rb+" mode - read & write in binary and calls it f. "with" closes the file automatically when the block ends
83
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
84
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
85
pos = f.tell()
๐Ÿ“ File Tells the current byte position of the file pointer in f; the result is stored in variable pos
86
e = pickle.load(f)
๐Ÿ“ File Reads (un-pickles) the next object from the binary file f; the result is stored in variable e
87
if e["code"] == code:
๐Ÿ”€ Decision CHECKS whether e["code"] is equal to code. If True, the indented lines below run; otherwise they are skipped
88
old = e["basic"]
๐Ÿงฎ Store / Calculate Stores the item e["basic"] in variable old
89
e["basic"] = round(old * (1 + pct / 100), 0)
๐Ÿงฎ Store / Calculate Rounds old * (1 + pct / 100) to 0 decimal places; the result is put into e["basic"] (item "basic" of e)
90
rest = f.read()                 # records after this one
๐Ÿ“ File Reads the whole content of file f as one string; the result is stored in variable rest
91
f.seek(pos)
๐Ÿ“ File Moves the file pointer of f to byte pos
92
pickle.dump(e, f)
๐Ÿ“ File Writes (pickles) e into the binary file f
93
f.write(rest)
๐Ÿ“ File Writes rest into file f
94
f.truncate()
๐Ÿงฎ Store / Calculate Cuts the file f at the current position
95
print(f"Basic of {e['name']} raised from {old:.0f} to {e['basic']:.0f} (record at byte {pos})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Basic of {e['name']} raised from {old:.0f} โ€ฆ with the values filled into { } on the screen
96
return
๐Ÿงฉ Function Ends the function and goes back to the caller
97
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
98
print("Not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Not found." on the screen
delete() - lines 101โ€“115
LineCodeWhat it does
101
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
102
code = input("Emp code to delete: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
103
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
104
with open(FILE, "rb") as f, open("temp.dat", "wb") as t:
๐Ÿ“ File Opens the file FILE in "rb" mode - read in binary and calls it f. "with" closes the file automatically when the block ends
105
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
106
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
107
e = pickle.load(f)
๐Ÿ“ File Reads (un-pickles) the next object from the binary file f; the result is stored in variable e
108
if e["code"] == code:
๐Ÿ”€ Decision CHECKS whether e["code"] is equal to code. If True, the indented lines below run; otherwise Python jumps to the elif/else part
109
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
110
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
111
pickle.dump(e, t)
๐Ÿ“ File Writes (pickles) e into the binary file t
112
except EOFError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if EOFError occurs - the end of the file is reached (no more data)
113
pass
๐Ÿงฎ Store / Calculate Does nothing (empty placeholder)
114
os.replace("temp.dat", FILE)
๐Ÿ“ File Replaces "temp.dat" with FILE in os
115
print("Deleted." if found else "Not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of "Deleted." if found else "Not found." on the screen
report() - lines 118โ€“126
LineCodeWhat it does
118
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
119
emps, dept = records(), {}
๐Ÿงฎ Store / Calculate Stores records(), {} into emps, dept respectively
120
for e in emps:
๐Ÿ” Loop LOOP: takes each item of emps one-by-one into e and runs the indented block for it
121
dept.setdefault(e["dept"], []).append(pay(e)["Net Pay"])
๐Ÿงฎ Store / Calculate Adds pay(e)["Net Pay"] at the end of list dept.setdefault(e["dept"], [])
122
print(f"{'Department':<12}{'Staff':>6}{'Total Net':>14}{'Average':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Department':<12}{'Staff':>6}{'Total Net':โ€ฆ with the values filled into { } on the screen
123
for d, v in sorted(dept.items()):
๐Ÿ” Loop LOOP: takes each item of sorted(dept.items()) one-by-one into d, v and runs the indented block for it
124
print(f"{d:<12}{len(v):>6}{sum(v):>14,.0f}{sum(v) / len(v):>12,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{d:<12}{len(v):>6}{sum(v):>14,.0f}{sum(v) /โ€ฆ with the values filled into { } on the screen
125
top = max(emps, key=lambda e: pay(e)["Net Pay"])
๐Ÿงฎ Store / Calculate Finds the largest value among emps; the result is stored in variable top
126
print(f"Monthly payroll: Rs. {sum(pay(e)['Net Pay'] for e in emps):,.0f} | Highest paid: {top['name']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Monthly payroll: Rs. {sum(pay(e)['Net Pay']โ€ฆ with the values filled into { } on the screen
tax() - lines 129โ€“142
LineCodeWhat it does
129
def tax():
๐Ÿงฉ Function DEFINES a function tax(). Python only remembers it here - its body runs later, each time tax() is called.
131
code = input("Emp code: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable code
132
e = [x for x in records() if x["code"] == code][0]
๐Ÿงฎ Store / Calculate Stores the item [x for x in records() if x["code"] == code][0] in variable e
133
income = pay(e)["Gross"] * 12 - 75000
๐Ÿงฎ Store / Calculate Stores the value of pay(e)["Gross"] * 12 - 75000 (calculated using -) in variable income
134
slabs = [(400000, 0), (800000, .05), (1200000, .10), (1600000, .15), (2000000, .20), (2400000, .25), (float("inf"), .30)]
๐Ÿงฎ Store / Calculate Stores a list [(400000, 0), (800000, .05), (1200000, .10), โ€ฆ in variable slabs
135
t, low = 0, 0
๐Ÿงฎ Store / Calculate Stores 0, 0 into t, low respectively
136
for up, r in slabs:
๐Ÿ” Loop LOOP: takes each item of slabs one-by-one into up, r and runs the indented block for it
137
if income > low:
๐Ÿ”€ Decision CHECKS whether income is greater than low. If True, the indented lines below run; otherwise they are skipped
138
t += (min(income, up) - low) * r
๐Ÿงฎ Store / Calculate Adds (min(income, up) - low) * r to t (same as t = t + (min(income, up) - low) โ€ฆ)
139
low = up
๐Ÿงฎ Store / Calculate Stores the value of up in variable low
140
if income <= 1200000:
๐Ÿ”€ Decision CHECKS whether income is less than or equal to 1200000. If True, the indented lines below run; otherwise they are skipped
141
t = 0                                    # rebate u/s 87A
๐Ÿงฎ Store / Calculate Stores the number 0 in variable t
142
print(f"Taxable income Rs. {income:,.0f} -> Tax Rs. {t:,.0f} + 4% cess = Rs. {t * 1.04:,.0f} per year")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Taxable income Rs. {income:,.0f} -> Tax Rs.โ€ฆ with the values filled into { } on the screen
Q1. What do seek() and tell() do?

tell() returns the current byte position of the file pointer; seek(pos) moves the pointer to that byte position.

Q2. Which mode allows reading and writing a binary file?

'rb+' opens an existing binary file for both reading and writing without truncating it.

Q3. Why is os.replace() used?

It renames temp.dat to employee.dat, replacing the old file in one step after deletion.

Q4. What is DA and HRA?

Dearness Allowance (to offset inflation) and House Rent Allowance (depends on city class X / Y / Z).

Q5. How is the highest paid employee found?

max(records, key=lambda e: net(e)) returns the record with the largest net pay.

08

Railway Reservation System (Python + MySQL)

PYTHON + MySQLTwo related MySQL tablesINSERT/UPDATE/DELETEtransactions with commitlastrowidconditional seat logic
๐Ÿ“ 131 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 120 output lines๐Ÿ“„ 25+ page report

Shows available trains, books tickets only when seats exist, generates a PNR, cancels tickets (restoring seats) and displays a booking by PNR.

โœจ Features
  • Two related tables: train (seats per class) and booking (PNR, passenger, class, status)
  • Booking with fare calculation by class (SL / 3A / 2A) and concession for senior citizens (40 %) and children (50 %)
  • Automatic waiting list when seats are full (WL1, WL2 ...)
  • Cancellation with refund (deduction Rs. 60 / 120 / 200) and automatic confirmation of the first waiting passenger
  • PNR enquiry using JOIN; chart preparation sorted by status
  • Revenue report per train using GROUP BY
โ˜ฐ Main menu
1Show TrainsSELECT from train
2Book TicketINSERT booking, reduce seats or put on WL
3PNR StatusJOIN of booking and train
4Cancel TicketRefund + promote waiting list
5Reservation ChartAll passengers of a train
6Revenue ReportGROUP BY train
0ExitCloses connection
๐ŸŽฏ Objectives
  • Design two related tables and join them
  • Update seat availability atomically with commit()
  • Use lastrowid to obtain the generated PNR
๐Ÿ“š Data dictionary
NameTypePurpose
trainMySQL tabletno PK, name, source, dest, sl, ac3, ac2 (available seats)
bookingMySQL tablepnr PK AUTO_INCREMENT (from 4501), tno FK, name, age, cls, fare, status
FAREdictClass -> base fare per train
lastrowidintGenerated PNR
Why it matters: Two linked tables and seat-count logic make this a realistic, high-scoring board project.
# =====================================================================
#   RAILWAY RESERVATION SYSTEM  (Python + MySQL)
#   Concepts : two related tables (FOREIGN KEY), INSERT / UPDATE /
#              DELETE, JOIN, GROUP BY, lastrowid, commit
# =====================================================================
import mysql.connector

FARE = {"SL": 545, "3A": 1430, "2A": 2040}
COL = {"SL": "sl", "3A": "ac3", "2A": "ac2"}
CANCEL = {"SL": 60, "3A": 120, "2A": 200}
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS railway_db")
cur.execute("USE railway_db")
cur.execute("""CREATE TABLE IF NOT EXISTS train (tno INT PRIMARY KEY, name VARCHAR(30), source VARCHAR(15),
               dest VARCHAR(15), sl INT, ac3 INT, ac2 INT)""")
cur.execute("""CREATE TABLE IF NOT EXISTS booking (pnr INT PRIMARY KEY AUTO_INCREMENT, tno INT, name VARCHAR(25),
               age INT, cls CHAR(2), fare DECIMAL(8,2), status VARCHAR(6),
               FOREIGN KEY (tno) REFERENCES train(tno)) AUTO_INCREMENT = 4501""")
cur.execute("SELECT COUNT(*) FROM train")
if cur.fetchone()[0] == 0:
    cur.executemany("INSERT INTO train VALUES (%s,%s,%s,%s,%s,%s,%s)",
                    [(12425, "Rajdhani Express", "New Delhi", "Jammu Tawi", 3, 2, 2),
                     (12951, "Mumbai Rajdhani", "Mumbai", "New Delhi", 5, 4, 2),
                     (12301, "Howrah Rajdhani", "Howrah", "New Delhi", 4, 3, 1)])
    conn.commit()


def trains():
    cur.execute("SELECT * FROM train")
    print(f"{'No':<7}{'Train':<19}{'From':<11}{'To':<12}{'SL':>3}{'3A':>4}{'2A':>4}")
    for t in cur.fetchall():
        print(f"{t[0]:<7}{t[1]:<19}{t[2]:<11}{t[3]:<12}{t[4]:>3}{t[5]:>4}{t[6]:>4}")


def concession(age):
    return 0.5 if age < 12 else 0.6 if age >= 60 else 1.0


def book():
    tno = int(input("Train no : "))
    name = input("Passenger name: ").strip().title()
    age = int(input("Age      : "))
    cls = input("Class SL/3A/2A: ").strip().upper()
    cur.execute(f"SELECT name, {COL.get(cls, 'sl')} FROM train WHERE tno = %s", (tno,))
    t = cur.fetchone()
    if not t or cls not in FARE:
        print("Train not found / invalid class.")
        return
    if t[1] > 0:
        status = "CNF"
        cur.execute(f"UPDATE train SET {COL[cls]} = {COL[cls]} - 1 WHERE tno = %s", (tno,))
    else:
        cur.execute("SELECT COUNT(*) FROM booking WHERE tno = %s AND cls = %s AND status LIKE 'WL%'", (tno, cls))
        status = "WL" + str(cur.fetchone()[0] + 1)
    fare = FARE[cls] * concession(age)
    cur.execute("INSERT INTO booking (tno, name, age, cls, fare, status) VALUES (%s,%s,%s,%s,%s,%s)",
                (tno, name, age, cls, fare, status))
    conn.commit()
    print("-" * 44)
    print(f"PNR {cur.lastrowid} | {t[0]} ({tno})")
    print(f"{name}, {age} yrs | Class {cls} | Fare Rs. {fare:.2f} | {status}")
    print("-" * 44)


def pnr_status(pnr=None):
    pnr = pnr or int(input("PNR: "))
    cur.execute("""SELECT b.pnr, b.name, b.age, b.cls, b.fare, b.status, t.name, t.source, t.dest
                   FROM booking b JOIN train t ON b.tno = t.tno WHERE b.pnr = %s""", (pnr,))
    r = cur.fetchone()
    if r:
        print(f"PNR {r[0]}: {r[1]} ({r[2]}) | {r[6]} {r[7]} -> {r[8]} | {r[3]} | Rs. {float(r[4]):.2f} | Status: {r[5]}")
    else:
        print("Invalid PNR.")


def cancel():
    pnr = int(input("PNR to cancel: "))
    cur.execute("SELECT tno, cls, fare, status, name FROM booking WHERE pnr = %s", (pnr,))
    r = cur.fetchone()
    if not r:
        print("Invalid PNR.")
        return
    tno, cls, fare, status, name = r
    refund = max(0, float(fare) - CANCEL[cls])
    cur.execute("DELETE FROM booking WHERE pnr = %s", (pnr,))
    print(f"Ticket of {name} cancelled. Refund Rs. {refund:.2f} (deduction Rs. {CANCEL[cls]})")
    if status == "CNF":
        cur.execute("SELECT pnr, name FROM booking WHERE tno = %s AND cls = %s AND status LIKE 'WL%%' ORDER BY pnr LIMIT 1", (tno, cls))
        w = cur.fetchone()
        if w:
            cur.execute("UPDATE booking SET status = 'CNF' WHERE pnr = %s", (w[0],))
            cur.execute("UPDATE booking SET status = CONCAT('WL', CAST(SUBSTRING(status, 3) AS UNSIGNED) - 1) "
                        "WHERE tno = %s AND cls = %s AND status LIKE 'WL%%'", (tno, cls))
            print(f"Waiting passenger {w[1]} (PNR {w[0]}) is now CONFIRMED.")
        else:
            cur.execute(f"UPDATE train SET {COL[cls]} = {COL[cls]} + 1 WHERE tno = %s", (tno,))
    conn.commit()


def chart():
    tno = int(input("Train no: "))
    cur.execute("SELECT pnr, name, age, cls, status FROM booking WHERE tno = %s ORDER BY cls, status, pnr", (tno,))
    print(f"{'PNR':<6}{'Name':<15}{'Age':>4}  {'Cls':<4}Status")
    for r in cur.fetchall():
        print(f"{r[0]:<6}{r[1]:<15}{r[2]:>4}  {r[3]:<4}{r[4]}")


def revenue():
    cur.execute("""SELECT t.name, COUNT(b.pnr), SUM(b.fare) FROM train t LEFT JOIN booking b
                   ON t.tno = b.tno GROUP BY t.name ORDER BY SUM(b.fare) DESC""")
    for n, c, s in cur.fetchall():
        print(f"  {n:<19} tickets {c:>2}   revenue Rs. {float(s or 0):>9.2f}")


menu = {"1": trains, "2": book, "3": pnr_status, "4": cancel, "5": chart, "6": revenue}
print("=" * 62)
print("INDIAN RAILWAYS - RESERVATION SYSTEM (Python + MySQL)".center(62))
print("=" * 62)
while True:
    print("\n1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Happy journey!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Invalid input.")

        
  1. Start
  2. Create railway_db, train and booking tables
  3. Display menu and read choice
  4. Choice is Book? → No: run selected option
  5. Read train, name, age, class
  6. Seats available? → No: status = WL n
  7. Reduce seat, status = CNF
  8. Compute fare with concession, INSERT, COMMIT
  9. Print ticket with PNR
  10. Choice is 0? → No: show menu
  11. Stop
#Test case / inputExpected resultStatus
1Book SL on 12425CNF, seat reducedPASS
2Senior citizen age 6540 % concessionPASS
3Child age 850 % farePASS
4Seats overStatus WL1PASS
5Invalid train 11111'Train not found'PASS
6PNR statusJoined detailsPASS
7Cancel CNF ticketRefund and WL1 confirmedPASS
8Cancel unknown PNR'Invalid PNR'PASS
9ChartSorted passengersPASS
10RevenueTrain-wise totalsPASS
โš  Limitations
  • Seat numbers are not allotted
  • Single journey (no intermediate stations)
  • No date of journey
  • No payment gateway
๐Ÿš€ Future scope
  • Journey date and seat map
  • Tatkal quota
  • Online payment (UPI)
  • SMS of PNR status

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): mysql.connector - connecting Python with MySQL are loaded.
  2. Global variables / constants are created: FARE, COL, CANCEL, conn, cur.
  3. 7 functions are defined (lines 29โ€“113) - Python stores them but does NOT run them yet.
  4. Main program starts at line 13: cur.execute("CREATE DATABASE IF NOT EXISTS railway_db") - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
trains()29โ€“33Trainsmain program (menu)
concession(age)36โ€“37Concessionbook()
book()40โ€“63Bookmain program (menu)
pnr_status(pnr)66โ€“74Pnr statusmain program (menu)
cancel()77โ€“98Cancelmain program (menu)
chart()101โ€“106Chartmain program (menu)
revenue()109โ€“113Revenuemain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
13
cur.execute("CREATE DATABASE IF NOT EXISTS railway_db")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
14
cur.execute("USE railway_db")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
15
cur.execute("""CREATE TABLE IF NOT EXISTS train (tno INT PRIMARY KEY, name VARCHAR(30), source VARCHAR(15),
               dest VARCHAR(15), sl INT, ac3 INT,โ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
17
cur.execute("""CREATE TABLE IF NOT EXISTS booking (pnr INT PRIMARY KEY AUTO_INCREMENT, tno INT, name VARCHAR(25),
               age INT, cls CHAR(2), fare Dโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
20
cur.execute("SELECT COUNT(*) FROM train")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
21
if cur.fetchone()[0] == 0:
๐Ÿ”€ Decision CHECKS whether cur.fetchone()[0] is equal to 0. If True, the indented lines below run; otherwise they are skipped
22
cur.executemany("INSERT INTO train VALUES (%s,%s,%s,%s,%s,%s,%s)",
                [(12425, "Rajdhani Express", "New Delhi", "Jammu Tawi", 3, 2, 2),
        โ€ฆ
๐Ÿฌ Database Runs the same SQL for every row of [(12425, "Rajdhani Express", "New Delhi", "Jaโ€ฆ
26
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
116
menu = {"1": trains, "2": book, "3": pnr_status, "4": cancel, "5": chart, "6": revenue}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": trains, "2": book, "3": pnr_status, "4"โ€ฆ in variable menu
117
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
118
print("INDIAN RAILWAYS - RESERVATION SYSTEM (Python + MySQL)".center(62))
๐Ÿ–ฅ๏ธ Output Displays the value of "INDIAN RAILWAYS - RESERVATION SYSTEM (Pythonโ€ฆ on the screen
119
print("=" * 62)
๐Ÿ–ฅ๏ธ Output Displays a line of 62 "=" signs on the screen
120
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
121
print("\n1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Trains 2.Book 3.PNR Status 4.Caโ€ฆ" on the screen
122
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
123
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
124
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
125
print("Happy journey!")
๐Ÿ–ฅ๏ธ Output Displays the text "Happy journey!" on the screen
126
break
๐Ÿ” Loop BREAK - leaves the loop immediately
127
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
128
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
129
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
130
print("Invalid input.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid input." on the screen
โ‘ฃ Inside each function - line by line
trains() - lines 29โ€“33
LineCodeWhat it does
29
def trains():
๐Ÿงฉ Function DEFINES a function trains(). Python only remembers it here - its body runs later, each time trains() is called.
30
cur.execute("SELECT * FROM train")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
31
print(f"{'No':<7}{'Train':<19}{'From':<11}{'To':<12}{'SL':>3}{'3A':>4}{'2A':>4}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'No':<7}{'Train':<19}{'From':<11}{'To':<12โ€ฆ with the values filled into { } on the screen
32
for t in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into t and runs the indented block for it
33
print(f"{t[0]:<7}{t[1]:<19}{t[2]:<11}{t[3]:<12}{t[4]:>3}{t[5]:>4}{t[6]:>4}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{t[0]:<7}{t[1]:<19}{t[2]:<11}{t[3]:<12}{t[4โ€ฆ with the values filled into { } on the screen
concession() - lines 36โ€“37
LineCodeWhat it does
36
def concession(age):
๐Ÿงฉ Function DEFINES a function concession(age). Python only remembers it here - its body runs later, each time concession() is called.
37
return 0.5 if age < 12 else 0.6 if age >= 60 else 1.0
๐Ÿงฉ Function Sends back (returns) either 0.5 or 0.6 if age >= 60 else 1.0 depending on age < 12 to the line that called the function
book() - lines 40โ€“63
LineCodeWhat it does
40
def book():
๐Ÿงฉ Function DEFINES a function book(). Python only remembers it here - its body runs later, each time book() is called.
41
tno = int(input("Train no : "))
โŒจ๏ธ Input Shows "Train no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable tno
42
name = input("Passenger name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
43
age = int(input("Age      : "))
โŒจ๏ธ Input Shows "Age : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable age
44
cls = input("Class SL/3A/2A: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable cls
45
cur.execute(f"SELECT name, {COL.get(cls, 'sl')} FROM train WHERE tno = %s", (tno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (tno,)
46
t = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable t
47
if not t or cls not in FARE:
๐Ÿ”€ Decision CHECKS whether (t is False (or empty / zero) OR cls is not present in FARE). If True, the indented lines below run; otherwise they are skipped
48
print("Train not found / invalid class.")
๐Ÿ–ฅ๏ธ Output Displays the text "Train not found / invalid class." on the screen
49
return
๐Ÿงฉ Function Ends the function and goes back to the caller
50
if t[1] > 0:
๐Ÿ”€ Decision CHECKS whether t[1] is greater than 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
51
status = "CNF"
๐Ÿงฎ Store / Calculate Stores the text "CNF" in variable status
52
cur.execute(f"UPDATE train SET {COL[cls]} = {COL[cls]} - 1 WHERE tno = %s", (tno,))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (tno,)
53
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
54
cur.execute("SELECT COUNT(*) FROM booking WHERE tno = %s AND cls = %s AND status LIKE 'WL%'", (tno, cls))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (tno, cls)
55
status = "WL" + str(cur.fetchone()[0] + 1)
๐Ÿฌ Database Stores the value of "WL" + str(cur.fetchone()[0] + 1) (calculated using +) in variable status
56
fare = FARE[cls] * concession(age)
๐Ÿงฎ Store / Calculate Stores the value of FARE[cls] * concession(age) (calculated using ร—) in variable fare
57
cur.execute("INSERT INTO booking (tno, name, age, cls, fare, status) VALUES (%s,%s,%s,%s,%s,%s)",
            (tno, name, age, cls, fare, status))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (tno, name, age, cls, fare, status)
59
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
60
print("-" * 44)
๐Ÿ–ฅ๏ธ Output Displays a line of 44 "-" signs on the screen
61
print(f"PNR {cur.lastrowid} | {t[0]} ({tno})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"PNR {cur.lastrowid} | {t[0]} ({tno})" with the values filled into { } on the screen
62
print(f"{name}, {age} yrs | Class {cls} | Fare Rs. {fare:.2f} | {status}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name}, {age} yrs | Class {cls} | Fare Rs. โ€ฆ with the values filled into { } on the screen
63
print("-" * 44)
๐Ÿ–ฅ๏ธ Output Displays a line of 44 "-" signs on the screen
pnr_status() - lines 66โ€“74
LineCodeWhat it does
66
def pnr_status(pnr=None):
๐Ÿงฉ Function DEFINES a function pnr_status(pnr). Python only remembers it here - its body runs later, each time pnr_status() is called.
67
pnr = pnr or int(input("PNR: "))
โŒจ๏ธ Input Stores the value of pnr, or int(input("PNR: ")) if the first one is empty / None / 0 in variable pnr
68
cur.execute("""SELECT b.pnr, b.name, b.age, b.cls, b.fare, b.status, t.name, t.source, t.dest
               FROM booking b JOIN train t ON b.tno = t.tno WHEโ€ฆ
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (pnr,)
70
r = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable r
71
if r:
๐Ÿ”€ Decision CHECKS whether r is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
72
print(f"PNR {r[0]}: {r[1]} ({r[2]}) | {r[6]} {r[7]} -> {r[8]} | {r[3]} | Rs. {float(r[4]):.2f} | Status: {r[5]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"PNR {r[0]}: {r[1]} ({r[2]}) | {r[6]} {r[7]}โ€ฆ with the values filled into { } on the screen
73
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
74
print("Invalid PNR.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid PNR." on the screen
cancel() - lines 77โ€“98
LineCodeWhat it does
77
def cancel():
๐Ÿงฉ Function DEFINES a function cancel(). Python only remembers it here - its body runs later, each time cancel() is called.
78
pnr = int(input("PNR to cancel: "))
โŒจ๏ธ Input Shows "PNR to cancel: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable pnr
79
cur.execute("SELECT tno, cls, fare, status, name FROM booking WHERE pnr = %s", (pnr,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (pnr,)
80
r = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable r
81
if not r:
๐Ÿ”€ Decision CHECKS whether r is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
82
print("Invalid PNR.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid PNR." on the screen
83
return
๐Ÿงฉ Function Ends the function and goes back to the caller
84
tno, cls, fare, status, name = r
๐Ÿงฎ Store / Calculate Stores the value of r in variables tno, cls, fare, status, name
85
refund = max(0, float(fare) - CANCEL[cls])
๐Ÿงฎ Store / Calculate Finds the largest value among 0, float(fare) - CANCEL[cls]; the result is stored in variable refund
86
cur.execute("DELETE FROM booking WHERE pnr = %s", (pnr,))
๐Ÿฌ Database Sends a DELETE query (removes rows) to MySQL through the cursor; the %s places are filled safely with the values (pnr,)
87
print(f"Ticket of {name} cancelled. Refund Rs. {refund:.2f} (deduction Rs. {CANCEL[cls]})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Ticket of {name} cancelled. Refund Rs. {refโ€ฆ with the values filled into { } on the screen
88
if status == "CNF":
๐Ÿ”€ Decision CHECKS whether status is equal to "CNF". If True, the indented lines below run; otherwise they are skipped
89
cur.execute("SELECT pnr, name FROM booking WHERE tno = %s AND cls = %s AND status LIKE 'WL%%' ORDER BY pnr LIMIT 1", (tno, cls))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (tno, cls)
90
w = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable w
91
if w:
๐Ÿ”€ Decision CHECKS whether w is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
cur.execute("UPDATE booking SET status = 'CNF' WHERE pnr = %s", (w[0],))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (w[0],)
93
cur.execute("UPDATE booking SET status = CONCAT('WL', CAST(SUBSTRING(status, 3) AS UNSIGNED) - 1) "
            "WHERE tno = %s AND cls = %s AND status LIKE โ€ฆ
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (tno, cls)
95
print(f"Waiting passenger {w[1]} (PNR {w[0]}) is now CONFIRMED.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Waiting passenger {w[1]} (PNR {w[0]}) is noโ€ฆ with the values filled into { } on the screen
96
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
97
cur.execute(f"UPDATE train SET {COL[cls]} = {COL[cls]} + 1 WHERE tno = %s", (tno,))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (tno,)
98
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
chart() - lines 101โ€“106
LineCodeWhat it does
101
def chart():
๐Ÿงฉ Function DEFINES a function chart(). Python only remembers it here - its body runs later, each time chart() is called.
102
tno = int(input("Train no: "))
โŒจ๏ธ Input Shows "Train no: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable tno
103
cur.execute("SELECT pnr, name, age, cls, status FROM booking WHERE tno = %s ORDER BY cls, status, pnr", (tno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (tno,)
104
print(f"{'PNR':<6}{'Name':<15}{'Age':>4}  {'Cls':<4}Status")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'PNR':<6}{'Name':<15}{'Age':>4} {'Cls':<4}โ€ฆ with the values filled into { } on the screen
105
for r in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into r and runs the indented block for it
106
print(f"{r[0]:<6}{r[1]:<15}{r[2]:>4}  {r[3]:<4}{r[4]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r[0]:<6}{r[1]:<15}{r[2]:>4} {r[3]:<4}{r[4]โ€ฆ with the values filled into { } on the screen
revenue() - lines 109โ€“113
LineCodeWhat it does
109
def revenue():
๐Ÿงฉ Function DEFINES a function revenue(). Python only remembers it here - its body runs later, each time revenue() is called.
110
cur.execute("""SELECT t.name, COUNT(b.pnr), SUM(b.fare) FROM train t LEFT JOIN booking b
               ON t.tno = b.tno GROUP BY t.name ORDER BY SUM(b.fare)โ€ฆ
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
112
for n, c, s in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into n, c, s and runs the indented block for it
113
print(f"  {n:<19} tickets {c:>2}   revenue Rs. {float(s or 0):>9.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {n:<19} tickets {c:>2} revenue Rs. {float(โ€ฆ with the values filled into { } on the screen
Q1. What is a foreign key?

A column (booking.tno) that refers to the primary key of another table (train.tno) to keep the tables related.

Q2. Why is JOIN used in PNR status?

To fetch the passenger details from booking along with the train name and route from the train table in one query.

Q3. How is the waiting list maintained?

If seats = 0 the booking is stored with status WL n; on cancellation the oldest WL row is updated to CNF.

Q4. What does AUTO_INCREMENT = 4501 do?

PNR numbers start from 4501 and increase by 1 automatically.

Q5. Why commit after cancellation?

Delete / update of refund and waiting-list confirmation must be saved together permanently.

09

Browser History Manager (Stack)

PYTHONStack using list (push/pop/peek)two-stack Back/Forward logicfunctionsisEmpty check
๐Ÿ“ 133 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 155 output lines๐Ÿ“„ 25+ page report

Simulates the Back and Forward buttons of a web browser using two stacks, with visit, back, forward, current page and full history display.

โœจ Features
  • Two stacks - back_stack and forward_stack - exactly like the Back / Forward buttons of a browser
  • Visit, Back, Forward with overflow / underflow checks (maximum 10 pages)
  • Bookmarks saved permanently in bookmarks.txt (text file)
  • History log saved in history.csv with visit number
  • Most visited sites using a dictionary counter
  • Display the stacks visually (top shown first) and clear history
โ˜ฐ Main menu
1Visit PagePush current page on back stack, clear forward stack
2BackPop from back stack, push current on forward stack
3ForwardPop from forward stack
4Current Page (peek)Shows current page and top of both stacks
5Show StacksDraws both stacks
6Add BookmarkAppends current page to bookmarks.txt
7Show BookmarksReads the text file
8History / Most VisitedReads history.csv and counts visits
9Clear HistoryEmpties both stacks
0ExitCloses the browser
๐ŸŽฏ Objectives
  • Implement the Stack data structure with a list
  • Apply push, pop, peek and isEmpty operations
  • Model a real-life LIFO problem
๐Ÿ“š Data dictionary
NameTypePurpose
back_stacklist (stack)Pages before the current page
forward_stacklist (stack)Pages after the current page (after Back)
currentstrPage on screen
MAXintStack size limit (overflow)
bookmarks.txttext fileOne URL per line
history.csvCSV filevisit_no, url
Why it matters: A direct application of the Stack data structure, a compulsory Class XII topic, in a familiar real-life setting.
# =====================================================================
#   BROWSER HISTORY MANAGER  (Two stacks + text / CSV files)
#   Concepts : stack using list (push, pop, peek, isEmpty, overflow),
#              text file, csv file, dictionary counting, functions
# =====================================================================
import csv, os

MAX = 10
back_stack, forward_stack = [], []
current = "home"
visits = 0


def is_empty(stk):
    return len(stk) == 0


def push(stk, item):
    if len(stk) == MAX:
        print("Overflow! Oldest page removed.")
        stk.pop(0)
    stk.append(item)


def pop(stk):
    return None if is_empty(stk) else stk.pop()


def peek(stk):
    return "-" if is_empty(stk) else stk[-1]


def visit():
    global current, visits
    url = input("Enter URL: ").strip().lower()
    if "." not in url:
        print("Invalid URL.")
        return
    push(back_stack, current)
    forward_stack.clear()                  # new branch of history
    current, visits = url, visits + 1
    with open("history.csv", "a", newline="") as f:
        csv.writer(f).writerow([visits, url])
    print("Now on:", current)


def back():
    global current
    if is_empty(back_stack):
        print("Underflow! No previous page.")
        return
    push(forward_stack, current)
    current = pop(back_stack)
    print("<- Back to:", current)


def forward():
    global current
    if is_empty(forward_stack):
        print("Underflow! No forward page.")
        return
    push(back_stack, current)
    current = pop(forward_stack)
    print("-> Forward to:", current)


def show_current():
    print(f"Current page : {current}")
    print(f"Back top     : {peek(back_stack)}")
    print(f"Forward top  : {peek(forward_stack)}")


def show_stacks():
    h = max(len(back_stack), len(forward_stack), 1)
    print(f"  {'BACK STACK':^22}   {'FORWARD STACK':^22}")
    for i in range(h - 1, -1, -1):
        b = back_stack[i] if i < len(back_stack) else ""
        f = forward_stack[i] if i < len(forward_stack) else ""
        tb = " <-top" if i == len(back_stack) - 1 else ""
        print(f"  |{b:^20}|{tb:<6} |{f:^20}|")
    print("  +" + "-" * 20 + "+       +" + "-" * 20 + "+")
    print("  Current page:", current)


def add_bookmark():
    with open("bookmarks.txt", "a") as f:
        f.write(current + "\n")
    print("Bookmarked:", current)


def show_bookmarks():
    if not os.path.exists("bookmarks.txt"):
        print("No bookmarks.")
        return
    with open("bookmarks.txt") as f:
        for i, line in enumerate(f, 1):
            print(f"  {i}. {line.strip()}")


def history():
    count = {}
    with open("history.csv", newline="") as f:
        rows = list(csv.reader(f))
    for n, url in rows:
        count[url] = count.get(url, 0) + 1
    print("Visit log:", " | ".join(f"{n}:{u}" for n, u in rows))
    print("Most visited:")
    for url, c in sorted(count.items(), key=lambda x: -x[1])[:3]:
        print(f"  {url:<22} {'#' * c} {c}")


def clear():
    back_stack.clear()
    forward_stack.clear()
    print("History cleared. Back and Forward stacks are empty.")


for fn in ("history.csv", "bookmarks.txt"):
    if os.path.exists(fn):
        os.remove(fn)
menu = {"1": visit, "2": back, "3": forward, "4": show_current, "5": show_stacks, "6": add_bookmark,
        "7": show_bookmarks, "8": history, "9": clear}
print("=" * 56)
print("BROWSER HISTORY MANAGER  (Stack)".center(56))
print("=" * 56)
while True:
    print("\n1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Browser closed.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Display menu and read choice
  3. Choice is Back? → No: Visit / Forward / other option
  4. back_stack empty? → No: forward.push(current); current = back.pop()
  5. 'Underflow - no previous page'
  6. Show current page
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Visit google.comCurrent = google.comPASS
2Visit 3 more pagesBack stack holds 3PASS
3Back twiceForward stack holds 2PASS
4Forward onceMoves one page aheadPASS
5Visit after BackForward stack clearedPASS
6Back with empty stackUnderflow messagePASS
7Forward with empty stackUnderflow messagePASS
8Visit invalid 'abc''Invalid URL'PASS
9BookmarkSaved in filePASS
10Most visitedCounts from history.csvPASS
โš  Limitations
  • URLs are typed - no real web page is opened
  • Stack limit of 10 for demonstration
  • Single tab
  • No search in history
๐Ÿš€ Future scope
  • Open pages with the webbrowser module
  • Multiple tabs (list of stack pairs)
  • Tkinter GUI with buttons
  • Incognito mode (no history saving)

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): csv - reading / writing CSV files, os - file and folder operations are loaded.
  2. Global variables / constants are created: MAX, current, visits.
  3. 13 functions are defined (lines 14โ€“115) - Python stores them but does NOT run them yet.
  4. Main program starts at line 9: back_stack, forward_stack = [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
is_empty(stk)14โ€“15Is emptypop(), peek(), back(), forward()
push(stk, item)18โ€“22Pushvisit(), back(), forward()
pop(stk)25โ€“26Popback(), forward()
peek(stk)29โ€“30Peekshow_current()
visit()33โ€“44Visitmain program (menu)
back()47โ€“54Backmain program (menu)
forward()57โ€“64Forwardmain program (menu)
show_current()67โ€“70Show currentmain program (menu)
show_stacks()73โ€“82Show stacksmain program (menu)
add_bookmark()85โ€“88Add bookmarkmain program (menu)
show_bookmarks()91โ€“97Show bookmarksmain program (menu)
history()100โ€“109Historymain program (menu)
clear()112โ€“115Clearmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
9
back_stack, forward_stack = [], []
๐Ÿงฎ Store / Calculate Stores [], [] into back_stack, forward_stack respectively
10
current = "home"
๐Ÿงฎ Store / Calculate Stores the text "home" in variable current
11
visits = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable visits
118
for fn in ("history.csv", "bookmarks.txt"):
๐Ÿ” Loop LOOP: takes each item of ("history.csv", "bookmarks.txt") one-by-one into fn and runs the indented block for it
119
if os.path.exists(fn):
๐Ÿ”€ Decision CHECKS whether os.path.exists(fn) is True. If True, the indented lines below run; otherwise they are skipped
120
os.remove(fn)
๐Ÿ“ File Deletes the file fn
121
menu = {"1": visit, "2": back, "3": forward, "4": show_current, "5": show_stacks, "6": add_bookmark,
        "7": show_bookmarks, "8": history, "9": clear}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": visit, "2": back, "3": forward, "4": shโ€ฆ in variable menu
123
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
124
print("BROWSER HISTORY MANAGER  (Stack)".center(56))
๐Ÿ–ฅ๏ธ Output Displays the value of "BROWSER HISTORY MANAGER (Stack)".center(56) on the screen
125
print("=" * 56)
๐Ÿ–ฅ๏ธ Output Displays a line of 56 "=" signs on the screen
126
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
127
print("\n1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Visit 2.Back 3.Forward 4.Currenโ€ฆ" on the screen
128
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
129
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
130
print("Browser closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Browser closed." on the screen
131
break
๐Ÿ” Loop BREAK - leaves the loop immediately
132
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: BROWSER HISTORY MANAGER (Stack) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: visit()
  3. You type www.google.com at Enter URL:
    runs: push()
    shows: Now on: www.google.com (+1 more lines)
  4. You type 1 at Enter choice:
    runs: visit()
  5. You type www.cbse.gov.in at Enter URL:
    runs: push()
    shows: Now on: www.cbse.gov.in (+1 more lines)
  6. You type 1 at Enter choice:
    runs: visit()
  7. You type kvsangathan.nic.in at Enter URL:
    runs: push()
    shows: Now on: kvsangathan.nic.in (+1 more lines)
  8. You type 1 at Enter choice:
    runs: visit()
  9. You type abc at Enter URL:
    shows: Invalid URL. (+1 more lines)
  10. You type 1 at Enter choice:
    runs: visit()
  11. You type www.python.org at Enter URL:
    runs: push()
    shows: Now on: www.python.org (+1 more lines)
  12. You type 5 at Enter choice:
    runs: show_stacks()
    shows: BACK STACK FORWARD STACK (+7 more lines)
  13. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: kvsangathan.nic.in (+1 more lines)
  14. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: www.cbse.gov.in (+1 more lines)
  15. You type 4 at Enter choice:
    runs: show_current() โ†’ peek() โ†’ is_empty() โ†’ peek() โ†’ is_empty()
    shows: Current page : www.cbse.gov.in (+3 more lines)
  16. You type 3 at Enter choice:
    runs: forward() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: -> Forward to: kvsangathan.nic.in (+1 more lines)
  17. You type 5 at Enter choice:
    runs: show_stacks()
    shows: BACK STACK FORWARD STACK (+6 more lines)
  18. You type 6 at Enter choice:
    runs: add_bookmark()
    shows: Bookmarked: kvsangathan.nic.in (+1 more lines)
  19. You type 1 at Enter choice:
    runs: visit()
  20. You type www.w3schools.com at Enter URL:
    runs: push()
    shows: Now on: www.w3schools.com (+1 more lines)
  21. You type 5 at Enter choice:
    runs: show_stacks()
    shows: BACK STACK FORWARD STACK (+7 more lines)
  22. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: kvsangathan.nic.in (+1 more lines)
  23. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: www.cbse.gov.in (+1 more lines)
  24. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: www.google.com (+1 more lines)
  25. You type 2 at Enter choice:
    runs: back() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: <- Back to: home (+1 more lines)
  26. You type 3 at Enter choice:
    runs: forward() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: -> Forward to: www.google.com (+1 more lines)
  27. You type 3 at Enter choice:
    runs: forward() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: -> Forward to: www.cbse.gov.in (+1 more lines)
  28. You type 3 at Enter choice:
    runs: forward() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: -> Forward to: kvsangathan.nic.in (+1 more lines)
  29. You type 3 at Enter choice:
    runs: forward() โ†’ is_empty() โ†’ push() โ†’ pop() โ†’ is_empty()
    shows: -> Forward to: www.w3schools.com (+1 more lines)
  30. You type 1 at Enter choice:
    runs: visit()
  31. You type www.google.com at Enter URL:
    runs: push()
    shows: Now on: www.google.com (+1 more lines)
  32. You type 1 at Enter choice:
    runs: visit()
  33. You type www.python.org at Enter URL:
    runs: push()
    shows: Now on: www.python.org (+1 more lines)
  34. You type 6 at Enter choice:
    runs: add_bookmark()
    shows: Bookmarked: www.python.org (+1 more lines)
  35. You type 7 at Enter choice:
    runs: show_bookmarks()
    shows: 1. kvsangathan.nic.in (+2 more lines)
  36. You type 8 at Enter choice:
    runs: history()
    shows: Visit log: 1:www.google.com | 2:www.cbse.gov.in | 3:kvsangathan.nic.in | 4:www.python.org (+5 more lines)
  37. You type 9 at Enter choice:
    runs: clear()
    shows: History cleared. Back and Forward stacks are empty. (+1 more lines)
  38. You type 2 at Enter choice:
    runs: back() โ†’ is_empty()
    shows: Underflow! No previous page. (+1 more lines)
  39. You type 0 at Enter choice:
    shows: Browser closed.
โ‘ค Inside each function - line by line
is_empty() - lines 14โ€“15
LineCodeWhat it does
14
def is_empty(stk):
๐Ÿงฉ Function DEFINES a function is_empty(stk). Python only remembers it here - its body runs later, each time is_empty() is called.
15
return len(stk) == 0
๐Ÿงฉ Function Sends back (returns) True/False for len(stk) is equal to 0 to the line that called the function
push() - lines 18โ€“22
LineCodeWhat it does
18
def push(stk, item):
๐Ÿงฉ Function DEFINES a function push(stk, item). Python only remembers it here - its body runs later, each time push() is called.
19
if len(stk) == MAX:
๐Ÿ”€ Decision CHECKS whether len(stk) is equal to MAX. If True, the indented lines below run; otherwise they are skipped
20
print("Overflow! Oldest page removed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Overflow! Oldest page removed." on the screen
21
stk.pop(0)
๐Ÿงฎ Store / Calculate Removes and returns an item at position 0 from stk
22
stk.append(item)
๐Ÿงฎ Store / Calculate Adds item at the end of list stk
pop() - lines 25โ€“26
LineCodeWhat it does
25
def pop(stk):
๐Ÿงฉ Function DEFINES a function pop(stk). Python only remembers it here - its body runs later, each time pop() is called.
26
return None if is_empty(stk) else stk.pop()
๐Ÿงฉ Function Sends back (returns) either None or stk.pop() depending on is_empty(stk) to the line that called the function
peek() - lines 29โ€“30
LineCodeWhat it does
29
def peek(stk):
๐Ÿงฉ Function DEFINES a function peek(stk). Python only remembers it here - its body runs later, each time peek() is called.
30
return "-" if is_empty(stk) else stk[-1]
๐Ÿงฉ Function Sends back (returns) either "-" or stk[-1] depending on is_empty(stk) to the line that called the function
visit() - lines 33โ€“44
LineCodeWhat it does
33
def visit():
๐Ÿงฉ Function DEFINES a function visit(). Python only remembers it here - its body runs later, each time visit() is called.
34
global current, visits
๐Ÿงฉ Function Tells Python that current, visits means the GLOBAL variable (outside the function)
35
url = input("Enter URL: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable url
36
if "." not in url:
๐Ÿ”€ Decision CHECKS whether "." is not present in url. If True, the indented lines below run; otherwise they are skipped
37
print("Invalid URL.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid URL." on the screen
38
return
๐Ÿงฉ Function Ends the function and goes back to the caller
39
push(back_stack, current)
๐Ÿงฎ Store / Calculate Calls our own function push(back_stack, current)
40
forward_stack.clear()                  # new branch of history
๐Ÿงฎ Store / Calculate Removes all items from forward_stack
41
current, visits = url, visits + 1
๐Ÿงฎ Store / Calculate Stores url, visits + 1 into current, visits respectively
42
with open("history.csv", "a", newline="") as f:
๐Ÿ“ File Opens the file "history.csv" in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
43
csv.writer(f).writerow([visits, url])
๐Ÿ“ File Writes one row [visits, url] into the CSV file
44
print("Now on:", current)
๐Ÿ–ฅ๏ธ Output Displays the text "Now on:", then the value of current on the screen
back() - lines 47โ€“54
LineCodeWhat it does
47
def back():
๐Ÿงฉ Function DEFINES a function back(). Python only remembers it here - its body runs later, each time back() is called.
48
global current
๐Ÿงฉ Function Tells Python that current means the GLOBAL variable (outside the function)
49
if is_empty(back_stack):
๐Ÿ”€ Decision CHECKS whether is_empty(back_stack) is True. If True, the indented lines below run; otherwise they are skipped
50
print("Underflow! No previous page.")
๐Ÿ–ฅ๏ธ Output Displays the text "Underflow! No previous page." on the screen
51
return
๐Ÿงฉ Function Ends the function and goes back to the caller
52
push(forward_stack, current)
๐Ÿงฎ Store / Calculate Calls our own function push(forward_stack, current)
53
current = pop(back_stack)
๐Ÿงฎ Store / Calculate Calls our own function pop(back_stack); the result is stored in variable current
54
print("<- Back to:", current)
๐Ÿ–ฅ๏ธ Output Displays the text "<- Back to:", then the value of current on the screen
forward() - lines 57โ€“64
LineCodeWhat it does
57
def forward():
๐Ÿงฉ Function DEFINES a function forward(). Python only remembers it here - its body runs later, each time forward() is called.
58
global current
๐Ÿงฉ Function Tells Python that current means the GLOBAL variable (outside the function)
59
if is_empty(forward_stack):
๐Ÿ”€ Decision CHECKS whether is_empty(forward_stack) is True. If True, the indented lines below run; otherwise they are skipped
60
print("Underflow! No forward page.")
๐Ÿ–ฅ๏ธ Output Displays the text "Underflow! No forward page." on the screen
61
return
๐Ÿงฉ Function Ends the function and goes back to the caller
62
push(back_stack, current)
๐Ÿงฎ Store / Calculate Calls our own function push(back_stack, current)
63
current = pop(forward_stack)
๐Ÿงฎ Store / Calculate Calls our own function pop(forward_stack); the result is stored in variable current
64
print("-> Forward to:", current)
๐Ÿ–ฅ๏ธ Output Displays the text "-> Forward to:", then the value of current on the screen
show_current() - lines 67โ€“70
LineCodeWhat it does
67
def show_current():
๐Ÿงฉ Function DEFINES a function show_current(). Python only remembers it here - its body runs later, each time show_current() is called.
68
print(f"Current page : {current}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Current page : {current}" with the values filled into { } on the screen
69
print(f"Back top     : {peek(back_stack)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Back top : {peek(back_stack)}" with the values filled into { } on the screen
70
print(f"Forward top  : {peek(forward_stack)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Forward top : {peek(forward_stack)}" with the values filled into { } on the screen
show_stacks() - lines 73โ€“82
LineCodeWhat it does
73
def show_stacks():
๐Ÿงฉ Function DEFINES a function show_stacks(). Python only remembers it here - its body runs later, each time show_stacks() is called.
74
h = max(len(back_stack), len(forward_stack), 1)
๐Ÿงฎ Store / Calculate Finds the largest value among len(back_stack), len(forward_stack), 1; the result is stored in variable h
75
print(f"  {'BACK STACK':^22}   {'FORWARD STACK':^22}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {'BACK STACK':^22} {'FORWARD STACK':^22}" with the values filled into { } on the screen
76
for i in range(h - 1, -1, -1):
๐Ÿ” Loop LOOP: gives the numbers from h - 1 up to (not including) -1, jumping by -1; for each number, i takes that value and the indented block runs once
77
b = back_stack[i] if i < len(back_stack) else ""
๐Ÿงฎ Store / Calculate Stores either back_stack[i] or "" depending on i < len(back_stack) in variable b
78
f = forward_stack[i] if i < len(forward_stack) else ""
๐Ÿงฎ Store / Calculate Stores either forward_stack[i] or "" depending on i < len(forward_stack) in variable f
79
tb = " <-top" if i == len(back_stack) - 1 else ""
๐Ÿงฎ Store / Calculate Stores either " <-top" or "" depending on i == len(back_stack) - 1 in variable tb
80
print(f"  |{b:^20}|{tb:<6} |{f:^20}|")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" |{b:^20}|{tb:<6} |{f:^20}|" with the values filled into { } on the screen
81
print("  +" + "-" * 20 + "+       +" + "-" * 20 + "+")
๐Ÿ–ฅ๏ธ Output Displays the value of " +" + "-" * 20 + "+ +" + "-" * 20 + "+" on the screen
82
print("  Current page:", current)
๐Ÿ–ฅ๏ธ Output Displays the text "Current page:", then the value of current on the screen
add_bookmark() - lines 85โ€“88
LineCodeWhat it does
85
def add_bookmark():
๐Ÿงฉ Function DEFINES a function add_bookmark(). Python only remembers it here - its body runs later, each time add_bookmark() is called.
86
with open("bookmarks.txt", "a") as f:
๐Ÿ“ File Opens the file "bookmarks.txt" in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
87
f.write(current + "\n")
๐Ÿ“ File Writes current + "\n" into file f
88
print("Bookmarked:", current)
๐Ÿ–ฅ๏ธ Output Displays the text "Bookmarked:", then the value of current on the screen
show_bookmarks() - lines 91โ€“97
LineCodeWhat it does
91
def show_bookmarks():
๐Ÿงฉ Function DEFINES a function show_bookmarks(). Python only remembers it here - its body runs later, each time show_bookmarks() is called.
92
if not os.path.exists("bookmarks.txt"):
๐Ÿ”€ Decision CHECKS whether NOT os.path.exists("bookmarks.txt") is True. If True, the indented lines below run; otherwise they are skipped
93
print("No bookmarks.")
๐Ÿ–ฅ๏ธ Output Displays the text "No bookmarks." on the screen
94
return
๐Ÿงฉ Function Ends the function and goes back to the caller
95
with open("bookmarks.txt") as f:
๐Ÿ“ File Opens the file "bookmarks.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
96
for i, line in enumerate(f, 1):
๐Ÿ” Loop LOOP over f with position: in each round i, line get (position, item)
97
print(f"  {i}. {line.strip()}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {i}. {line.strip()}" with the values filled into { } on the screen
history() - lines 100โ€“109
LineCodeWhat it does
100
def history():
๐Ÿงฉ Function DEFINES a function history(). Python only remembers it here - its body runs later, each time history() is called.
101
count = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable count
102
with open("history.csv", newline="") as f:
๐Ÿ“ File Opens the file "history.csv" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
103
rows = list(csv.reader(f))
๐Ÿ“ File Makes a list from csv.reader(f); the result is stored in variable rows
104
for n, url in rows:
๐Ÿ” Loop LOOP: takes each item of rows one-by-one into n, url and runs the indented block for it
105
count[url] = count.get(url, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of count.get(url, 0) + 1 (calculated using +) into count[url] (item url of count)
106
print("Visit log:", " | ".join(f"{n}:{u}" for n, u in rows))
๐Ÿ–ฅ๏ธ Output Displays the text "Visit log:", then the value of " | ".join(f"{n}:{u}" for n, u in rows) on the screen
107
print("Most visited:")
๐Ÿ–ฅ๏ธ Output Displays the text "Most visited:" on the screen
108
for url, c in sorted(count.items(), key=lambda x: -x[1])[:3]:
๐Ÿ” Loop LOOP: takes each item of sorted(count.items(), key=lambda x: -x[1])[:3] one-by-one into url, c and runs the indented block for it
109
print(f"  {url:<22} {'#' * c} {c}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {url:<22} {'#' * c} {c}" with the values filled into { } on the screen
clear() - lines 112โ€“115
LineCodeWhat it does
112
def clear():
๐Ÿงฉ Function DEFINES a function clear(). Python only remembers it here - its body runs later, each time clear() is called.
113
back_stack.clear()
๐Ÿงฎ Store / Calculate Removes all items from back_stack
114
forward_stack.clear()
๐Ÿงฎ Store / Calculate Removes all items from forward_stack
115
print("History cleared. Back and Forward stacks are empty.")
๐Ÿ–ฅ๏ธ Output Displays the text "History cleared. Back and Forwardโ€ฆ" on the screen
Q1. Why are two stacks needed?

Back needs the pages visited before (back stack) and Forward needs pages left after pressing Back (forward stack); both work in LIFO order.

Q2. Why is the forward stack cleared on a new visit?

After visiting a new page the old 'forward' pages are no longer reachable - real browsers behave the same way.

Q3. What is underflow and overflow?

Underflow: pop from an empty stack. Overflow: push on a full stack (here when size reaches MAX).

Q4. How is peek done?

stack[-1] returns the top element without removing it.

Q5. Which file modes are used?

'a' to add bookmarks and history, 'r' to read them; 'w' to clear.

10

Hotel Management System (Python + MySQL)

PYTHON + MySQLMySQL tablesUPDATE with statusdate arithmetic (datetime)aggregate GROUP BY reportfunctions
๐Ÿ“ 153 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 143 output lines๐Ÿ“„ 25+ page report

Check guests in to vacant rooms, check them out with automatic bill calculation (nights x rate + 12% GST) and print a room-type revenue report.

โœจ Features
  • Room master table (Standard / Deluxe / Suite) with tariff and status
  • Guest check-in with ID proof, number of guests and check-in date
  • Room service orders added to the bill (restaurant / laundry)
  • Check-out: nights from dates (datetime), room charge + service + GST 12 % / 18 % by tariff
  • Available rooms by type; occupancy percentage
  • Revenue report with GROUP BY room type
โ˜ฐ Main menu
1Show RoomsAll rooms with status
2Available RoomsFilter by type
3Check-inINSERT guest, room -> Occupied
4Room ServiceAdds service charges
5Check-out & BillCalculates nights, GST and prints bill
6Current GuestsJOIN of guest and room
7Revenue ReportGROUP BY room type
8OccupancyPercentage of rooms occupied
0ExitCloses connection
๐ŸŽฏ Objectives
  • Maintain room status with UPDATE queries
  • Calculate bills with GST in Python
  • Generate reports with JOIN and GROUP BY
๐Ÿ“š Data dictionary
NameTypePurpose
roomMySQL tablerno PK, rtype, tariff, status
guestMySQL tablegid PK, name, idproof, rno, checkin DATE, checkout DATE, service, total
serviceMySQL tablegid, item, amount
GSTfunction12 % if tariff <= 7500 else 18 %
Why it matters: Combines Python date handling with SQL updates and reporting - ideal for a documented board project.
# =====================================================================
#   HOTEL MANAGEMENT SYSTEM  (Python + MySQL)
#   Concepts : MySQL tables, INSERT / UPDATE, JOIN, GROUP BY,
#              datetime date arithmetic, functions
# =====================================================================
import mysql.connector
from datetime import date

conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS hotel_db")
cur.execute("USE hotel_db")
cur.execute("CREATE TABLE IF NOT EXISTS room (rno INT PRIMARY KEY, rtype VARCHAR(10), tariff INT, status VARCHAR(10))")
cur.execute("""CREATE TABLE IF NOT EXISTS guest (gid INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(25), idproof VARCHAR(10),
               rno INT, checkin DATE, checkout DATE, total DECIMAL(10,2))""")
cur.execute("CREATE TABLE IF NOT EXISTS service (gid INT, item VARCHAR(20), amount DECIMAL(8,2))")
cur.execute("SELECT COUNT(*) FROM room")
if cur.fetchone()[0] == 0:
    rooms = [(101, "Standard", 3500), (102, "Standard", 3500), (103, "Standard", 3500),
             (201, "Deluxe", 6000), (202, "Deluxe", 6000), (301, "Suite", 12000)]
    cur.executemany("INSERT INTO room VALUES (%s,%s,%s,'Available')", rooms)
    conn.commit()


def gst_rate(tariff):
    return 0.12 if tariff <= 7500 else 0.18


def show_rooms():
    cur.execute("SELECT * FROM room")
    print(f"{'Room':<6}{'Type':<10}{'Tariff':>8}  Status")
    for r in cur.fetchall():
        print(f"{r[0]:<6}{r[1]:<10}{r[2]:>8}  {r[3]}")


def available():
    t = input("Room type (Standard/Deluxe/Suite): ").strip().title()
    cur.execute("SELECT rno, tariff FROM room WHERE rtype = %s AND status = 'Available'", (t,))
    rows = cur.fetchall()
    print(f"Available {t} rooms:", ", ".join(f"{r} (Rs. {p})" for r, p in rows) or "None")


def guest_in(rno):
    cur.execute("SELECT gid, name, checkin FROM guest WHERE rno = %s AND checkout IS NULL", (rno,))
    return cur.fetchone()


def check_in():
    rno = int(input("Room no  : "))
    cur.execute("SELECT status FROM room WHERE rno = %s", (rno,))
    r = cur.fetchone()
    if not r:
        print("No such room.")
        return
    name = input("Guest name: ").strip().title()
    idp = input("ID proof  : ").strip()
    d = input("Check-in date (yyyy-mm-dd): ").strip()
    if r[0] != "Available":
        print("Room not available.")
        return
    cur.execute("INSERT INTO guest (name, idproof, rno, checkin) VALUES (%s,%s,%s,%s)", (name, idp, rno, d))
    gid = cur.lastrowid
    cur.execute("UPDATE room SET status = 'Occupied' WHERE rno = %s", (rno,))
    conn.commit()
    print(f"Welcome {name}! Room {rno} allotted. Guest ID {gid}")


def room_service():
    rno = int(input("Room no : "))
    g = guest_in(rno)
    item, amt = input("Item    : ").strip(), float(input("Amount  : "))
    if not g:
        print("Room is not occupied.")
        return
    cur.execute("INSERT INTO service VALUES (%s,%s,%s)", (g[0], item, amt))
    conn.commit()
    print(f"Rs. {amt:.0f} for {item} added to {g[1]}'s bill.")


def check_out():
    rno = int(input("Room no : "))
    out = date.fromisoformat(input("Check-out date (yyyy-mm-dd): ").strip())
    g = guest_in(rno)
    if not g:
        print("Room is not occupied.")
        return
    nights = (out - g[2]).days
    if nights <= 0:
        print("Invalid date - check-out must be after check-in.")
        return
    cur.execute("SELECT tariff, rtype FROM room WHERE rno = %s", (rno,))
    tariff, rtype = cur.fetchone()
    cur.execute("SELECT item, amount FROM service WHERE gid = %s", (g[0],))
    services = cur.fetchall()
    room_amt = nights * tariff
    serv = sum(float(a) for _, a in services)
    rate = gst_rate(tariff)
    gst = room_amt * rate
    total = room_amt + serv + gst
    cur.execute("UPDATE guest SET checkout = %s, total = %s WHERE gid = %s", (out, total, g[0]))
    cur.execute("UPDATE room SET status = 'Available' WHERE rno = %s", (rno,))
    conn.commit()
    print("=" * 44)
    print("HOTEL KV RESIDENCY - BILL".center(44))
    print(f"Guest: {g[1]}   Room {rno} ({rtype})")
    print(f"Stay : {g[2]} to {out}  ({nights} nights)")
    print("-" * 44)
    print(f"{'Room charges ' + str(nights) + ' x ' + str(tariff):<30}{room_amt:>14,.2f}")
    for item, a in services:
        print(f"  {item:<28}{float(a):>14,.2f}")
    print(f"{'GST on room @ ' + str(int(rate * 100)) + '%':<30}{gst:>14,.2f}")
    print(f"{'TOTAL':<30}{total:>14,.2f}")
    print("=" * 44)


def current_guests():
    cur.execute("""SELECT g.gid, g.name, r.rno, r.rtype, g.checkin FROM guest g JOIN room r ON g.rno = r.rno
                   WHERE g.checkout IS NULL ORDER BY r.rno""")
    for r in cur.fetchall():
        print(f"  Guest {r[0]}: {r[1]:<15} Room {r[2]} ({r[3]}) since {r[4]}")


def revenue():
    cur.execute("""SELECT r.rtype, COUNT(g.gid), SUM(g.total) FROM room r LEFT JOIN guest g
                   ON r.rno = g.rno AND g.checkout IS NOT NULL GROUP BY r.rtype""")
    print(f"{'Type':<10}{'Stays':>6}{'Revenue':>14}")
    for t, c, s in cur.fetchall():
        print(f"{t:<10}{c:>6}{float(s or 0):>14,.2f}")


def occupancy():
    cur.execute("SELECT COUNT(*), SUM(status = 'Occupied') FROM room")
    n, occ = cur.fetchone()
    print(f"Occupied {occ}/{n} rooms -> occupancy {int(occ) * 100 / n:.1f}%")


menu = {"1": show_rooms, "2": available, "3": check_in, "4": room_service, "5": check_out,
        "6": current_guests, "7": revenue, "8": occupancy}
print("=" * 50)
print("HOTEL MANAGEMENT SYSTEM (Python + MySQL)".center(50))
print("=" * 50)
while True:
    print("\n1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Thank you!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Invalid input.")

        
  1. Start
  2. Create hotel_db tables and rooms
  3. Display menu and read choice
  4. Choice is Check-out? → No: run selected option
  5. Read room number and checkout date
  6. nights = (checkout - checkin).days
  7. Bill = nights x tariff + service + GST
  8. UPDATE guest and room status, COMMIT
  9. Print bill
  10. Choice is 0? → No: show menu
  11. Stop
#Test case / inputExpected resultStatus
1Check-in room 101Room OccupiedPASS
2Check-in occupied room'Room not available'PASS
3Room 999'No such room'PASS
4Room service Rs. 450Added to guestPASS
5Check-out after 3 nights3 x tariff + GSTPASS
6Checkout before checkin'Invalid date'PASS
7Available DeluxeOnly free Deluxe roomsPASS
8Revenue reportType-wise totalsPASS
9OccupancyPercentagePASS
โš  Limitations
  • No advance booking for future dates
  • One guest record per room stay
  • GST rule simplified
  • No online payment
๐Ÿš€ Future scope
  • Advance booking calendar
  • Tkinter front-desk GUI
  • Invoice PDF and e-mail
  • Housekeeping status module

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 6): mysql.connector - connecting Python with MySQL, date are loaded.
  2. Global variables / constants are created: conn, cur.
  3. 10 functions are defined (lines 25โ€“134) - Python stores them but does NOT run them yet.
  4. Main program starts at line 11: cur.execute("CREATE DATABASE IF NOT EXISTS hotel_db") - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
gst_rate(tariff)25โ€“26Gst ratecheck_out()
show_rooms()29โ€“33Show roomsmain program (menu)
available()36โ€“40Availablemain program (menu)
guest_in(rno)43โ€“45Guest inroom_service(), check_out()
check_in()48โ€“65Check inmain program (menu)
room_service()68โ€“77Room servicemain program (menu)
check_out()80โ€“113Check outmain program (menu)
current_guests()116โ€“120Current guestsmain program (menu)
revenue()123โ€“128Revenuemain program (menu)
occupancy()131โ€“134Occupancymain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
11
cur.execute("CREATE DATABASE IF NOT EXISTS hotel_db")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
12
cur.execute("USE hotel_db")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
13
cur.execute("CREATE TABLE IF NOT EXISTS room (rno INT PRIMARY KEY, rtype VARCHAR(10), tariff INT, status VARCHAR(10))")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
14
cur.execute("""CREATE TABLE IF NOT EXISTS guest (gid INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(25), idproof VARCHAR(10),
               rno INT, checkin Dโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
16
cur.execute("CREATE TABLE IF NOT EXISTS service (gid INT, item VARCHAR(20), amount DECIMAL(8,2))")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
17
cur.execute("SELECT COUNT(*) FROM room")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
18
if cur.fetchone()[0] == 0:
๐Ÿ”€ Decision CHECKS whether cur.fetchone()[0] is equal to 0. If True, the indented lines below run; otherwise they are skipped
19
rooms = [(101, "Standard", 3500), (102, "Standard", 3500), (103, "Standard", 3500),
         (201, "Deluxe", 6000), (202, "Deluxe", 6000), (301, "Suite", 120โ€ฆ
๐Ÿงฎ Store / Calculate Stores a list [(101, "Standard", 3500), (102, "Standard", 3โ€ฆ in variable rooms
21
cur.executemany("INSERT INTO room VALUES (%s,%s,%s,'Available')", rooms)
๐Ÿฌ Database Runs the same SQL for every row of rooms
22
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
137
menu = {"1": show_rooms, "2": available, "3": check_in, "4": room_service, "5": check_out,
        "6": current_guests, "7": revenue, "8": occupancy}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": show_rooms, "2": available, "3": check_โ€ฆ in variable menu
139
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
140
print("HOTEL MANAGEMENT SYSTEM (Python + MySQL)".center(50))
๐Ÿ–ฅ๏ธ Output Displays the value of "HOTEL MANAGEMENT SYSTEM (Python + MySQL)".ceโ€ฆ on the screen
141
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
142
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
143
print("\n1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Rooms 2.Available 3.Check-in 4.โ€ฆ" on the screen
144
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
145
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
146
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
147
print("Thank you!")
๐Ÿ–ฅ๏ธ Output Displays the text "Thank you!" on the screen
148
break
๐Ÿ” Loop BREAK - leaves the loop immediately
149
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
150
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
151
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
152
print("Invalid input.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid input." on the screen
โ‘ฃ Inside each function - line by line
gst_rate() - lines 25โ€“26
LineCodeWhat it does
25
def gst_rate(tariff):
๐Ÿงฉ Function DEFINES a function gst_rate(tariff). Python only remembers it here - its body runs later, each time gst_rate() is called.
26
return 0.12 if tariff <= 7500 else 0.18
๐Ÿงฉ Function Sends back (returns) either 0.12 or 0.18 depending on tariff <= 7500 to the line that called the function
show_rooms() - lines 29โ€“33
LineCodeWhat it does
29
def show_rooms():
๐Ÿงฉ Function DEFINES a function show_rooms(). Python only remembers it here - its body runs later, each time show_rooms() is called.
30
cur.execute("SELECT * FROM room")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
31
print(f"{'Room':<6}{'Type':<10}{'Tariff':>8}  Status")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Room':<6}{'Type':<10}{'Tariff':>8} Status" with the values filled into { } on the screen
32
for r in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into r and runs the indented block for it
33
print(f"{r[0]:<6}{r[1]:<10}{r[2]:>8}  {r[3]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r[0]:<6}{r[1]:<10}{r[2]:>8} {r[3]}" with the values filled into { } on the screen
available() - lines 36โ€“40
LineCodeWhat it does
36
def available():
๐Ÿงฉ Function DEFINES a function available(). Python only remembers it here - its body runs later, each time available() is called.
37
t = input("Room type (Standard/Deluxe/Suite): ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable t
38
cur.execute("SELECT rno, tariff FROM room WHERE rtype = %s AND status = 'Available'", (t,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (t,)
39
rows = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable rows
40
print(f"Available {t} rooms:", ", ".join(f"{r} (Rs. {p})" for r, p in rows) or "None")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Available {t} rooms:" with the values filled into { }, then the value of ", ".join(f"{r} (Rs. {p})" for r, p in rows) โ€ฆ on the screen
guest_in() - lines 43โ€“45
LineCodeWhat it does
43
def guest_in(rno):
๐Ÿงฉ Function DEFINES a function guest_in(rno). Python only remembers it here - its body runs later, each time guest_in() is called.
44
cur.execute("SELECT gid, name, checkin FROM guest WHERE rno = %s AND checkout IS NULL", (rno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (rno,)
45
return cur.fetchone()
๐Ÿงฉ Function Sends back (returns) the result of: brings the NEXT ONE row of the result as a tuple (None if no row is left) to the line that called the function
check_in() - lines 48โ€“65
LineCodeWhat it does
48
def check_in():
๐Ÿงฉ Function DEFINES a function check_in(). Python only remembers it here - its body runs later, each time check_in() is called.
49
rno = int(input("Room no  : "))
โŒจ๏ธ Input Shows "Room no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable rno
50
cur.execute("SELECT status FROM room WHERE rno = %s", (rno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (rno,)
51
r = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variable r
52
if not r:
๐Ÿ”€ Decision CHECKS whether r is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
53
print("No such room.")
๐Ÿ–ฅ๏ธ Output Displays the text "No such room." on the screen
54
return
๐Ÿงฉ Function Ends the function and goes back to the caller
55
name = input("Guest name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable name
56
idp = input("ID proof  : ").strip()
โŒจ๏ธ Input Shows "ID proof : ", reads the typed text, removes extra spaces (strip) and stores it in variable idp
57
d = input("Check-in date (yyyy-mm-dd): ").strip()
โŒจ๏ธ Input Shows "Check-in date (yyyy-mm-dd): ", reads the typed text, removes extra spaces (strip) and stores it in variable d
58
if r[0] != "Available":
๐Ÿ”€ Decision CHECKS whether r[0] is not equal to "Available". If True, the indented lines below run; otherwise they are skipped
59
print("Room not available.")
๐Ÿ–ฅ๏ธ Output Displays the text "Room not available." on the screen
60
return
๐Ÿงฉ Function Ends the function and goes back to the caller
61
cur.execute("INSERT INTO guest (name, idproof, rno, checkin) VALUES (%s,%s,%s,%s)", (name, idp, rno, d))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (name, idp, rno, d)
62
gid = cur.lastrowid
๐Ÿงฎ Store / Calculate Stores cur.lastrowid in variable gid
63
cur.execute("UPDATE room SET status = 'Occupied' WHERE rno = %s", (rno,))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (rno,)
64
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
65
print(f"Welcome {name}! Room {rno} allotted. Guest ID {gid}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Welcome {name}! Room {rno} allotted. Guest โ€ฆ with the values filled into { } on the screen
room_service() - lines 68โ€“77
LineCodeWhat it does
68
def room_service():
๐Ÿงฉ Function DEFINES a function room_service(). Python only remembers it here - its body runs later, each time room_service() is called.
69
rno = int(input("Room no : "))
โŒจ๏ธ Input Shows "Room no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable rno
70
g = guest_in(rno)
๐Ÿงฎ Store / Calculate Calls our own function guest_in(rno); the result is stored in variable g
71
item, amt = input("Item    : ").strip(), float(input("Amount  : "))
โŒจ๏ธ Input Stores input("Item : ").strip(), float(input("Amount : ")) into item, amt respectively
72
if not g:
๐Ÿ”€ Decision CHECKS whether g is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
73
print("Room is not occupied.")
๐Ÿ–ฅ๏ธ Output Displays the text "Room is not occupied." on the screen
74
return
๐Ÿงฉ Function Ends the function and goes back to the caller
75
cur.execute("INSERT INTO service VALUES (%s,%s,%s)", (g[0], item, amt))
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values (g[0], item, amt)
76
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
77
print(f"Rs. {amt:.0f} for {item} added to {g[1]}'s bill.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Rs. {amt:.0f} for {item} added to {g[1]}'s โ€ฆ with the values filled into { } on the screen
check_out() - lines 80โ€“113
LineCodeWhat it does
80
def check_out():
๐Ÿงฉ Function DEFINES a function check_out(). Python only remembers it here - its body runs later, each time check_out() is called.
81
rno = int(input("Room no : "))
โŒจ๏ธ Input Shows "Room no : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable rno
82
out = date.fromisoformat(input("Check-out date (yyyy-mm-dd): ").strip())
โŒจ๏ธ Input Converts text like "2026-01-15" into a date; the result is stored in variable out
83
g = guest_in(rno)
๐Ÿงฎ Store / Calculate Calls our own function guest_in(rno); the result is stored in variable g
84
if not g:
๐Ÿ”€ Decision CHECKS whether g is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
85
print("Room is not occupied.")
๐Ÿ–ฅ๏ธ Output Displays the text "Room is not occupied." on the screen
86
return
๐Ÿงฉ Function Ends the function and goes back to the caller
87
nights = (out - g[2]).days
๐Ÿงฎ Store / Calculate Stores (out - g[2]).days in variable nights
88
if nights <= 0:
๐Ÿ”€ Decision CHECKS whether nights is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
89
print("Invalid date - check-out must be after check-in.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid date - check-out must be โ€ฆ" on the screen
90
return
๐Ÿงฉ Function Ends the function and goes back to the caller
91
cur.execute("SELECT tariff, rtype FROM room WHERE rno = %s", (rno,))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (rno,)
92
tariff, rtype = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables tariff, rtype
93
cur.execute("SELECT item, amount FROM service WHERE gid = %s", (g[0],))
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor; the %s places are filled safely with the values (g[0],)
94
services = cur.fetchall()
๐Ÿฌ Database Brings ALL rows of the last SELECT result as a list of tuples; the result is stored in variable services
95
room_amt = nights * tariff
๐Ÿงฎ Store / Calculate Stores the value of nights * tariff (calculated using ร—) in variable room_amt
96
serv = sum(float(a) for _, a in services)
๐Ÿงฎ Store / Calculate Adds up all the values in (float(a) for _, a in services); the result is stored in variable serv
97
rate = gst_rate(tariff)
๐Ÿงฎ Store / Calculate Calls our own function gst_rate(tariff); the result is stored in variable rate
98
gst = room_amt * rate
๐Ÿงฎ Store / Calculate Stores the value of room_amt * rate (calculated using ร—) in variable gst
99
total = room_amt + serv + gst
๐Ÿงฎ Store / Calculate Stores the value of room_amt + serv + gst (calculated using +) in variable total
100
cur.execute("UPDATE guest SET checkout = %s, total = %s WHERE gid = %s", (out, total, g[0]))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (out, total, g[0])
101
cur.execute("UPDATE room SET status = 'Available' WHERE rno = %s", (rno,))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (rno,)
102
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
103
print("=" * 44)
๐Ÿ–ฅ๏ธ Output Displays a line of 44 "=" signs on the screen
104
print("HOTEL KV RESIDENCY - BILL".center(44))
๐Ÿ–ฅ๏ธ Output Displays the value of "HOTEL KV RESIDENCY - BILL".center(44) on the screen
105
print(f"Guest: {g[1]}   Room {rno} ({rtype})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Guest: {g[1]} Room {rno} ({rtype})" with the values filled into { } on the screen
106
print(f"Stay : {g[2]} to {out}  ({nights} nights)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Stay : {g[2]} to {out} ({nights} nights)" with the values filled into { } on the screen
107
print("-" * 44)
๐Ÿ–ฅ๏ธ Output Displays a line of 44 "-" signs on the screen
108
print(f"{'Room charges ' + str(nights) + ' x ' + str(tariff):<30}{room_amt:>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Room charges ' + str(nights) + ' x ' + stโ€ฆ with the values filled into { } on the screen
109
for item, a in services:
๐Ÿ” Loop LOOP: takes each item of services one-by-one into item, a and runs the indented block for it
110
print(f"  {item:<28}{float(a):>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {item:<28}{float(a):>14,.2f}" with the values filled into { } on the screen
111
print(f"{'GST on room @ ' + str(int(rate * 100)) + '%':<30}{gst:>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'GST on room @ ' + str(int(rate * 100)) + โ€ฆ with the values filled into { } on the screen
112
print(f"{'TOTAL':<30}{total:>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'TOTAL':<30}{total:>14,.2f}" with the values filled into { } on the screen
113
print("=" * 44)
๐Ÿ–ฅ๏ธ Output Displays a line of 44 "=" signs on the screen
current_guests() - lines 116โ€“120
LineCodeWhat it does
116
def current_guests():
๐Ÿงฉ Function DEFINES a function current_guests(). Python only remembers it here - its body runs later, each time current_guests() is called.
117
cur.execute("""SELECT g.gid, g.name, r.rno, r.rtype, g.checkin FROM guest g JOIN room r ON g.rno = r.rno
               WHERE g.checkout IS NULL ORDER BY r.rโ€ฆ
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
119
for r in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into r and runs the indented block for it
120
print(f"  Guest {r[0]}: {r[1]:<15} Room {r[2]} ({r[3]}) since {r[4]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Guest {r[0]}: {r[1]:<15} Room {r[2]} ({r[3โ€ฆ with the values filled into { } on the screen
revenue() - lines 123โ€“128
LineCodeWhat it does
123
def revenue():
๐Ÿงฉ Function DEFINES a function revenue(). Python only remembers it here - its body runs later, each time revenue() is called.
124
cur.execute("""SELECT r.rtype, COUNT(g.gid), SUM(g.total) FROM room r LEFT JOIN guest g
               ON r.rno = g.rno AND g.checkout IS NOT NULL GROUP BY rโ€ฆ
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
126
print(f"{'Type':<10}{'Stays':>6}{'Revenue':>14}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Type':<10}{'Stays':>6}{'Revenue':>14}" with the values filled into { } on the screen
127
for t, c, s in cur.fetchall():
๐Ÿ” Loop LOOP: takes each item of cur.fetchall() one-by-one into t, c, s and runs the indented block for it
128
print(f"{t:<10}{c:>6}{float(s or 0):>14,.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{t:<10}{c:>6}{float(s or 0):>14,.2f}" with the values filled into { } on the screen
occupancy() - lines 131โ€“134
LineCodeWhat it does
131
def occupancy():
๐Ÿงฉ Function DEFINES a function occupancy(). Python only remembers it here - its body runs later, each time occupancy() is called.
132
cur.execute("SELECT COUNT(*), SUM(status = 'Occupied') FROM room")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
133
n, occ = cur.fetchone()
๐Ÿฌ Database Brings the NEXT ONE row of the result as a tuple (None if no row is left); the result is stored in variables n, occ
134
print(f"Occupied {occ}/{n} rooms -> occupancy {int(occ) * 100 / n:.1f}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Occupied {occ}/{n} rooms -> occupancy {int(โ€ฆ with the values filled into { } on the screen
Q1. How are nights calculated?

date.fromisoformat() converts the strings to dates; (checkout - checkin).days gives the number of nights.

Q2. Which SQL statement changes room status?

UPDATE room SET status = 'Occupied' WHERE rno = %s (and 'Available' at check-out).

Q3. Why is a separate service table used?

One guest may have many service orders - a one-to-many relation that is summed with SUM(amount).

Q4. What does GROUP BY rtype give?

Revenue and number of stays for each room type.

Q5. What is the role of LEFT JOIN?

It keeps all rows of the left table even if there is no matching row on the right.

๐Ÿ“• Class XII Informatics Practices (065) โ€” 10 Data Projects 10 projects

01

School Result Analytics Dashboard

PYTHONPandas DataFramegroupbyMatplotlib charts (Practicals 5910)
๐Ÿ“ 98 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 92 output lines๐Ÿ“„ 25+ page report

Load class-wise/subject-wise marks into a DataFrame, compute averages, pass %, topper list, and plot bar/line charts comparing sections โ€” a genuine School MIS-style tool.

โœจ Features
  • DataFrame of 12 students x 5 subjects created from a dictionary
  • Calculated columns: Total, Percentage, Grade (apply with a function) and Result
  • groupby() for section-wise average and pass percentage
  • Topper of every subject with idxmax(); nlargest() merit list
  • Four charts: subject average bar, grade pie, section comparison and marks histogram
  • Result exported to result_analysis.csv
โ˜ฐ Main menu
1Show Result SheetComplete DataFrame with calculated columns
2Descriptive Statisticsdescribe() of all subjects
3Section-wise Analysisgroupby mean, count and pass %
4Subject Toppersidxmax() for each subject
5Merit Listnlargest(5, 'Total')
6Search StudentBoolean indexing by name
7ChartsSaves and shows 4 charts
8Export CSVto_csv() of the result sheet
0ExitEnds the program
๐ŸŽฏ Objectives
  • Create and display a DataFrame
  • Use groupby() and boolean filtering
  • Plot and save a bar chart with Matplotlib
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameName, Section, Eng, Maths, Phy, Chem, IP + calculated columns
SUBJlistSubject column names
grade()functionCBSE grade from percentage
secDataFrameResult of groupby('Section')
Why it matters: Directly usable by the school's own exam cell for real result analysis.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
# =====================================================================
#   SCHOOL RESULT ANALYTICS DASHBOARD  (Pandas + Matplotlib)
# =====================================================================
SUBJ = ["Eng", "Maths", "Phy", "Chem", "IP"]
data = {"Name": ["Amit", "Sara", "Rahul", "Priya", "Karan", "Neha", "Arjun", "Ishita", "Vikram", "Zoya", "Manav", "Divya"],
        "Section": ["A", "A", "B", "B", "A", "C", "C", "B", "A", "C", "B", "C"],
        "Eng":   [88, 92, 65, 78, 55, 81, 47, 90, 72, 85, 60, 74],
        "Maths": [95, 89, 58, 82, 30, 77, 41, 94, 68, 79, 52, 88],
        "Phy":   [84, 90, 62, 75, 38, 70, 35, 88, 66, 81, 57, 69],
        "Chem":  [80, 93, 60, 79, 44, 73, 39, 91, 64, 76, 49, 72],
        "IP":    [97, 96, 71, 88, 61, 90, 52, 98, 80, 93, 67, 85]}
df = pd.DataFrame(data, index=range(1, 13))


def grade(p):
    for cut, g in ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"), (41, "C2"), (33, "D")):
        if p >= cut:
            return g
    return "E"


df["Total"] = df[SUBJ].sum(axis=1)
df["Percent"] = (df["Total"] / 5).round(1)
df["Grade"] = df["Percent"].apply(grade)
df["Result"] = df[SUBJ].min(axis=1).apply(lambda m: "PASS" if m >= 33 else "COMPT")


def sheet():
    print(df)


def stats():
    print(df[SUBJ].describe().round(2))


def sections():
    sec = df.groupby("Section").agg(Students=("Name", "count"), Avg_Percent=("Percent", "mean"), Highest=("Total", "max"))
    sec["Pass_%"] = df[df["Result"] == "PASS"].groupby("Section")["Name"].count() / sec["Students"] * 100
    print(sec.round(2))
    print("\nBest section:", sec["Avg_Percent"].idxmax())


def toppers():
    for s in SUBJ:
        i = df[s].idxmax()
        print(f"{s:<6}: {df.loc[i, 'Name']:<8} ({df.loc[i, s]})")
    print("Overall topper:", df.loc[df["Total"].idxmax(), "Name"])


def merit():
    print(df.nlargest(5, "Total")[["Name", "Section", "Total", "Percent", "Grade"]])


def search():
    n = input("Enter name: ").strip().lower()
    r = df[df["Name"].str.lower() == n]
    print(r.T if not r.empty else "Not found.")


def charts():
    avg = df[SUBJ].mean()
    avg.plot(kind="bar", color=["#1565c0", "#2e7d32", "#ef6c00", "#6a1b9a", "#c62828"], title="Subject-wise Average Marks")
    plt.ylabel("Average marks"); plt.xticks(rotation=0); plt.ylim(0, 100); plt.tight_layout()
    plt.savefig("subject_avg.png"); plt.show()

    df["Grade"].value_counts().sort_index().plot(kind="pie", autopct="%1.0f%%", title="Grade Distribution")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("grade_pie.png"); plt.show()

    df.groupby("Section")[SUBJ].mean().T.plot(kind="bar", title="Section-wise Subject Average")
    plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()

    plt.hist(df["Percent"], bins=[30, 40, 50, 60, 70, 80, 90, 100], color="teal", edgecolor="black")
    plt.title("Percentage Histogram"); plt.xlabel("Percentage"); plt.ylabel("Students")
    plt.tight_layout(); plt.savefig("marks_hist.png"); plt.show()
    print("4 charts saved: subject_avg.png, grade_pie.png, section_compare.png, marks_hist.png")


def export():
    df.to_csv("result_analysis.csv", index_label="Roll")
    print("Saved result_analysis.csv ->", len(pd.read_csv("result_analysis.csv")), "rows")


menu = {"1": sheet, "2": stats, "3": sections, "4": toppers, "5": merit, "6": search, "7": charts, "8": export}
print("=" * 60)
print("SCHOOL RESULT ANALYTICS DASHBOARD".center(60))
print("=" * 60)
while True:
    print("\n1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Analysis complete.")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Create DataFrame and calculated columns
  3. Display menu and read choice
  4. Choice is Charts? → No: run the selected analysis
  5. Plot bar, pie, bar and histogram
  6. savefig() and show()
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Option 112 rows with Total, %, GradePASS
2Option 2count, mean, std, min, maxPASS
3Option 3Average of A, B, CPASS
4Option 4Topper per subjectPASS
5Option 5Top 5 by totalPASS
6Search 'priya'Her row shownPASS
7Search 'xyz''Not found'PASS
8Option 74 PNG filesPASS
9Option 8CSV createdPASS
โš  Limitations
  • Marks typed in the program (not read from school ERP)
  • Fixed 5 subjects
  • No term-wise comparison
  • Charts static
๐Ÿš€ Future scope
  • Read marks from Excel / Google Sheet
  • Term-1 vs Term-2 comparison
  • Report card PDF per student
  • Interactive dashboard with Plotly

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: SUBJ, data, df.
  3. 9 functions are defined (lines 19โ€“84) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
grade(p)19โ€“23Grademain program (menu)
sheet()32โ€“33Sheetmain program (menu)
stats()36โ€“37Statsmain program (menu)
sections()40โ€“44Sectionsmain program (menu)
toppers()47โ€“51Toppersmain program (menu)
merit()54โ€“55Meritmain program (menu)
search()58โ€“61Searchmain program (menu)
charts()64โ€“79Chartsmain program (menu)
export()82โ€“84Exportmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
๐Ÿ“Œ SCHOOL RESULT ANALYTICS DASHBOARD (Pandas + Matplotlib)
8
SUBJ = ["Eng", "Maths", "Phy", "Chem", "IP"]
๐Ÿงฎ Store / Calculate Stores a list ["Eng", "Maths", "Phy", "Chem", "IP"] in variable SUBJ
9
data = {"Name": ["Amit", "Sara", "Rahul", "Priya", "Karan", "Neha", "Arjun", "Ishita", "Vikram", "Zoya", "Manav", "Divya"],
        "Section": ["A", "A", "B"โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Name": ["Amit", "Sara", "Rahul", "Priya", "โ€ฆ in variable data
16
df = pd.DataFrame(data, index=range(1, 13))
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from data; the result is stored in variable df
26
df["Total"] = df[SUBJ].sum(axis=1)
๐Ÿงฎ Store / Calculate Adds up all values of df[SUBJ]; the result is put into df["Total"] (item "Total" of df)
27
df["Percent"] = (df["Total"] / 5).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of df["Total"] / 5 to 1 decimal places; the result is put into df["Percent"] (item "Percent" of df)
28
df["Grade"] = df["Percent"].apply(grade)
๐Ÿงฎ Store / Calculate Applies grade on every value/row of df["Percent"]; the result is put into df["Grade"] (item "Grade" of df)
29
df["Result"] = df[SUBJ].min(axis=1).apply(lambda m: "PASS" if m >= 33 else "COMPT")
๐Ÿงฎ Store / Calculate Applies lambda m: "PASS" if m >= 33 else "COMPT" on every value/row of df[SUBJ].min(axis=1); the result is put into df["Result"] (item "Result" of df)
87
menu = {"1": sheet, "2": stats, "3": sections, "4": toppers, "5": merit, "6": search, "7": charts, "8": export}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": sheet, "2": stats, "3": sections, "4": โ€ฆ in variable menu
88
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
89
print("SCHOOL RESULT ANALYTICS DASHBOARD".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "SCHOOL RESULT ANALYTICS DASHBOARD".center(60) on the screen
90
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
91
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
92
print("\n1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Result Sheet 2.Statistics 3.Secโ€ฆ" on the screen
93
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
94
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
95
print("Analysis complete.")
๐Ÿ–ฅ๏ธ Output Displays the text "Analysis complete." on the screen
96
break
๐Ÿ” Loop BREAK - leaves the loop immediately
97
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: grade() ร—12
    shows: SCHOOL RESULT ANALYTICS DASHBOARD (+1 more lines)
  2. You type 1 at Enter choice:
    runs: sheet()
    shows: Name Section Eng Maths Phy Chem IP Total Percent Grade Result (+13 more lines)
  3. You type 2 at Enter choice:
    runs: stats()
    shows: Eng Maths Phy Chem IP (+9 more lines)
  4. You type 3 at Enter choice:
    runs: sections()
    shows: Students Avg_Percent Highest Pass_% (+6 more lines)
  5. You type 4 at Enter choice:
    runs: toppers()
    shows: Eng : Sara (92) (+6 more lines)
  6. You type 5 at Enter choice:
    runs: merit()
    shows: Name Section Total Percent Grade (+6 more lines)
  7. You type 6 at Enter choice:
    runs: search()
  8. You type priya at Enter name:
    shows: 4 (+12 more lines)
  9. You type 6 at Enter choice:
    runs: search()
  10. You type xyz at Enter name:
    shows: Not found. (+1 more lines)
  11. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+5 more lines)
  12. You type 8 at Enter choice:
    runs: export()
    shows: Saved result_analysis.csv -> 12 rows (+1 more lines)
  13. You type 0 at Enter choice:
    shows: Analysis complete.
โ‘ค Inside each function - line by line
grade() - lines 19โ€“23
LineCodeWhat it does
19
def grade(p):
๐Ÿงฉ Function DEFINES a function grade(p). Python only remembers it here - its body runs later, each time grade() is called.
20
for cut, g in ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"), (41, "C2"), (33, "D")):
๐Ÿ” Loop LOOP: takes each item of ((91, "A1"), (81, "A2"), (71, "B1"), (61, "B2โ€ฆ one-by-one into cut, g and runs the indented block for it
21
if p >= cut:
๐Ÿ”€ Decision CHECKS whether p is greater than or equal to cut. If True, the indented lines below run; otherwise they are skipped
22
return g
๐Ÿงฉ Function Sends back (returns) the value of g to the line that called the function
23
return "E"
๐Ÿงฉ Function Sends back (returns) the text "E" to the line that called the function
sheet() - lines 32โ€“33
LineCodeWhat it does
32
def sheet():
๐Ÿงฉ Function DEFINES a function sheet(). Python only remembers it here - its body runs later, each time sheet() is called.
33
print(df)
๐Ÿ–ฅ๏ธ Output Displays the value of df on the screen
stats() - lines 36โ€“37
LineCodeWhat it does
36
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
37
print(df[SUBJ].describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of df[SUBJ].describe().round(2) on the screen
sections() - lines 40โ€“44
LineCodeWhat it does
40
def sections():
๐Ÿงฉ Function DEFINES a function sections(). Python only remembers it here - its body runs later, each time sections() is called.
41
sec = df.groupby("Section").agg(Students=("Name", "count"), Avg_Percent=("Percent", "mean"), Highest=("Total", "max"))
๐Ÿ“ฆ Library / Data Calculates the given summary values for every group; the result is stored in variable sec
42
sec["Pass_%"] = df[df["Result"] == "PASS"].groupby("Section")["Name"].count() / sec["Students"] * 100
๐Ÿงฎ Store / Calculate Puts the value of df[df["Result"] == "PASS"].groupby("Section")โ€ฆ (calculated using ร—) into sec["Pass_%"] (item "Pass_%" of sec)
43
print(sec.round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of sec.round(2) on the screen
44
print("\nBest section:", sec["Avg_Percent"].idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Best section:", then the value of sec["Avg_Percent"].idxmax() on the screen
toppers() - lines 47โ€“51
LineCodeWhat it does
47
def toppers():
๐Ÿงฉ Function DEFINES a function toppers(). Python only remembers it here - its body runs later, each time toppers() is called.
48
for s in SUBJ:
๐Ÿ” Loop LOOP: takes each item of SUBJ one-by-one into s and runs the indented block for it
49
i = df[s].idxmax()
๐Ÿงฎ Store / Calculate Gives the label (index) of the largest value of df[s]; the result is stored in variable i
50
print(f"{s:<6}: {df.loc[i, 'Name']:<8} ({df.loc[i, s]})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s:<6}: {df.loc[i, 'Name']:<8} ({df.loc[i, โ€ฆ with the values filled into { } on the screen
51
print("Overall topper:", df.loc[df["Total"].idxmax(), "Name"])
๐Ÿ–ฅ๏ธ Output Displays the text "Overall topper:", then the value of df.loc[df["Total"].idxmax(), "Name"] on the screen
merit() - lines 54โ€“55
LineCodeWhat it does
54
def merit():
๐Ÿงฉ Function DEFINES a function merit(). Python only remembers it here - its body runs later, each time merit() is called.
55
print(df.nlargest(5, "Total")[["Name", "Section", "Total", "Percent", "Grade"]])
๐Ÿ–ฅ๏ธ Output Displays the value of df.nlargest(5, "Total")[["Name", "Section", "โ€ฆ on the screen
search() - lines 58โ€“61
LineCodeWhat it does
58
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
59
n = input("Enter name: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable n
60
r = df[df["Name"].str.lower() == n]
๐Ÿงฎ Store / Calculate Stores the item df[df["Name"].str.lower() == n] in variable r
61
print(r.T if not r.empty else "Not found.")
๐Ÿ–ฅ๏ธ Output Displays the value of r.T if not r.empty else "Not found." on the screen
charts() - lines 64โ€“79
LineCodeWhat it does
64
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
65
avg = df[SUBJ].mean()
๐Ÿงฎ Store / Calculate Finds the average (mean) of df[SUBJ]; the result is stored in variable avg
66
avg.plot(kind="bar", color=["#1565c0", "#2e7d32", "#ef6c00", "#6a1b9a", "#c62828"], title="Subject-wise Average Marks")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
67
plt.ylabel("Average marks"); plt.xticks(rotation=0); plt.ylim(0, 100); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Writes "Average marks" as the label of the Y-axis
67
plt.ylabel("Average marks"); plt.xticks(rotation=0); plt.ylim(0, 100); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
67
plt.ylabel("Average marks"); plt.xticks(rotation=0); plt.ylim(0, 100); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Sets the range of the Y-axis
67
plt.ylabel("Average marks"); plt.xticks(rotation=0); plt.ylim(0, 100); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
68
plt.savefig("subject_avg.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "subject_avg.png"
68
plt.savefig("subject_avg.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
70
df["Grade"].value_counts().sort_index().plot(kind="pie", autopct="%1.0f%%", title="Grade Distribution")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
71
plt.ylabel(""); plt.tight_layout(); plt.savefig("grade_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
71
plt.ylabel(""); plt.tight_layout(); plt.savefig("grade_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
71
plt.ylabel(""); plt.tight_layout(); plt.savefig("grade_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "grade_pie.png"
71
plt.ylabel(""); plt.tight_layout(); plt.savefig("grade_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
73
df.groupby("Section")[SUBJ].mean().T.plot(kind="bar", title="Section-wise Subject Average")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
74
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Average" as the label of the Y-axis
74
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
74
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
74
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "section_compare.png"
74
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
76
plt.hist(df["Percent"], bins=[30, 40, 50, 60, 70, 80, 90, 100], color="teal", edgecolor="black")
๐Ÿ–ฅ๏ธ Output Draws a histogram of df["Percent"]
77
plt.title("Percentage Histogram"); plt.xlabel("Percentage"); plt.ylabel("Students")
๐Ÿ–ฅ๏ธ Output Writes "Percentage Histogram" as the title of the chart
77
plt.title("Percentage Histogram"); plt.xlabel("Percentage"); plt.ylabel("Students")
๐Ÿ–ฅ๏ธ Output Writes "Percentage" as the label of the X-axis
77
plt.title("Percentage Histogram"); plt.xlabel("Percentage"); plt.ylabel("Students")
๐Ÿ–ฅ๏ธ Output Writes "Students" as the label of the Y-axis
78
plt.tight_layout(); plt.savefig("marks_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
78
plt.tight_layout(); plt.savefig("marks_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "marks_hist.png"
78
plt.tight_layout(); plt.savefig("marks_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
79
print("4 charts saved: subject_avg.png, grade_pie.png, section_compare.png, marks_hist.png")
๐Ÿ–ฅ๏ธ Output Displays the text "4 charts saved: subject_avg.png, โ€ฆ" on the screen
export() - lines 82โ€“84
LineCodeWhat it does
82
def export():
๐Ÿงฉ Function DEFINES a function export(). Python only remembers it here - its body runs later, each time export() is called.
83
df.to_csv("result_analysis.csv", index_label="Roll")
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "result_analysis.csv"
84
print("Saved result_analysis.csv ->", len(pd.read_csv("result_analysis.csv")), "rows")
๐Ÿ–ฅ๏ธ Output Displays the text "Saved result_analysis.csv ->", then the value of len(pd.read_csv("result_analysis.csv")), then the text "rows" on the screen
Q1. What does groupby() do?

It splits the DataFrame into groups by a column (Section) so aggregate functions like mean() are calculated for each group.

Q2. How is a calculated column added?

By assigning an expression, e.g. df['Total'] = df[SUBJ].sum(axis=1).

Q3. What is axis=1?

Operation is done across columns (row-wise), so each student's marks are added.

Q4. What does idxmax() return?

The index label of the maximum value - used with loc to get the topper's name.

Q5. Which function saves a chart?

plt.savefig('file.png') - must be called before plt.show().

02

Household / Shop Expenditure Analyzer

PYTHONDataFrame filteringCSV import/exportvisualisation (Practicals 7818)
๐Ÿ“ 131 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 130 output lines๐Ÿ“„ 25+ page report

Import a CSV of monthly expenses, filter by category, remove duplicate entries, and visualise spending trend with a bar/pie chart โ€” helping a family or small shop track expenses.

โœจ Features
  • Expense records (date, category, item, amount, mode) in a DataFrame and expenses.csv
  • Add new expense with validation; delete by index
  • Month-wise and category-wise totals with groupby and pivot_table
  • Budget vs actual comparison with over-budget warning
  • Filter by category / payment mode / amount range
  • Pie, line and grouped bar charts
โ˜ฐ Main menu
1View ExpensesReads expenses.csv
2Add ExpenseAppends a row and saves
3Delete Expensedrop() by index
4Category Summarygroupby + percentage share
5Monthly Pivotpivot_table month x category
6Budget CheckCompares with monthly budget
7FilterBy category / mode / minimum amount
8ChartsPie, trend and budget charts
0ExitSaves and exits
๐ŸŽฏ Objectives
  • Read and write CSV files with Pandas
  • Clean data using drop_duplicates()
  • Visualise proportions with a pie chart
๐Ÿ“š Data dictionary
NameTypePurpose
expDataFrameDate, Category, Item, Amount, Mode
expenses.csvCSV filePermanent storage
BUDGETdictCategory -> monthly budget
MonthcolumnDerived with dt.strftime('%b')
Why it matters: Reusable template โ€” just swap in real expense CSV data.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import os
# =====================================================================
#   HOUSEHOLD / SHOP EXPENDITURE ANALYZER  (Pandas + CSV + Matplotlib)
# =====================================================================
FILE = "expenses.csv"
CATS = ["Grocery", "Bills", "Education", "Transport", "Health", "Entertainment"]
BUDGET = {"Grocery": 8000, "Bills": 5000, "Education": 6000, "Transport": 3000, "Health": 2000, "Entertainment": 2500}
rows = [("2026-01-03", "Grocery", "Monthly ration", 5200, "UPI"), ("2026-01-05", "Bills", "Electricity", 2350, "UPI"),
        ("2026-01-08", "Education", "School fee", 4500, "Netbanking"), ("2026-01-12", "Transport", "Petrol", 2100, "Card"),
        ("2026-01-20", "Entertainment", "Movie", 900, "UPI"), ("2026-01-25", "Health", "Medicines", 650, "Cash"),
        ("2026-02-02", "Grocery", "Monthly ration", 5600, "UPI"), ("2026-02-06", "Bills", "Mobile + WiFi", 1450, "UPI"),
        ("2026-02-10", "Bills", "Electricity", 2780, "UPI"), ("2026-02-14", "Entertainment", "Dinner out", 2400, "Card"),
        ("2026-02-18", "Transport", "Petrol", 2600, "Card"), ("2026-02-22", "Education", "Books", 1800, "Cash"),
        ("2026-03-01", "Grocery", "Monthly ration", 6100, "UPI"), ("2026-03-04", "Health", "Doctor visit", 1500, "Cash"),
        ("2026-03-09", "Bills", "Electricity", 3120, "UPI"), ("2026-03-15", "Transport", "Car service", 3400, "Card"),
        ("2026-03-21", "Entertainment", "Holi party", 1800, "Cash"), ("2026-03-26", "Education", "Coaching", 3500, "Netbanking")]
pd.DataFrame(rows, columns=["Date", "Category", "Item", "Amount", "Mode"]).to_csv(FILE, index=False)


def load():
    e = pd.read_csv(FILE, parse_dates=["Date"])
    e["Month"] = e["Date"].dt.strftime("%b")
    return e


def view():
    e = load()
    print(e)
    print(f"\nRecords: {len(e)}  |  Total spent: Rs. {e['Amount'].sum():,}")


def add():
    d = input("Date (yyyy-mm-dd): ").strip()
    c = input("Category: ").strip().title()
    item = input("Item: ").strip()
    amt = float(input("Amount: "))
    mode = input("Mode (UPI/Cash/Card/Netbanking): ").strip()
    if amt <= 0 or c not in CATS:
        print("Invalid amount or category. Not saved.")
        return
    e = pd.read_csv(FILE)
    e = pd.concat([e, pd.DataFrame([[d, c, item, amt, mode]], columns=e.columns)], ignore_index=True)
    e.to_csv(FILE, index=False)
    print("Expense saved. Total records:", len(e))


def delete():
    e = pd.read_csv(FILE)
    i = int(input("Index to delete: "))
    if i in e.index:
        print("Deleted:", e.loc[i, "Item"], e.loc[i, "Amount"])
        e.drop(i).to_csv(FILE, index=False)
    else:
        print("No such index.")


def summary():
    e = load()
    s = e.groupby("Category")["Amount"].agg(["count", "sum", "mean"]).sort_values("sum", ascending=False)
    s["Share_%"] = (s["sum"] / s["sum"].sum() * 100).round(1)
    print(s.round(1))
    print("\nHighest spending:", s.index[0])


def pivot():
    e = load()
    p = e.pivot_table(index="Month", columns="Category", values="Amount", aggfunc="sum", fill_value=0)
    p = p.reindex(["Jan", "Feb", "Mar"])
    p["TOTAL"] = p.sum(axis=1)
    print(p)
    print("\nMonth-on-month change in total (%):")
    print(p["TOTAL"].pct_change().mul(100).round(1).fillna(0))


def budget():
    e = load()
    avg = e.groupby("Category")["Amount"].sum() / e["Month"].nunique()
    b = pd.DataFrame({"Budget": pd.Series(BUDGET), "Avg_Spent": avg.round(0)})
    b["Status"] = b.apply(lambda r: "OVER by Rs. %d" % (r.Avg_Spent - r.Budget) if r.Avg_Spent > r.Budget else "Within", axis=1)
    print(b)


def filt():
    e = load()
    by = input("Filter by (category/mode/amount): ").strip().lower()
    v = input("Value: ").strip()
    if by == "amount":
        r = e[e["Amount"] >= float(v)]
    elif by == "mode":
        r = e[e["Mode"].str.lower() == v.lower()]
    else:
        r = e[e["Category"].str.lower() == v.lower()]
    print(r[["Date", "Category", "Item", "Amount", "Mode"]])
    print("Rows:", len(r), "| Sum: Rs.", r["Amount"].sum())


def charts():
    e = load()
    e.groupby("Category")["Amount"].sum().plot(kind="pie", autopct="%1.1f%%", startangle=90, title="Category-wise Expenditure")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("expense_pie.png"); plt.show()
    m = e.groupby("Month", sort=False)["Amount"].sum()
    plt.plot(m.index, m.values, marker="o", color="crimson", linewidth=2)
    for x, y in zip(m.index, m.values):
        plt.text(x, y + 200, f"{y:,.0f}", ha="center")
    plt.title("Monthly Expenditure Trend"); plt.ylabel("Rs."); plt.grid(alpha=.3)
    plt.tight_layout(); plt.savefig("monthly_trend.png"); plt.show()
    avg = e.groupby("Category")["Amount"].sum() / e["Month"].nunique()
    pd.DataFrame({"Budget": pd.Series(BUDGET), "Average spent": avg}).plot(kind="bar", color=["#90caf9", "#ef6c00"], title="Budget vs Actual (per month)")
    plt.xticks(rotation=20); plt.tight_layout(); plt.savefig("budget_vs_actual.png"); plt.show()
    print("Charts saved: expense_pie.png, monthly_trend.png, budget_vs_actual.png")


menu = {"1": view, "2": add, "3": delete, "4": summary, "5": pivot, "6": budget, "7": filt, "8": charts}
print("=" * 60)
print("HOUSEHOLD EXPENDITURE ANALYZER".center(60))
print("=" * 60)
while True:
    print("\n1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Data saved in", FILE)
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Invalid number.")

        
  1. Start
  2. Create / read expenses.csv into DataFrame
  3. Display menu and read choice
  4. Choice is Add? → No: run selected analysis
  5. Read date, category, item, amount, mode
  6. Amount > 0 and category valid? → No: show error
  7. Append row with pd.concat and to_csv()
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1ViewAll rowsPASS
2Add Rs. 450 GroceryRow added, file savedPASS
3Add amount -5RejectedPASS
4Delete index 3Row removedPASS
5Category summaryTotals and % sharePASS
6Monthly pivotMonth x category tablePASS
7Budget checkOver-budget categories flaggedPASS
8Filter Mode = UPIOnly UPI rowsPASS
9Charts3 PNG filesPASS
โš  Limitations
  • Manual entry of expenses
  • Single family / shop
  • No bank statement import
  • Budget fixed in program
๐Ÿš€ Future scope
  • Import bank / UPI statement CSV
  • Savings goal tracker
  • Mobile app with the same logic
  • Forecast next month's expense

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, os - file and folder operations are loaded.
  2. Global variables / constants are created: FILE, CATS, BUDGET, rows.
  3. 9 functions are defined (lines 24โ€“114) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
load()24โ€“27Loadview(), summary(), pivot(), budget()
view()30โ€“33Viewmain program (menu)
add()36โ€“48Addmain program (menu)
delete()51โ€“58Deletemain program (menu)
summary()61โ€“66Summarymain program (menu)
pivot()69โ€“76Pivotmain program (menu)
budget()79โ€“84Budgetmain program (menu)
filt()87โ€“98Filtmain program (menu)
charts()101โ€“114Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import os
๐Ÿ“ฆ Library / Data Loads the module os - file and folder operations
๐Ÿ“Œ HOUSEHOLD / SHOP EXPENDITURE ANALYZER (Pandas + CSV + Matplotlib)
9
FILE = "expenses.csv"
๐Ÿงฎ Store / Calculate Stores the text "expenses.csv" in variable FILE
10
CATS = ["Grocery", "Bills", "Education", "Transport", "Health", "Entertainment"]
๐Ÿงฎ Store / Calculate Stores a list ["Grocery", "Bills", "Education", "Transport"โ€ฆ in variable CATS
11
BUDGET = {"Grocery": 8000, "Bills": 5000, "Education": 6000, "Transport": 3000, "Health": 2000, "Entertainment": 2500}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Grocery": 8000, "Bills": 5000, "Education":โ€ฆ in variable BUDGET
12
rows = [("2026-01-03", "Grocery", "Monthly ration", 5200, "UPI"), ("2026-01-05", "Bills", "Electricity", 2350, "UPI"),
        ("2026-01-08", "Education", "Sโ€ฆ
๐Ÿงฎ Store / Calculate Stores a list [("2026-01-03", "Grocery", "Monthly ration", โ€ฆ in variable rows
21
pd.DataFrame(rows, columns=["Date", "Category", "Item", "Amount", "Mode"]).to_csv(FILE, index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file FILE
117
menu = {"1": view, "2": add, "3": delete, "4": summary, "5": pivot, "6": budget, "7": filt, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": add, "3": delete, "4": summaโ€ฆ in variable menu
118
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
119
print("HOUSEHOLD EXPENDITURE ANALYZER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "HOUSEHOLD EXPENDITURE ANALYZER".center(60) on the screen
120
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
121
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
122
print("\n1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Add 3.Delete 4.Summary 5โ€ฆ" on the screen
123
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
124
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
125
print("Data saved in", FILE)
๐Ÿ–ฅ๏ธ Output Displays the text "Data saved in", then the value of FILE on the screen
126
break
๐Ÿ” Loop BREAK - leaves the loop immediately
127
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
128
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
129
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
130
print("Invalid number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid number." on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HOUSEHOLD EXPENDITURE ANALYZER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: view() โ†’ load()
    shows: Date Category Item Amount Mode Month (+20 more lines)
  3. You type 2 at Enter choice:
    runs: add()
  4. You type 2026-03-28 at Date (yyyy-mm-dd):
  5. You type Grocery at Category:
  6. You type Fruits & vegetables at Item:
  7. You type 450 at Amount:
  8. You type UPI at Mode (UPI/Cash/Card/Netbanking):
    shows: Expense saved. Total records: 19 (+1 more lines)
  9. You type 2 at Enter choice:
    runs: add()
  10. You type 2026-03-29 at Date (yyyy-mm-dd):
  11. You type Food at Category:
  12. You type Pizza at Item:
  13. You type -5 at Amount:
  14. You type Cash at Mode (UPI/Cash/Card/Netbanking):
    shows: Invalid amount or category. Not saved. (+1 more lines)
  15. You type 3 at Enter choice:
    runs: delete()
  16. You type 3 at Index to delete:
    shows: Deleted: Petrol 2100.0 (+1 more lines)
  17. You type 4 at Enter choice:
    runs: summary() โ†’ load()
    shows: count sum mean Share_% (+9 more lines)
  18. You type 5 at Enter choice:
    runs: pivot() โ†’ load()
    shows: Category Bills Education Entertainment Grocery Health Transport TOTAL (+11 more lines)
  19. You type 6 at Enter choice:
    runs: budget() โ†’ load()
    shows: Budget Avg_Spent Status (+7 more lines)
  20. You type 7 at Enter choice:
    runs: filt() โ†’ load()
  21. You type mode at Filter by (category/mode/amount):
  22. You type UPI at Value:
    shows: Date Category Item Amount Mode (+11 more lines)
  23. You type 7 at Enter choice:
    runs: filt() โ†’ load()
  24. You type amount at Filter by (category/mode/amount):
  25. You type 2000 at Value:
    shows: Date Category Item Amount Mode (+13 more lines)
  26. You type 8 at Enter choice:
    runs: charts() โ†’ load()
    shows: [chart is drawn] (+4 more lines)
  27. You type 0 at Enter choice:
    shows: Data saved in expenses.csv
โ‘ค Inside each function - line by line
load() - lines 24โ€“27
LineCodeWhat it does
24
def load():
๐Ÿงฉ Function DEFINES a function load(). Python only remembers it here - its body runs later, each time load() is called.
25
e = pd.read_csv(FILE, parse_dates=["Date"])
๐Ÿ“ฆ Library / Data Reads the CSV file FILE into a DataFrame (table); the result is stored in variable e
26
e["Month"] = e["Date"].dt.strftime("%b")
๐Ÿงฎ Store / Calculate Formats the date as text; the result is put into e["Month"] (item "Month" of e)
27
return e
๐Ÿงฉ Function Sends back (returns) the value of e to the line that called the function
view() - lines 30โ€“33
LineCodeWhat it does
30
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
31
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
32
print(e)
๐Ÿ–ฅ๏ธ Output Displays the value of e on the screen
33
print(f"\nRecords: {len(e)}  |  Total spent: Rs. {e['Amount'].sum():,}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nRecords: {len(e)} | Total spent: Rs. {e['โ€ฆ with the values filled into { } on the screen
add() - lines 36โ€“48
LineCodeWhat it does
36
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
37
d = input("Date (yyyy-mm-dd): ").strip()
โŒจ๏ธ Input Shows "Date (yyyy-mm-dd): ", reads the typed text, removes extra spaces (strip) and stores it in variable d
38
c = input("Category: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable c
39
item = input("Item: ").strip()
โŒจ๏ธ Input Shows "Item: ", reads the typed text, removes extra spaces (strip) and stores it in variable item
40
amt = float(input("Amount: "))
โŒจ๏ธ Input Shows "Amount: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable amt
41
mode = input("Mode (UPI/Cash/Card/Netbanking): ").strip()
โŒจ๏ธ Input Shows "Mode (UPI/Cash/Card/Netbanking): ", reads the typed text, removes extra spaces (strip) and stores it in variable mode
42
if amt <= 0 or c not in CATS:
๐Ÿ”€ Decision CHECKS whether (amt is less than or equal to 0 OR c is not present in CATS). If True, the indented lines below run; otherwise they are skipped
43
print("Invalid amount or category. Not saved.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid amount or category. Not sโ€ฆ" on the screen
44
return
๐Ÿงฉ Function Ends the function and goes back to the caller
45
e = pd.read_csv(FILE)
๐Ÿ“ฆ Library / Data Reads the CSV file FILE into a DataFrame (table); the result is stored in variable e
46
e = pd.concat([e, pd.DataFrame([[d, c, item, amt, mode]], columns=e.columns)], ignore_index=True)
๐Ÿ“ฆ Library / Data Joins DataFrames one below the other; the result is stored in variable e
47
e.to_csv(FILE, index=False)
๐Ÿงฎ Store / Calculate Saves the DataFrame into CSV file FILE
48
print("Expense saved. Total records:", len(e))
๐Ÿ–ฅ๏ธ Output Displays the text "Expense saved. Total records:", then the value of len(e) on the screen
delete() - lines 51โ€“58
LineCodeWhat it does
51
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
52
e = pd.read_csv(FILE)
๐Ÿ“ฆ Library / Data Reads the CSV file FILE into a DataFrame (table); the result is stored in variable e
53
i = int(input("Index to delete: "))
โŒจ๏ธ Input Shows "Index to delete: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable i
54
if i in e.index:
๐Ÿ”€ Decision CHECKS whether i is present in e.index. If True, the indented lines below run; otherwise Python jumps to the elif/else part
55
print("Deleted:", e.loc[i, "Item"], e.loc[i, "Amount"])
๐Ÿ–ฅ๏ธ Output Displays the text "Deleted:", then the value of e.loc[i, "Item"], then the value of e.loc[i, "Amount"] on the screen
56
e.drop(i).to_csv(FILE, index=False)
๐Ÿงฎ Store / Calculate Saves the DataFrame into CSV file FILE
57
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
58
print("No such index.")
๐Ÿ–ฅ๏ธ Output Displays the text "No such index." on the screen
summary() - lines 61โ€“66
LineCodeWhat it does
61
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
62
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
63
s = e.groupby("Category")["Amount"].agg(["count", "sum", "mean"]).sort_values("sum", ascending=False)
๐Ÿงฎ Store / Calculate Sorts e.groupby("Category")["Amount"].agg(["count",โ€ฆ by "sum" in descending order; the result is stored in variable s
64
s["Share_%"] = (s["sum"] / s["sum"].sum() * 100).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of s["sum"] / s["sum"].sum() * 100 to 1 decimal places; the result is put into s["Share_%"] (item "Share_%" of s)
65
print(s.round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of s.round(1) on the screen
66
print("\nHighest spending:", s.index[0])
๐Ÿ–ฅ๏ธ Output Displays the text "Highest spending:", then the value of s.index[0] on the screen
pivot() - lines 69โ€“76
LineCodeWhat it does
69
def pivot():
๐Ÿงฉ Function DEFINES a function pivot(). Python only remembers it here - its body runs later, each time pivot() is called.
70
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
71
p = e.pivot_table(index="Month", columns="Category", values="Amount", aggfunc="sum", fill_value=0)
๐Ÿงฎ Store / Calculate Makes a summary (pivot) table from e; the result is stored in variable p
72
p = p.reindex(["Jan", "Feb", "Mar"])
๐Ÿงฎ Store / Calculate Arranges p in a new order of labels; the result is stored in variable p
73
p["TOTAL"] = p.sum(axis=1)
๐Ÿงฎ Store / Calculate Adds up all values of p; the result is put into p["TOTAL"] (item "TOTAL" of p)
74
print(p)
๐Ÿ–ฅ๏ธ Output Displays the value of p on the screen
75
print("\nMonth-on-month change in total (%):")
๐Ÿ–ฅ๏ธ Output Displays the text "Month-on-month change in total (%โ€ฆ" on the screen
76
print(p["TOTAL"].pct_change().mul(100).round(1).fillna(0))
๐Ÿ–ฅ๏ธ Output Displays the value of p["TOTAL"].pct_change().mul(100).round(1).filโ€ฆ on the screen
budget() - lines 79โ€“84
LineCodeWhat it does
79
def budget():
๐Ÿงฉ Function DEFINES a function budget(). Python only remembers it here - its body runs later, each time budget() is called.
80
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
81
avg = e.groupby("Category")["Amount"].sum() / e["Month"].nunique()
๐Ÿงฎ Store / Calculate Stores the value of e.groupby("Category")["Amount"].sum() / e["Moโ€ฆ (calculated using รท) in variable avg
82
b = pd.DataFrame({"Budget": pd.Series(BUDGET), "Avg_Spent": avg.round(0)})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Budget": pd.Series(BUDGET), "Avg_Spent": avโ€ฆ; the result is stored in variable b
83
b["Status"] = b.apply(lambda r: "OVER by Rs. %d" % (r.Avg_Spent - r.Budget) if r.Avg_Spent > r.Budget else "Within", axis=1)
๐Ÿงฎ Store / Calculate Applies lambda r: "OVER by Rs. %d" % (r.Avg_Spent - rโ€ฆ on every value/row of b; the result is put into b["Status"] (item "Status" of b)
84
print(b)
๐Ÿ–ฅ๏ธ Output Displays the value of b on the screen
filt() - lines 87โ€“98
LineCodeWhat it does
87
def filt():
๐Ÿงฉ Function DEFINES a function filt(). Python only remembers it here - its body runs later, each time filt() is called.
88
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
89
by = input("Filter by (category/mode/amount): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable by
90
v = input("Value: ").strip()
โŒจ๏ธ Input Shows "Value: ", reads the typed text, removes extra spaces (strip) and stores it in variable v
91
if by == "amount":
๐Ÿ”€ Decision CHECKS whether by is equal to "amount". If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
r = e[e["Amount"] >= float(v)]
๐Ÿงฎ Store / Calculate Stores the item e[e["Amount"] >= float(v)] in variable r
93
elif by == "mode":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether by is equal to "mode"
94
r = e[e["Mode"].str.lower() == v.lower()]
๐Ÿงฎ Store / Calculate Stores the item e[e["Mode"].str.lower() == v.lower()] in variable r
95
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
96
r = e[e["Category"].str.lower() == v.lower()]
๐Ÿงฎ Store / Calculate Stores the item e[e["Category"].str.lower() == v.lower()] in variable r
97
print(r[["Date", "Category", "Item", "Amount", "Mode"]])
๐Ÿ–ฅ๏ธ Output Displays the value of r[["Date", "Category", "Item", "Amount", "Modโ€ฆ on the screen
98
print("Rows:", len(r), "| Sum: Rs.", r["Amount"].sum())
๐Ÿ–ฅ๏ธ Output Displays the text "Rows:", then the value of len(r), then the text "| Sum: Rs.", then the value of r["Amount"].sum() on the screen
charts() - lines 101โ€“114
LineCodeWhat it does
101
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
102
e = load()
๐Ÿงฎ Store / Calculate Calls our own function load(); the result is stored in variable e
103
e.groupby("Category")["Amount"].sum().plot(kind="pie", autopct="%1.1f%%", startangle=90, title="Category-wise Expenditure")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
104
plt.ylabel(""); plt.tight_layout(); plt.savefig("expense_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
104
plt.ylabel(""); plt.tight_layout(); plt.savefig("expense_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
104
plt.ylabel(""); plt.tight_layout(); plt.savefig("expense_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "expense_pie.png"
104
plt.ylabel(""); plt.tight_layout(); plt.savefig("expense_pie.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
105
m = e.groupby("Month", sort=False)["Amount"].sum()
๐Ÿงฎ Store / Calculate Adds up all values of e.groupby("Month", sort=False)["Amount"]; the result is stored in variable m
106
plt.plot(m.index, m.values, marker="o", color="crimson", linewidth=2)
๐Ÿ–ฅ๏ธ Output Draws a line chart of m.index, m.values
107
for x, y in zip(m.index, m.values):
๐Ÿ” Loop LOOP that walks through m.index, m.values together; x, y get one item from each
108
plt.text(x, y + 200, f"{y:,.0f}", ha="center")
๐Ÿ–ฅ๏ธ Output Writes text on the chart
109
plt.title("Monthly Expenditure Trend"); plt.ylabel("Rs."); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Monthly Expenditure Trend" as the title of the chart
109
plt.title("Monthly Expenditure Trend"); plt.ylabel("Rs."); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Rs." as the label of the Y-axis
109
plt.title("Monthly Expenditure Trend"); plt.ylabel("Rs."); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
110
plt.tight_layout(); plt.savefig("monthly_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
110
plt.tight_layout(); plt.savefig("monthly_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "monthly_trend.png"
110
plt.tight_layout(); plt.savefig("monthly_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
111
avg = e.groupby("Category")["Amount"].sum() / e["Month"].nunique()
๐Ÿงฎ Store / Calculate Stores the value of e.groupby("Category")["Amount"].sum() / e["Moโ€ฆ (calculated using รท) in variable avg
112
pd.DataFrame({"Budget": pd.Series(BUDGET), "Average spent": avg}).plot(kind="bar", color=["#90caf9", "#ef6c00"], title="Budget vs Actual (per month)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
113
plt.xticks(rotation=20); plt.tight_layout(); plt.savefig("budget_vs_actual.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
113
plt.xticks(rotation=20); plt.tight_layout(); plt.savefig("budget_vs_actual.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
113
plt.xticks(rotation=20); plt.tight_layout(); plt.savefig("budget_vs_actual.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "budget_vs_actual.png"
113
plt.xticks(rotation=20); plt.tight_layout(); plt.savefig("budget_vs_actual.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
114
print("Charts saved: expense_pie.png, monthly_trend.png, budget_vs_actual.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: expense_pie.png, moโ€ฆ" on the screen
Q1. How is a new row added to a DataFrame?

Create a one-row DataFrame and join with pd.concat([exp, new], ignore_index=True).

Q2. What does pivot_table() do?

It reshapes data into a summary table, here months as rows, categories as columns and sum of Amount as values.

Q3. How do you extract the month from a date column?

Convert with pd.to_datetime() and use .dt.month or .dt.strftime('%b').

Q4. What is the use of drop()?

Removes rows (axis=0) or columns (axis=1) by label.

Q5. Why is index=False used in to_csv()?

So the row index is not written as an extra column in the CSV file.

03

Open Government Data Explorer

PYTHONData from data.gov.inaggregationMatplotlib (Practical 11)
๐Ÿ“ 96 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 118 output lines๐Ÿ“„ 25+ page report

Download a real dataset (e.g. literacy rate or population by state) from data.gov.in, clean it with pandas, summarise with describe(), and plot comparative charts across states/years.

โœจ Features
  • State-wise Census 2011 indicators (literacy, male / female literacy, sex ratio, population) as in data.gov.in open data
  • Data saved to and read back from census_data.csv
  • Ranking of states, top / bottom 5 with nlargest / nsmallest
  • Gender gap in literacy (calculated column) and region-wise averages with groupby
  • Correlation between literacy and sex ratio
  • Horizontal bar, grouped bar and scatter charts
โ˜ฐ Main menu
1View DatasetFull DataFrame
2Top / Bottom 5nlargest and nsmallest on Literacy
3Gender GapMale - Female literacy
4Region Summarygroupby Region
5Search StateDetails of one state
6States above valueBoolean filter on a chosen column
7Correlationcorr() between indicators
8Charts3 charts saved
0ExitEnds program
๐ŸŽฏ Objectives
  • Load and explore a dataset with describe()
  • Sort a DataFrame using sort_values()
  • Create a customised bar chart
๐Ÿ“š Data dictionary
NameTypePurpose
censusDataFrameState, Region, Population (lakh), Literacy, Male, Female, SexRatio
census_data.csvCSV fileDownloaded / saved open data
GapcolumnMale - Female literacy
Rankcolumnrank(ascending=False)
Why it matters: Matches the exact CBSE-suggested practical and shows real data-science skill for the interview panel too.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
# =====================================================================
#   OPEN GOVERNMENT DATA EXPLORER  (Census 2011 state indicators)
#   Source: Census of India 2011 (as published on data.gov.in)
# =====================================================================
raw = {"State": ["Kerala", "Mizoram", "Goa", "Tripura", "Himachal Pradesh", "Maharashtra", "Tamil Nadu", "Punjab",
                 "Gujarat", "West Bengal", "Karnataka", "Odisha", "Uttar Pradesh", "Rajasthan", "Bihar"],
       "Region": ["South", "North-East", "West", "North-East", "North", "West", "South", "North",
                  "West", "East", "South", "East", "North", "North", "East"],
       "Population": [334.1, 10.9, 14.6, 36.7, 68.6, 1123.7, 721.5, 277.4, 604.4, 912.8, 610.9, 419.7, 1998.1, 685.5, 1041.0],
       "Literacy": [94.0, 91.3, 88.7, 87.2, 82.8, 82.3, 80.1, 75.8, 78.0, 76.3, 75.4, 72.9, 67.7, 66.1, 61.8],
       "Male": [96.1, 93.3, 92.6, 91.5, 89.5, 88.4, 86.8, 80.4, 85.8, 81.7, 82.5, 81.6, 77.3, 79.2, 71.2],
       "Female": [92.1, 89.3, 84.7, 82.7, 75.9, 75.9, 73.4, 70.7, 69.7, 70.5, 68.1, 64.0, 57.2, 52.1, 51.5],
       "SexRatio": [1084, 976, 973, 960, 972, 929, 996, 895, 919, 950, 973, 979, 912, 928, 918]}
pd.DataFrame(raw).to_csv("census_data.csv", index=False)
census = pd.read_csv("census_data.csv")
census["Gap"] = (census["Male"] - census["Female"]).round(1)
census["Rank"] = census["Literacy"].rank(ascending=False).astype(int)
print("Dataset loaded:", census.shape[0], "states x", census.shape[1], "columns")


def view():
    print(census)


def top_bottom():
    print("TOP 5 LITERATE STATES\n", census.nlargest(5, "Literacy")[["State", "Literacy", "Rank"]].to_string(index=False))
    print("\nBOTTOM 5 STATES\n", census.nsmallest(5, "Literacy")[["State", "Literacy", "Rank"]].to_string(index=False))


def gap():
    g = census.sort_values("Gap", ascending=False)[["State", "Male", "Female", "Gap"]]
    print(g.to_string(index=False))
    print(f"\nLargest gender gap: {g.iloc[0, 0]} ({g.iloc[0, 3]} points) | Smallest: {g.iloc[-1, 0]} ({g.iloc[-1, 3]})")


def region():
    r = census.groupby("Region").agg(States=("State", "count"), Avg_Literacy=("Literacy", "mean"),
                                     Avg_SexRatio=("SexRatio", "mean"), Population=("Population", "sum"))
    print(r.round(1).sort_values("Avg_Literacy", ascending=False))


def search():
    s = input("State name: ").strip().lower()
    r = census[census["State"].str.lower() == s]
    print(r.T.to_string(header=False) if not r.empty else "State not in dataset.")


def above():
    col = input("Column (Literacy/Female/SexRatio/Population): ").strip()
    v = float(input("Value: "))
    r = census[census[col] > v][["State", col]]
    print(r.to_string(index=False))
    print(len(r), "states have", col, ">", v)


def correlation():
    c = census[["Literacy", "Female", "SexRatio", "Population"]].corr().round(2)
    print(c)
    print("\nLiteracy vs Sex ratio correlation:", c.loc["Literacy", "SexRatio"])


def charts():
    s = census.sort_values("Literacy")
    plt.barh(s["State"], s["Literacy"], color=["#c62828" if v < 70 else "#2e7d32" if v > 85 else "#1565c0" for v in s["Literacy"]])
    plt.axvline(74.04, color="black", linestyle="--", label="India 74.04%")
    plt.title("State-wise Literacy Rate (Census 2011)"); plt.xlabel("Literacy %"); plt.legend(loc="lower right")
    plt.tight_layout(); plt.savefig("literacy_bar.png"); plt.show()
    census.set_index("State")[["Male", "Female"]].plot(kind="bar", figsize=(10, 4.5), color=["#1565c0", "#ec407a"], title="Male vs Female Literacy")
    plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
    plt.scatter(census["Literacy"], census["SexRatio"], s=census["Population"] / 8, alpha=.6, c="purple")
    for _, r in census.iterrows():
        plt.annotate(r["State"][:8], (r["Literacy"], r["SexRatio"]), fontsize=7)
    plt.title("Literacy vs Sex Ratio (bubble = population)"); plt.xlabel("Literacy %"); plt.ylabel("Females per 1000 males")
    plt.tight_layout(); plt.savefig("literacy_vs_sex_ratio.png"); plt.show()
    print("Charts saved: literacy_bar.png, gender_gap.png, literacy_vs_sex_ratio.png")


menu = {"1": view, "2": top_bottom, "3": gap, "4": region, "5": search, "6": above, "7": correlation, "8": charts}
print("=" * 60)
print("OPEN GOVERNMENT DATA EXPLORER".center(60))
print("=" * 60)
while True:
    print("\n1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Thank you for exploring open data!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except (KeyError, ValueError):
        print("Invalid column / value.")

        
  1. Start
  2. Save open data as CSV and read with read_csv()
  3. Add Gap and Rank columns
  4. Display menu and read choice
  5. Valid option? → No: 'Invalid choice'
  6. Run analysis / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1View15 statesPASS
2Top 5Kerala firstPASS
3Bottom 5Bihar lastPASS
4Gender gapLargest gap state shownPASS
5Region summaryAverages by regionPASS
6Search 'kerala'Kerala rowPASS
7Filter SexRatio > 950Matching statesPASS
8CorrelationValue between -1 and 1PASS
9Charts3 PNG filesPASS
โš  Limitations
  • Only 15 major states included
  • Census 2011 values (latest full census)
  • No district-level data
  • Offline copy of the dataset
๐Ÿš€ Future scope
  • Download latest datasets with the data.gov.in API
  • District-wise map using GeoPandas
  • Compare with NFHS-5 data
  • Dashboard in Streamlit

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: raw, census.
  3. 8 functions are defined (lines 25โ€“79) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
view()25โ€“26Viewmain program (menu)
top_bottom()29โ€“31Top bottommain program (menu)
gap()34โ€“37Gapmain program (menu)
region()40โ€“43Regionmain program (menu)
search()46โ€“49Searchmain program (menu)
above()52โ€“57Abovemain program (menu)
correlation()60โ€“63Correlationmain program (menu)
charts()66โ€“79Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
๐Ÿ“Œ OPEN GOVERNMENT DATA EXPLORER (Census 2011 state indicators)
๐Ÿ“Œ Source: Census of India 2011 (as published on data.gov.in)
9
raw = {"State": ["Kerala", "Mizoram", "Goa", "Tripura", "Himachal Pradesh", "Maharashtra", "Tamil Nadu", "Punjab",
                 "Gujarat", "West Bengal",โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"State": ["Kerala", "Mizoram", "Goa", "Tripuโ€ฆ in variable raw
18
pd.DataFrame(raw).to_csv("census_data.csv", index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "census_data.csv"
19
census = pd.read_csv("census_data.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "census_data.csv" into a DataFrame (table); the result is stored in variable census
20
census["Gap"] = (census["Male"] - census["Female"]).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of census["Male"] - census["Female"] to 1 decimal places; the result is put into census["Gap"] (item "Gap" of census)
21
census["Rank"] = census["Literacy"].rank(ascending=False).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of census["Literacy"].rank(ascending=False) to int; the result is put into census["Rank"] (item "Rank" of census)
22
print("Dataset loaded:", census.shape[0], "states x", census.shape[1], "columns")
๐Ÿ–ฅ๏ธ Output Displays the text "Dataset loaded:", then the value of census.shape[0], then the text "states x", then the value of census.shape[1], then the text "columns" on the screen
82
menu = {"1": view, "2": top_bottom, "3": gap, "4": region, "5": search, "6": above, "7": correlation, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": top_bottom, "3": gap, "4": rโ€ฆ in variable menu
83
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
84
print("OPEN GOVERNMENT DATA EXPLORER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "OPEN GOVERNMENT DATA EXPLORER".center(60) on the screen
85
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
86
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
87
print("\n1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Top/Bottom 3.Gender Gap โ€ฆ" on the screen
88
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
89
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
90
print("Thank you for exploring open data!")
๐Ÿ–ฅ๏ธ Output Displays the text "Thank you for exploring open data!" on the screen
91
break
๐Ÿ” Loop BREAK - leaves the loop immediately
92
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
93
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
94
except (KeyError, ValueError):
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (KeyError, ValueError) occurs - that error
95
print("Invalid column / value.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid column / value." on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: Dataset loaded: 15 states x 9 columns (+2 more lines)
  2. You type 1 at Enter choice:
    runs: view()
    shows: State Region Population Literacy Male Female SexRatio Gap Rank (+16 more lines)
  3. You type 2 at Enter choice:
    runs: top_bottom()
    shows: TOP 5 LITERATE STATES (+14 more lines)
  4. You type 3 at Enter choice:
    runs: gap()
    shows: State Male Female Gap (+17 more lines)
  5. You type 4 at Enter choice:
    runs: region()
    shows: States Avg_Literacy Avg_SexRatio Population (+7 more lines)
  6. You type 5 at Enter choice:
    runs: search()
  7. You type kerala at State name:
    shows: State Kerala (+9 more lines)
  8. You type 6 at Enter choice:
    runs: above()
  9. You type SexRatio at Column (Literacy/Female/SexRatio/Population):
  10. You type 950 at Value:
    shows: State SexRatio (+10 more lines)
  11. You type 7 at Enter choice:
    runs: correlation()
    shows: Literacy Female SexRatio Population (+6 more lines)
  12. You type 8 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  13. You type 0 at Enter choice:
    shows: Thank you for exploring open data!
โ‘ค Inside each function - line by line
view() - lines 25โ€“26
LineCodeWhat it does
25
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
26
print(census)
๐Ÿ–ฅ๏ธ Output Displays the value of census on the screen
top_bottom() - lines 29โ€“31
LineCodeWhat it does
29
def top_bottom():
๐Ÿงฉ Function DEFINES a function top_bottom(). Python only remembers it here - its body runs later, each time top_bottom() is called.
30
print("TOP 5 LITERATE STATES\n", census.nlargest(5, "Literacy")[["State", "Literacy", "Rank"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "TOP 5 LITERATE STATES", then the value of census.nlargest(5, "Literacy")[["State", "Litโ€ฆ on the screen
31
print("\nBOTTOM 5 STATES\n", census.nsmallest(5, "Literacy")[["State", "Literacy", "Rank"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "BOTTOM 5 STATES", then the value of census.nsmallest(5, "Literacy")[["State", "Liโ€ฆ on the screen
gap() - lines 34โ€“37
LineCodeWhat it does
34
def gap():
๐Ÿงฉ Function DEFINES a function gap(). Python only remembers it here - its body runs later, each time gap() is called.
35
g = census.sort_values("Gap", ascending=False)[["State", "Male", "Female", "Gap"]]
๐Ÿงฎ Store / Calculate Stores the item census.sort_values("Gap", ascending=False)[["โ€ฆ in variable g
36
print(g.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of g.to_string(index=False) on the screen
37
print(f"\nLargest gender gap: {g.iloc[0, 0]} ({g.iloc[0, 3]} points) | Smallest: {g.iloc[-1, 0]} ({g.iloc[-1, 3]})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nLargest gender gap: {g.iloc[0, 0]} ({g.ilโ€ฆ with the values filled into { } on the screen
region() - lines 40โ€“43
LineCodeWhat it does
40
def region():
๐Ÿงฉ Function DEFINES a function region(). Python only remembers it here - its body runs later, each time region() is called.
41
r = census.groupby("Region").agg(States=("State", "count"), Avg_Literacy=("Literacy", "mean"),
                                 Avg_SexRatio=("SexRatio", "meโ€ฆ
๐Ÿงฎ Store / Calculate Calculates the given summary values for every group; the result is stored in variable r
43
print(r.round(1).sort_values("Avg_Literacy", ascending=False))
๐Ÿ–ฅ๏ธ Output Displays the value of r.round(1).sort_values("Avg_Literacy", ascendโ€ฆ on the screen
search() - lines 46โ€“49
LineCodeWhat it does
46
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
47
s = input("State name: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable s
48
r = census[census["State"].str.lower() == s]
๐Ÿงฎ Store / Calculate Stores the item census[census["State"].str.lower() == s] in variable r
49
print(r.T.to_string(header=False) if not r.empty else "State not in dataset.")
๐Ÿ–ฅ๏ธ Output Displays the value of r.T.to_string(header=False) if not r.empty elโ€ฆ on the screen
above() - lines 52โ€“57
LineCodeWhat it does
52
def above():
๐Ÿงฉ Function DEFINES a function above(). Python only remembers it here - its body runs later, each time above() is called.
53
col = input("Column (Literacy/Female/SexRatio/Population): ").strip()
โŒจ๏ธ Input Shows "Column (Literacy/Female/SexRatio/Population): ", reads the typed text, removes extra spaces (strip) and stores it in variable col
54
v = float(input("Value: "))
โŒจ๏ธ Input Shows "Value: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable v
55
r = census[census[col] > v][["State", col]]
๐Ÿงฎ Store / Calculate Stores the item census[census[col] > v][["State", col]] in variable r
56
print(r.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of r.to_string(index=False) on the screen
57
print(len(r), "states have", col, ">", v)
๐Ÿ–ฅ๏ธ Output Displays the value of len(r), then the text "states have", then the value of col, then the text ">", then the value of v on the screen
correlation() - lines 60โ€“63
LineCodeWhat it does
60
def correlation():
๐Ÿงฉ Function DEFINES a function correlation(). Python only remembers it here - its body runs later, each time correlation() is called.
61
c = census[["Literacy", "Female", "SexRatio", "Population"]].corr().round(2)
๐Ÿงฎ Store / Calculate Rounds the values of census[["Literacy", "Female", "SexRatio", "Poโ€ฆ to 2 decimal places; the result is stored in variable c
62
print(c)
๐Ÿ–ฅ๏ธ Output Displays the value of c on the screen
63
print("\nLiteracy vs Sex ratio correlation:", c.loc["Literacy", "SexRatio"])
๐Ÿ–ฅ๏ธ Output Displays the text "Literacy vs Sex ratio correlation:", then the value of c.loc["Literacy", "SexRatio"] on the screen
charts() - lines 66โ€“79
LineCodeWhat it does
66
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
67
s = census.sort_values("Literacy")
๐Ÿงฎ Store / Calculate Sorts census by "Literacy"; the result is stored in variable s
68
plt.barh(s["State"], s["Literacy"], color=["#c62828" if v < 70 else "#2e7d32" if v > 85 else "#1565c0" for v in s["Literacy"]])
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
69
plt.axvline(74.04, color="black", linestyle="--", label="India 74.04%")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
70
plt.title("State-wise Literacy Rate (Census 2011)"); plt.xlabel("Literacy %"); plt.legend(loc="lower right")
๐Ÿ–ฅ๏ธ Output Writes "State-wise Literacy Rate (Census 2011)" as the title of the chart
70
plt.title("State-wise Literacy Rate (Census 2011)"); plt.xlabel("Literacy %"); plt.legend(loc="lower right")
๐Ÿ–ฅ๏ธ Output Writes "Literacy %" as the label of the X-axis
70
plt.title("State-wise Literacy Rate (Census 2011)"); plt.xlabel("Literacy %"); plt.legend(loc="lower right")
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
71
plt.tight_layout(); plt.savefig("literacy_bar.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
71
plt.tight_layout(); plt.savefig("literacy_bar.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "literacy_bar.png"
71
plt.tight_layout(); plt.savefig("literacy_bar.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
72
census.set_index("State")[["Male", "Female"]].plot(kind="bar", figsize=(10, 4.5), color=["#1565c0", "#ec407a"], title="Male vs Female Literacy")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
73
plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "%" as the label of the Y-axis
73
plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
73
plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
73
plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "gender_gap.png"
73
plt.ylabel("%"); plt.xticks(rotation=60); plt.tight_layout(); plt.savefig("gender_gap.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
74
plt.scatter(census["Literacy"], census["SexRatio"], s=census["Population"] / 8, alpha=.6, c="purple")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of census["Literacy"], census["SexRatio"]
75
for _, r in census.iterrows():
๐Ÿ” Loop LOOP over each row of census; _, r get (index, row)
76
plt.annotate(r["State"][:8], (r["Literacy"], r["SexRatio"]), fontsize=7)
๐Ÿ–ฅ๏ธ Output Writes a note with an arrow on the chart
77
plt.title("Literacy vs Sex Ratio (bubble = population)"); plt.xlabel("Literacy %"); plt.ylabel("Females per 1000 males")
๐Ÿ–ฅ๏ธ Output Writes "Literacy vs Sex Ratio (bubble = population)" as the title of the chart
77
plt.title("Literacy vs Sex Ratio (bubble = population)"); plt.xlabel("Literacy %"); plt.ylabel("Females per 1000 males")
๐Ÿ–ฅ๏ธ Output Writes "Literacy %" as the label of the X-axis
77
plt.title("Literacy vs Sex Ratio (bubble = population)"); plt.xlabel("Literacy %"); plt.ylabel("Females per 1000 males")
๐Ÿ–ฅ๏ธ Output Writes "Females per 1000 males" as the label of the Y-axis
78
plt.tight_layout(); plt.savefig("literacy_vs_sex_ratio.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
78
plt.tight_layout(); plt.savefig("literacy_vs_sex_ratio.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "literacy_vs_sex_ratio.png"
78
plt.tight_layout(); plt.savefig("literacy_vs_sex_ratio.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
79
print("Charts saved: literacy_bar.png, gender_gap.png, literacy_vs_sex_ratio.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: literacy_bar.png, gโ€ฆ" on the screen
Q1. What is open government data?

Data published by government (e.g. data.gov.in) in machine-readable formats such as CSV for anyone to use.

Q2. What do nlargest() and nsmallest() do?

Return n rows with the largest / smallest values of a column.

Q3. What does corr() tell us?

Correlation coefficient: +1 strong positive, -1 strong negative, 0 no linear relation.

Q4. What is rank()?

Gives position numbers to values; ascending=False makes the highest value rank 1.

Q5. Why barh()?

A horizontal bar chart makes long state names easy to read.

04

Student Database + SQL Analytics Combo

PYTHON + MySQLMySQL table creation from PythonexecutemanySELECT into a DataFramegroupbynlargest
๐Ÿ“ 114 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 124 output lines๐Ÿ“„ 25+ page report

Creates a student table in MySQL, loads it into a Pandas DataFrame and analyses section-wise averages, toppers and pass percentage with a chart.

โœจ Features
  • Student table created in MySQL from Python; 12 records inserted with executemany()
  • SQL query results loaded into a DataFrame (pd.DataFrame(cur.fetchall(), columns=...))
  • SQL aggregates (GROUP BY, HAVING, ORDER BY) compared with Pandas groupby
  • Add / update / delete student records from the menu
  • Grade calculation in Pandas and toppers using nlargest
  • Bar, box and count charts
โ˜ฐ Main menu
1View TableSELECT * into DataFrame
2Add StudentINSERT with commit
3Update MarksUPDATE ... WHERE roll
4Delete StudentDELETE
5SQL ReportsGROUP BY / HAVING queries
6Pandas Analysisgroupby, describe, grades
7Top Performersnlargest(3)
8Charts3 charts
0ExitCloses connection
๐ŸŽฏ Objectives
  • Create and populate a MySQL table from Python
  • Convert query results into a DataFrame
  • Analyse and visualise data with Pandas and Matplotlib
๐Ÿ“š Data dictionary
NameTypePurpose
studentMySQL tableroll PK, name, section, maths, science, english
dfDataFrameData fetched from MySQL
q()functionRuns a query and returns a DataFrame
curcursorExecutes SQL
Why it matters: Shows the complete IP pipeline - SQL storage, Pandas analysis and Matplotlib visualisation - in one script.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import mysql.connector
# =====================================================================
#   STUDENT DATABASE + SQL ANALYTICS COMBO  (MySQL + Pandas)
# =====================================================================
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS school_ip")
cur.execute("USE school_ip")
cur.execute("""CREATE TABLE IF NOT EXISTS student (roll INT PRIMARY KEY, name VARCHAR(20), section CHAR(1),
               maths INT, science INT, english INT)""")
cur.execute("SELECT COUNT(*) FROM student")
if cur.fetchone()[0] == 0:
    rows = [(1, "Aarav", "A", 88, 92, 79), (2, "Bhavya", "A", 76, 81, 85), (3, "Chirag", "B", 54, 61, 70),
            (4, "Diya", "B", 95, 89, 91), (5, "Eshan", "C", 45, 52, 60), (6, "Farah", "C", 82, 78, 88),
            (7, "Gaurav", "A", 67, 73, 64), (8, "Hina", "B", 90, 94, 86), (9, "Ira", "C", 38, 44, 55),
            (10, "Jatin", "A", 79, 70, 68), (11, "Kavya", "B", 85, 91, 95), (12, "Laksh", "C", 60, 58, 72)]
    cur.executemany("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s)", rows)
    conn.commit()
    print(cur.rowcount, "records inserted with executemany()")
SUBJ = ["maths", "science", "english"]


def q(sql, params=()):
    """Runs a SELECT and returns a DataFrame."""
    cur.execute(sql, params)
    return pd.DataFrame(cur.fetchall(), columns=[d[0] for d in cur.description])


def view():
    df = q("SELECT * FROM student ORDER BY roll")
    df["total"] = df[SUBJ].sum(axis=1)
    print(df.to_string(index=False))


def add():
    r = (int(input("Roll: ")), input("Name: ").strip().title(), input("Section: ").strip().upper(),
         int(input("Maths: ")), int(input("Science: ")), int(input("English: ")))
    cur.execute("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s)", r)
    conn.commit()
    print("Inserted", r[1])


def update():
    roll, sub, m = int(input("Roll: ")), input("Subject: ").strip().lower(), int(input("New marks: "))
    if sub in SUBJ:
        cur.execute(f"UPDATE student SET {sub} = %s WHERE roll = %s", (m, roll))
        conn.commit()
        print(cur.rowcount, "row(s) updated")


def delete():
    cur.execute("DELETE FROM student WHERE roll = %s", (int(input("Roll to delete: ")),))
    conn.commit()
    print(cur.rowcount, "row(s) deleted")


def sql_reports():
    print("Section-wise average (SQL GROUP BY):")
    print(q("""SELECT section, COUNT(*) AS students, ROUND(AVG(maths),2) AS avg_maths,
               ROUND(AVG(science),2) AS avg_sci, ROUND(AVG(english),2) AS avg_eng
               FROM student GROUP BY section""").to_string(index=False))
    print("\nSections with maths average > 70 (HAVING):")
    print(q("SELECT section, AVG(maths) AS avg_maths FROM student GROUP BY section HAVING AVG(maths) > 70").to_string(index=False))
    print("\nStudents scoring 85+ in any subject:")
    print(q("SELECT name, maths, science, english FROM student WHERE GREATEST(maths, science, english) >= 85 ORDER BY name").to_string(index=False))


def pandas_analysis():
    df = q("SELECT * FROM student")
    df["total"] = df[SUBJ].sum(axis=1)
    df["percent"] = (df["total"] / 3).round(1)
    df["grade"] = pd.cut(df["percent"], [0, 50, 60, 75, 90, 100], labels=["D", "C", "B", "A", "A+"])
    print(df[SUBJ].describe().round(2))
    print("\nSection-wise mean (Pandas groupby):")
    print(df.groupby("section")[SUBJ + ["percent"]].mean().round(2))
    print("\nGrade count:\n", df["grade"].value_counts().sort_index().to_string())


def toppers():
    df = q("SELECT name, section, maths + science + english AS total FROM student")
    print(df.nlargest(3, "total").to_string(index=False))


def charts():
    df = q("SELECT * FROM student")
    df.groupby("section")[SUBJ].mean().plot(kind="bar", title="Section-wise Average (from MySQL)", color=["#1565c0", "#2e7d32", "#ef6c00"])
    plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
    df[SUBJ].plot(kind="box", title="Spread of Marks"); plt.tight_layout(); plt.savefig("subject_box.png"); plt.show()
    pct = df[SUBJ].mean(axis=1)
    pd.cut(pct, [0, 50, 60, 75, 90, 100], labels=["D", "C", "B", "A", "A+"]).value_counts().sort_index().plot(kind="bar", color="teal", title="Grade Count")
    plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("grade_count.png"); plt.show()
    print("Charts saved: section_avg_sql.png, subject_box.png, grade_count.png")


menu = {"1": view, "2": add, "3": update, "4": delete, "5": sql_reports, "6": pandas_analysis, "7": toppers, "8": charts}
print("=" * 60)
print("STUDENT DATABASE + SQL ANALYTICS".center(60))
print("=" * 60)
while True:
    print("\n1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Connection closed.")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except (ValueError, mysql.connector.Error) as e:
        print("Error:", e)

        
  1. Start
  2. Connect to MySQL, create table, executemany()
  3. Display menu and read choice
  4. DML option (2/3/4)? → No: run SELECT and build DataFrame
  5. execute() + commit()
  6. Analyse DataFrame / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1View12 rows in DataFramePASS
2Add roll 13Row insertedPASS
3Update maths roll 51 row changedPASS
4Delete roll 990 rowsPASS
5SQL reportsSection averagesPASS
6Pandas analysisSame averages as SQLPASS
7Top performers3 studentsPASS
8Charts3 PNG filesPASS
โš  Limitations
  • Password in code
  • Three subjects only
  • No foreign keys
  • Local server only
๐Ÿš€ Future scope
  • Use SQLAlchemy and pd.read_sql()
  • Web dashboard
  • Attendance table JOIN
  • Export to Excel

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, mysql.connector - connecting Python with MySQL are loaded.
  2. Global variables / constants are created: conn, cur, SUBJ.
  3. 9 functions are defined (lines 27โ€“96) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
q(sql, params)27โ€“30Runs a SELECT and returns a DataFrame.view(), sql_reports(), pandas_analysis(), toppers()
view()33โ€“36Viewmain program (menu)
add()39โ€“44Addmain program (menu)
update()47โ€“52Updatemain program (menu)
delete()55โ€“58Deletemain program (menu)
sql_reports()61โ€“69Sql reportsmain program (menu)
pandas_analysis()72โ€“80Pandas analysismain program (menu)
toppers()83โ€“85Toppersmain program (menu)
charts()88โ€“96Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import mysql.connector
๐Ÿ“ฆ Library / Data Loads the module mysql.connector - connecting Python with MySQL
๐Ÿ“Œ STUDENT DATABASE + SQL ANALYTICS COMBO (MySQL + Pandas)
9
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
๐Ÿฌ Database Connects Python to the MySQL server using host, user, password; the result is stored in variable conn
10
cur = conn.cursor()
๐Ÿฌ Database Creates a cursor - the object that carries SQL queries to MySQL; the result is stored in variable cur
11
cur.execute("CREATE DATABASE IF NOT EXISTS school_ip")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
12
cur.execute("USE school_ip")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
13
cur.execute("""CREATE TABLE IF NOT EXISTS student (roll INT PRIMARY KEY, name VARCHAR(20), section CHAR(1),
               maths INT, science INT, english INโ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
15
cur.execute("SELECT COUNT(*) FROM student")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
16
if cur.fetchone()[0] == 0:
๐Ÿ”€ Decision CHECKS whether cur.fetchone()[0] is equal to 0. If True, the indented lines below run; otherwise they are skipped
17
rows = [(1, "Aarav", "A", 88, 92, 79), (2, "Bhavya", "A", 76, 81, 85), (3, "Chirag", "B", 54, 61, 70),
        (4, "Diya", "B", 95, 89, 91), (5, "Eshan", "C"โ€ฆ
๐Ÿงฎ Store / Calculate Stores a list [(1, "Aarav", "A", 88, 92, 79), (2, "Bhavya",โ€ฆ in variable rows
21
cur.executemany("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s)", rows)
๐Ÿฌ Database Runs the same SQL for every row of rows
22
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
23
print(cur.rowcount, "records inserted with executemany()")
๐Ÿ–ฅ๏ธ Output Displays the value of cur.rowcount, then the text "records inserted with executemanyโ€ฆ" on the screen
24
SUBJ = ["maths", "science", "english"]
๐Ÿงฎ Store / Calculate Stores a list ["maths", "science", "english"] in variable SUBJ
99
menu = {"1": view, "2": add, "3": update, "4": delete, "5": sql_reports, "6": pandas_analysis, "7": toppers, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": add, "3": update, "4": deletโ€ฆ in variable menu
100
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
101
print("STUDENT DATABASE + SQL ANALYTICS".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "STUDENT DATABASE + SQL ANALYTICS".center(60) on the screen
102
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
103
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
104
print("\n1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Add 3.Update 4.Delete 5.โ€ฆ" on the screen
105
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
106
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
107
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
108
print("Connection closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Connection closed." on the screen
109
break
๐Ÿ” Loop BREAK - leaves the loop immediately
110
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
111
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
112
except (ValueError, mysql.connector.Error) as e:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, mysql.connector.Error) occurs - that error
113
print("Error:", e)
๐Ÿ–ฅ๏ธ Output Displays the text "Error:", then the value of e on the screen
โ‘ฃ Inside each function - line by line
q() - lines 27โ€“30
LineCodeWhat it does
27
def q(sql, params=()):
๐Ÿงฉ Function DEFINES a function q(sql, params). Python only remembers it here - its body runs later, each time q() is called.
29
cur.execute(sql, params)
๐Ÿฌ Database Sends the SQL statement to MySQL through the cursor; the %s places are filled safely with the values params
30
return pd.DataFrame(cur.fetchall(), columns=[d[0] for d in cur.description])
๐Ÿงฉ Function Sends back (returns) the result of: creates a pandas DataFrame (table) from cur.fetchall() to the line that called the function
view() - lines 33โ€“36
LineCodeWhat it does
33
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
34
df = q("SELECT * FROM student ORDER BY roll")
๐Ÿงฎ Store / Calculate Calls our own function q("SELECT * FROM studโ€ฆ) - runs a select and returns a dataframe; the result is stored in variable df
35
df["total"] = df[SUBJ].sum(axis=1)
๐Ÿงฎ Store / Calculate Adds up all values of df[SUBJ]; the result is put into df["total"] (item "total" of df)
36
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
add() - lines 39โ€“44
LineCodeWhat it does
39
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
40
r = (int(input("Roll: ")), input("Name: ").strip().title(), input("Section: ").strip().upper(),
     int(input("Maths: ")), int(input("Science: ")), int(inpuโ€ฆ
โŒจ๏ธ Input Stores the tuple (int(input("Roll: ")), input("Name: ").strip(โ€ฆ in variable r
42
cur.execute("INSERT INTO student VALUES (%s,%s,%s,%s,%s,%s)", r)
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values r
43
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
44
print("Inserted", r[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Inserted", then the value of r[1] on the screen
update() - lines 47โ€“52
LineCodeWhat it does
47
def update():
๐Ÿงฉ Function DEFINES a function update(). Python only remembers it here - its body runs later, each time update() is called.
48
roll, sub, m = int(input("Roll: ")), input("Subject: ").strip().lower(), int(input("New marks: "))
โŒจ๏ธ Input Stores int(input("Roll: ")), input("Subject: ").strip().lower(), int(input("New marks: ")) into roll, sub, m respectively
49
if sub in SUBJ:
๐Ÿ”€ Decision CHECKS whether sub is present in SUBJ. If True, the indented lines below run; otherwise they are skipped
50
cur.execute(f"UPDATE student SET {sub} = %s WHERE roll = %s", (m, roll))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (m, roll)
51
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
52
print(cur.rowcount, "row(s) updated")
๐Ÿ–ฅ๏ธ Output Displays the value of cur.rowcount, then the text "row(s) updated" on the screen
delete() - lines 55โ€“58
LineCodeWhat it does
55
def delete():
๐Ÿงฉ Function DEFINES a function delete(). Python only remembers it here - its body runs later, each time delete() is called.
56
cur.execute("DELETE FROM student WHERE roll = %s", (int(input("Roll to delete: ")),))
๐Ÿฌ Database Sends a DELETE query (removes rows) to MySQL through the cursor; the %s places are filled safely with the values (int(input("Roll to delete: ")),)
57
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
58
print(cur.rowcount, "row(s) deleted")
๐Ÿ–ฅ๏ธ Output Displays the value of cur.rowcount, then the text "row(s) deleted" on the screen
sql_reports() - lines 61โ€“69
LineCodeWhat it does
61
def sql_reports():
๐Ÿงฉ Function DEFINES a function sql_reports(). Python only remembers it here - its body runs later, each time sql_reports() is called.
62
print("Section-wise average (SQL GROUP BY):")
๐Ÿ–ฅ๏ธ Output Displays the text "Section-wise average (SQL GROUP Bโ€ฆ" on the screen
63
print(q("""SELECT section, COUNT(*) AS students, ROUND(AVG(maths),2) AS avg_maths,
           ROUND(AVG(science),2) AS avg_sci, ROUND(AVG(english),2) AS avg_โ€ฆ
๐Ÿ–ฅ๏ธ Output Displays the value of q("""SELECT section, COUNT(*) AS students, ROโ€ฆ on the screen
66
print("\nSections with maths average > 70 (HAVING):")
๐Ÿ–ฅ๏ธ Output Displays the text "Sections with maths average > 70 โ€ฆ" on the screen
67
print(q("SELECT section, AVG(maths) AS avg_maths FROM student GROUP BY section HAVING AVG(maths) > 70").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of q("SELECT section, AVG(maths) AS avg_maths FRโ€ฆ on the screen
68
print("\nStudents scoring 85+ in any subject:")
๐Ÿ–ฅ๏ธ Output Displays the text "Students scoring 85+ in any subjeโ€ฆ" on the screen
69
print(q("SELECT name, maths, science, english FROM student WHERE GREATEST(maths, science, english) >= 85 ORDER BY name").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of q("SELECT name, maths, science, english FROM โ€ฆ on the screen
pandas_analysis() - lines 72โ€“80
LineCodeWhat it does
72
def pandas_analysis():
๐Ÿงฉ Function DEFINES a function pandas_analysis(). Python only remembers it here - its body runs later, each time pandas_analysis() is called.
73
df = q("SELECT * FROM student")
๐Ÿงฎ Store / Calculate Calls our own function q("SELECT * FROM studโ€ฆ) - runs a select and returns a dataframe; the result is stored in variable df
74
df["total"] = df[SUBJ].sum(axis=1)
๐Ÿงฎ Store / Calculate Adds up all values of df[SUBJ]; the result is put into df["total"] (item "total" of df)
75
df["percent"] = (df["total"] / 3).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of df["total"] / 3 to 1 decimal places; the result is put into df["percent"] (item "percent" of df)
76
df["grade"] = pd.cut(df["percent"], [0, 50, 60, 75, 90, 100], labels=["D", "C", "B", "A", "A+"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["grade"] (item "grade" of df)
77
print(df[SUBJ].describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of df[SUBJ].describe().round(2) on the screen
78
print("\nSection-wise mean (Pandas groupby):")
๐Ÿ–ฅ๏ธ Output Displays the text "Section-wise mean (Pandas groupbyโ€ฆ" on the screen
79
print(df.groupby("section")[SUBJ + ["percent"]].mean().round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of df.groupby("section")[SUBJ + ["percent"]].meaโ€ฆ on the screen
80
print("\nGrade count:\n", df["grade"].value_counts().sort_index().to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Grade count:", then the value of df["grade"].value_counts().sort_index().to_stโ€ฆ on the screen
toppers() - lines 83โ€“85
LineCodeWhat it does
83
def toppers():
๐Ÿงฉ Function DEFINES a function toppers(). Python only remembers it here - its body runs later, each time toppers() is called.
84
df = q("SELECT name, section, maths + science + english AS total FROM student")
๐Ÿงฎ Store / Calculate Calls our own function q("SELECT name, sectiโ€ฆ) - runs a select and returns a dataframe; the result is stored in variable df
85
print(df.nlargest(3, "total").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.nlargest(3, "total").to_string(index=False) on the screen
charts() - lines 88โ€“96
LineCodeWhat it does
88
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
89
df = q("SELECT * FROM student")
๐Ÿงฎ Store / Calculate Calls our own function q("SELECT * FROM studโ€ฆ) - runs a select and returns a dataframe; the result is stored in variable df
90
df.groupby("section")[SUBJ].mean().plot(kind="bar", title="Section-wise Average (from MySQL)", color=["#1565c0", "#2e7d32", "#ef6c00"])
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
91
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Average" as the label of the Y-axis
91
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
91
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
91
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "section_avg_sql.png"
91
plt.ylabel("Average"); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("section_avg_sql.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
92
df[SUBJ].plot(kind="box", title="Spread of Marks"); plt.tight_layout(); plt.savefig("subject_box.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
92
df[SUBJ].plot(kind="box", title="Spread of Marks"); plt.tight_layout(); plt.savefig("subject_box.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
92
df[SUBJ].plot(kind="box", title="Spread of Marks"); plt.tight_layout(); plt.savefig("subject_box.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "subject_box.png"
92
df[SUBJ].plot(kind="box", title="Spread of Marks"); plt.tight_layout(); plt.savefig("subject_box.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
93
pct = df[SUBJ].mean(axis=1)
๐Ÿงฎ Store / Calculate Finds the average (mean) of df[SUBJ]; the result is stored in variable pct
94
pd.cut(pct, [0, 50, 60, 75, 90, 100], labels=["D", "C", "B", "A", "A+"]).value_counts().sort_index().plot(kind="bar", color="teal", title="Grade Count")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
95
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("grade_count.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
95
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("grade_count.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
95
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("grade_count.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "grade_count.png"
95
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("grade_count.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
96
print("Charts saved: section_avg_sql.png, subject_box.png, grade_count.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: section_avg_sql.pngโ€ฆ" on the screen
Q1. How is SQL data converted into a DataFrame?

cur.fetchall() gives rows; pd.DataFrame(rows, columns=[d[0] for d in cur.description]) creates the DataFrame.

Q2. What is executemany()?

It runs the same INSERT for every tuple in a list - faster than a loop of execute().

Q3. What does cursor.description hold?

Information about the result columns; d[0] is each column name.

Q4. HAVING vs WHERE?

WHERE filters rows; HAVING filters groups after GROUP BY.

Q5. Which is better for analysis - SQL or Pandas?

SQL is best for storing and filtering large data on the server; Pandas is best for further analysis and charts in Python.

05

Inventory / Stock Price Tracker

PYTHONDataFrame operationsnegative-value/missing-value handlingline charts (Practicals 12-1517)
๐Ÿ“ 116 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 134 output lines๐Ÿ“„ 25+ page report

Maintain a small inventory or mock stock-price DataFrame, clean missing/negative entries, find top-3 highest values, and plot the price/quantity trend using a line chart.

โœจ Features
  • Inventory DataFrame of 10 items with opening stock, purchase, sales, price and reorder level
  • Data cleaning: missing values (NaN) filled, negative quantities corrected
  • Closing stock, stock value and reorder flag as calculated columns
  • Daily price series of 3 products with rolling 5-day average and % change
  • Stock IN / OUT entry updates the DataFrame
  • Line, bar and highlighted reorder charts
โ˜ฐ Main menu
1Raw Data & Cleaningisnull().sum(), fillna(), negatives fixed
2Inventory ReportClosing stock and value
3Reorder ListItems below reorder level
4Stock IN / OUTUpdates purchase / sales
5Price TrackerDaily prices, rolling mean, pct_change
6Category Summarygroupby category
7Charts3 charts
8Save CSVinventory_clean.csv
0ExitEnds program
๐ŸŽฏ Objectives
  • Handle missing and wrong data with fillna() and apply()
  • Select rows using nlargest()
  • Draw a line chart with markers
๐Ÿ“š Data dictionary
NameTypePurpose
invDataFrameItem, Category, Opening, Purchase, Sold, Price, Reorder
pricesDataFrameDate-indexed daily prices of 3 items
ClosingcolumnOpening + Purchase - Sold
ValuecolumnClosing x Price
Why it matters: Reinforces the exact data-cleaning skills tested in Practicals 12-15 in a business-realistic setting.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import numpy as np
# =====================================================================
#   INVENTORY / STOCK PRICE TRACKER  (Pandas + Matplotlib)
# =====================================================================
inv = pd.DataFrame({
    "Item": ["Notebook", "Gel Pen", "Pencil Box", "Geometry Box", "Calculator", "Drawing File", "Eraser", "Marker", "Stapler", "Glue Stick"],
    "Category": ["Paper", "Writing", "Writing", "Maths", "Maths", "Paper", "Writing", "Writing", "Office", "Office"],
    "Opening": [120, 200, 40, 25, 10, 60, np.nan, 80, 15, 50],
    "Purchase": [100, -10, 20, 10, 5, np.nan, 50, 40, 10, 30],
    "Sold": [150, 160, 45, 28, 9, 35, 30, 70, 6, 72],
    "Price": [45, 10, 120, 150, 950, 60, 5, np.nan, 180, 25],
    "Reorder": [50, 60, 15, 10, 5, 20, 20, 30, 5, 20]})
raw = inv.copy()


def clean():
    print("Raw data:\n", raw)
    print("\nMissing values per column:\n", inv.isnull().sum().to_string())
    inv["Opening"] = inv["Opening"].fillna(0)
    inv["Purchase"] = inv["Purchase"].fillna(0).abs()
    inv["Price"] = inv["Price"].fillna(inv["Price"].median())
    recalc()
    print("\nAfter cleaning - missing:", int(inv.isnull().sum().sum()), "| negative purchase fixed:", (raw["Purchase"] < 0).sum())


def recalc():
    inv["Closing"] = (inv["Opening"] + inv["Purchase"] - inv["Sold"]).fillna(0).astype(int)
    inv["Value"] = inv["Closing"] * inv["Price"]
    inv["Status"] = np.where(inv["Closing"] < inv["Reorder"], "REORDER", "OK")


def report():
    print(inv[["Item", "Opening", "Purchase", "Sold", "Closing", "Price", "Value", "Status"]].to_string(index=False))
    print(f"\nTotal stock value: Rs. {inv['Value'].sum():,.0f}")


def reorder():
    r = inv[inv["Status"] == "REORDER"].copy()
    r["Order_Qty"] = r["Reorder"] * 2 - r["Closing"]
    print(r[["Item", "Closing", "Reorder", "Order_Qty"]].to_string(index=False) if len(r) else "Nothing to reorder.")


def stock_entry():
    item = input("Item name: ").strip().title()
    typ = input("IN or OUT: ").strip().upper()
    qty = int(input("Quantity: "))
    m = inv["Item"].str.title() == item
    if not m.any():
        print("Item not found.")
        return
    i = inv.index[m][0]
    if typ == "OUT" and qty > inv.loc[i, "Closing"]:
        print("Insufficient stock! Available:", inv.loc[i, "Closing"])
        return
    inv.loc[i, "Purchase" if typ == "IN" else "Sold"] += qty
    recalc()
    print(f"{item}: closing stock now {inv.loc[i, 'Closing']} ({inv.loc[i, 'Status']})")


rng = np.random.default_rng(5)
days = pd.date_range("2026-07-01", periods=15, freq="D")
prices = pd.DataFrame({"Calculator": 950 + rng.integers(-25, 30, 15).cumsum(),
                       "Geometry Box": 150 + rng.integers(-4, 5, 15).cumsum(),
                       "Stapler": 180 + rng.integers(-6, 6, 15).cumsum()}, index=days)


def tracker():
    print(prices)
    print("\n5-day rolling average (last 3 days):\n", prices.rolling(5).mean().tail(3).round(1))
    ch = ((prices.iloc[-1] / prices.iloc[0] - 1) * 100).round(2)
    print("\n% change over 15 days:\n", ch.to_string())
    print("Max single-day rise:", prices.pct_change().mul(100).max().round(2).to_dict())


def category():
    print(inv.groupby("Category").agg(Items=("Item", "count"), Closing=("Closing", "sum"), Value=("Value", "sum")))


def charts():
    prices.plot(subplots=True, layout=(3, 1), figsize=(8, 6), marker=".", title="Daily Price Trend")
    plt.tight_layout(); plt.savefig("stock_trend.png"); plt.show()
    inv.set_index("Item")["Value"].sort_values().plot(kind="barh", color="#00897b", title="Stock Value by Item (Rs.)")
    plt.tight_layout(); plt.savefig("stock_value.png"); plt.show()
    col = ["#c62828" if s == "REORDER" else "#90caf9" for s in inv["Status"]]
    plt.bar(inv["Item"], inv["Closing"], color=col, label="Closing stock")
    plt.plot(inv["Item"], inv["Reorder"], "k--o", label="Reorder level")
    plt.xticks(rotation=45); plt.title("Closing Stock vs Reorder Level (red = reorder)"); plt.legend()
    plt.tight_layout(); plt.savefig("reorder.png"); plt.show()
    print("Charts saved: stock_trend.png, stock_value.png, reorder.png")


def save():
    inv.to_csv("inventory_clean.csv", index=False)
    print("inventory_clean.csv saved with", inv.shape[1], "columns")


menu = {"1": clean, "2": report, "3": reorder, "4": stock_entry, "5": tracker, "6": category, "7": charts, "8": save}
print("=" * 60)
print("INVENTORY & PRICE TRACKER".center(60))
print("=" * 60)
recalc()
while True:
    print("\n1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Goodbye!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Invalid number.")

        
  1. Start
  2. Create DataFrame with NaN / negative values
  3. Clean data
  4. Display menu and read choice
  5. Choice is Stock IN/OUT? → No: run report
  6. Read item, type and quantity
  7. OUT quantity <= closing? → No: 'Insufficient stock'
  8. Update and recalculate
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1CleaningNaN count becomes 0PASS
2Negative purchase -10Converted to 10PASS
3Inventory reportClosing and valuePASS
4Reorder listItems below levelPASS
5Stock IN 50 PenClosing increasesPASS
6Stock OUT more than stockRefusedPASS
7Price trackerRolling mean shownPASS
8Category summaryTotalsPASS
9Charts3 PNG filesPASS
โš  Limitations
  • Sample data only
  • Prices simulated for demo
  • No supplier details
  • Single warehouse
๐Ÿš€ Future scope
  • Barcode based stock entry
  • Live prices from an API
  • Automatic purchase order e-mail
  • ABC analysis

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, numpy - fast arrays and maths are loaded.
  2. Global variables / constants are created: inv, raw.
  3. 9 functions are defined (lines 20โ€“98) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
clean()20โ€“27Cleanmain program (menu)
recalc()30โ€“33Recalcclean(), stock_entry(), main program
report()36โ€“38Reportmain program (menu)
reorder()41โ€“44Reordermain program (menu)
stock_entry()47โ€“61Stock entrymain program (menu)
tracker()71โ€“76Trackermain program (menu)
category()79โ€“80Categorymain program (menu)
charts()83โ€“93Chartsmain program (menu)
save()96โ€“98Savemain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ INVENTORY / STOCK PRICE TRACKER (Pandas + Matplotlib)
9
inv = pd.DataFrame({
    "Item": ["Notebook", "Gel Pen", "Pencil Box", "Geometry Box", "Calculator", "Drawing File", "Eraser", "Marker", "Stapler", "Glue Stiโ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from { "Item": ["Notebook", "Gel Pen", "Pencil Boxโ€ฆ; the result is stored in variable inv
17
raw = inv.copy()
๐Ÿงฎ Store / Calculate Makes a copy of inv; the result is stored in variable raw
64
rng = np.random.default_rng(5)
๐Ÿ“ฆ Library / Data Creates a random number generator with seed 5; the result is stored in variable rng
65
days = pd.date_range("2026-07-01", periods=15, freq="D")
๐Ÿ“ฆ Library / Data Makes a list of dates; the result is stored in variable days
66
prices = pd.DataFrame({"Calculator": 950 + rng.integers(-25, 30, 15).cumsum(),
                       "Geometry Box": 150 + rng.integers(-4, 5, 15).cumsum(),โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Calculator": 950 + rng.integers(-25, 30, 15โ€ฆ; the result is stored in variable prices
101
menu = {"1": clean, "2": report, "3": reorder, "4": stock_entry, "5": tracker, "6": category, "7": charts, "8": save}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": clean, "2": report, "3": reorder, "4": โ€ฆ in variable menu
102
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
103
print("INVENTORY & PRICE TRACKER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "INVENTORY & PRICE TRACKER".center(60) on the screen
104
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
105
recalc()
๐Ÿงฎ Store / Calculate Calls our own function recalc()
106
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
107
print("\n1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Clean 2.Report 3.Reorder 4.Stocโ€ฆ" on the screen
108
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
109
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
110
print("Goodbye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Goodbye!" on the screen
111
break
๐Ÿ” Loop BREAK - leaves the loop immediately
112
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
113
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
114
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
115
print("Invalid number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid number." on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: recalc()
    shows: INVENTORY & PRICE TRACKER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: clean() โ†’ recalc()
    shows: Raw data: (+24 more lines)
  3. You type 2 at Enter choice:
    runs: report()
    shows: Item Opening Purchase Sold Closing Price Value Status (+12 more lines)
  4. You type 3 at Enter choice:
    runs: reorder()
    shows: Item Closing Reorder Order_Qty (+4 more lines)
  5. You type 4 at Enter choice:
    runs: stock_entry()
  6. You type Gel Pen at Item name:
  7. You type IN at IN or OUT:
  8. You type 50 at Quantity:
    runs: recalc()
    shows: Gel Pen: closing stock now 100 (OK) (+1 more lines)
  9. You type 4 at Enter choice:
    runs: stock_entry()
  10. You type Notebook at Item name:
  11. You type OUT at IN or OUT:
  12. You type 500 at Quantity:
    shows: Insufficient stock! Available: 70 (+1 more lines)
  13. You type 4 at Enter choice:
    runs: stock_entry()
  14. You type Notebook at Item name:
  15. You type OUT at IN or OUT:
  16. You type 20 at Quantity:
    runs: recalc()
    shows: Notebook: closing stock now 50 (OK) (+1 more lines)
  17. You type 3 at Enter choice:
    runs: reorder()
    shows: Item Closing Reorder Order_Qty (+3 more lines)
  18. You type 5 at Enter choice:
    runs: tracker()
    shows: Calculator Geometry Box Stapler (+26 more lines)
  19. You type 6 at Enter choice:
    runs: category()
    shows: Items Closing Value (+6 more lines)
  20. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  21. You type 8 at Enter choice:
    runs: save()
    shows: inventory_clean.csv saved with 10 columns (+1 more lines)
  22. You type 0 at Enter choice:
    shows: Goodbye!
โ‘ค Inside each function - line by line
clean() - lines 20โ€“27
LineCodeWhat it does
20
def clean():
๐Ÿงฉ Function DEFINES a function clean(). Python only remembers it here - its body runs later, each time clean() is called.
21
print("Raw data:\n", raw)
๐Ÿ–ฅ๏ธ Output Displays the text "Raw data:", then the value of raw on the screen
22
print("\nMissing values per column:\n", inv.isnull().sum().to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Missing values per column:", then the value of inv.isnull().sum().to_string() on the screen
23
inv["Opening"] = inv["Opening"].fillna(0)
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of inv["Opening"] with 0; the result is put into inv["Opening"] (item "Opening" of inv)
24
inv["Purchase"] = inv["Purchase"].fillna(0).abs()
๐Ÿงฎ Store / Calculate Gives the absolute (positive) value of ; the result is put into inv["Purchase"] (item "Purchase" of inv)
25
inv["Price"] = inv["Price"].fillna(inv["Price"].median())
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of inv["Price"] with inv["Price"].median(); the result is put into inv["Price"] (item "Price" of inv)
26
recalc()
๐Ÿงฎ Store / Calculate Calls our own function recalc()
27
print("\nAfter cleaning - missing:", int(inv.isnull().sum().sum()), "| negative purchase fixed:", (raw["Purchase"] < 0).sum())
๐Ÿ–ฅ๏ธ Output Displays the text "After cleaning - missing:", then the value of int(inv.isnull().sum().sum()), then the text "| negative purchase fixed:", then the value of (raw["Purchase"] < 0).sum() on the screen
recalc() - lines 30โ€“33
LineCodeWhat it does
30
def recalc():
๐Ÿงฉ Function DEFINES a function recalc(). Python only remembers it here - its body runs later, each time recalc() is called.
31
inv["Closing"] = (inv["Opening"] + inv["Purchase"] - inv["Sold"]).fillna(0).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of (inv["Opening"] + inv["Purchase"] - inv["Soldโ€ฆ to int; the result is put into inv["Closing"] (item "Closing" of inv)
32
inv["Value"] = inv["Closing"] * inv["Price"]
๐Ÿงฎ Store / Calculate Puts the value of inv["Closing"] * inv["Price"] (calculated using ร—) into inv["Value"] (item "Value" of inv)
33
inv["Status"] = np.where(inv["Closing"] < inv["Reorder"], "REORDER", "OK")
๐Ÿ“ฆ Library / Data Chooses values depending on condition inv["Closing"] < inv["Reorder"]; the result is put into inv["Status"] (item "Status" of inv)
report() - lines 36โ€“38
LineCodeWhat it does
36
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
37
print(inv[["Item", "Opening", "Purchase", "Sold", "Closing", "Price", "Value", "Status"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of inv[["Item", "Opening", "Purchase", "Sold", "โ€ฆ on the screen
38
print(f"\nTotal stock value: Rs. {inv['Value'].sum():,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nTotal stock value: Rs. {inv['Value'].sum(โ€ฆ with the values filled into { } on the screen
reorder() - lines 41โ€“44
LineCodeWhat it does
41
def reorder():
๐Ÿงฉ Function DEFINES a function reorder(). Python only remembers it here - its body runs later, each time reorder() is called.
42
r = inv[inv["Status"] == "REORDER"].copy()
๐Ÿงฎ Store / Calculate Makes a copy of inv[inv["Status"] == "REORDER"]; the result is stored in variable r
43
r["Order_Qty"] = r["Reorder"] * 2 - r["Closing"]
๐Ÿงฎ Store / Calculate Puts the value of r["Reorder"] * 2 - r["Closing"] (calculated using -) into r["Order_Qty"] (item "Order_Qty" of r)
44
print(r[["Item", "Closing", "Reorder", "Order_Qty"]].to_string(index=False) if len(r) else "Nothing to reorder.")
๐Ÿ–ฅ๏ธ Output Displays the value of r[["Item", "Closing", "Reorder", "Order_Qty"]โ€ฆ on the screen
stock_entry() - lines 47โ€“61
LineCodeWhat it does
47
def stock_entry():
๐Ÿงฉ Function DEFINES a function stock_entry(). Python only remembers it here - its body runs later, each time stock_entry() is called.
48
item = input("Item name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable item
49
typ = input("IN or OUT: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable typ
50
qty = int(input("Quantity: "))
โŒจ๏ธ Input Shows "Quantity: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable qty
51
m = inv["Item"].str.title() == item
๐Ÿงฎ Store / Calculate Stores True/False for inv["Item"].str.title() is equal to item in variable m
52
if not m.any():
๐Ÿ”€ Decision CHECKS whether NOT m.any() is True. If True, the indented lines below run; otherwise they are skipped
53
print("Item not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Item not found." on the screen
54
return
๐Ÿงฉ Function Ends the function and goes back to the caller
55
i = inv.index[m][0]
๐Ÿงฎ Store / Calculate Stores the item inv.index[m][0] in variable i
56
if typ == "OUT" and qty > inv.loc[i, "Closing"]:
๐Ÿ”€ Decision CHECKS whether (typ is equal to "OUT" AND qty is greater than inv.loc[i, "Closing"]). If True, the indented lines below run; otherwise they are skipped
57
print("Insufficient stock! Available:", inv.loc[i, "Closing"])
๐Ÿ–ฅ๏ธ Output Displays the text "Insufficient stock! Available:", then the value of inv.loc[i, "Closing"] on the screen
58
return
๐Ÿงฉ Function Ends the function and goes back to the caller
59
inv.loc[i, "Purchase" if typ == "IN" else "Sold"] += qty
๐Ÿงฎ Store / Calculate Adds qty to inv.loc[i, "Purchase" if typ == "IN" else "Soโ€ฆ (same as inv.loc[i, "Purchase" if typ == "IN" else "Sold"] = inv.loc[i, "Purchase" if typ == "IN" else "Sold"] + qty)
60
recalc()
๐Ÿงฎ Store / Calculate Calls our own function recalc()
61
print(f"{item}: closing stock now {inv.loc[i, 'Closing']} ({inv.loc[i, 'Status']})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{item}: closing stock now {inv.loc[i, 'Closโ€ฆ with the values filled into { } on the screen
tracker() - lines 71โ€“76
LineCodeWhat it does
71
def tracker():
๐Ÿงฉ Function DEFINES a function tracker(). Python only remembers it here - its body runs later, each time tracker() is called.
72
print(prices)
๐Ÿ–ฅ๏ธ Output Displays the value of prices on the screen
73
print("\n5-day rolling average (last 3 days):\n", prices.rolling(5).mean().tail(3).round(1))
๐Ÿ–ฅ๏ธ Output Displays the text "5-day rolling average (last 3 dayโ€ฆ", then the value of prices.rolling(5).mean().tail(3).round(1) on the screen
74
ch = ((prices.iloc[-1] / prices.iloc[0] - 1) * 100).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of (prices.iloc[-1] / prices.iloc[0] - 1) * 100 to 2 decimal places; the result is stored in variable ch
75
print("\n% change over 15 days:\n", ch.to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "% change over 15 days:", then the value of ch.to_string() on the screen
76
print("Max single-day rise:", prices.pct_change().mul(100).max().round(2).to_dict())
๐Ÿ–ฅ๏ธ Output Displays the text "Max single-day rise:", then the value of prices.pct_change().mul(100).max().round(2).tโ€ฆ on the screen
category() - lines 79โ€“80
LineCodeWhat it does
79
def category():
๐Ÿงฉ Function DEFINES a function category(). Python only remembers it here - its body runs later, each time category() is called.
80
print(inv.groupby("Category").agg(Items=("Item", "count"), Closing=("Closing", "sum"), Value=("Value", "sum")))
๐Ÿ–ฅ๏ธ Output Displays the value of inv.groupby("Category").agg(Items=("Item", "cโ€ฆ on the screen
charts() - lines 83โ€“93
LineCodeWhat it does
83
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
84
prices.plot(subplots=True, layout=(3, 1), figsize=(8, 6), marker=".", title="Daily Price Trend")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
85
plt.tight_layout(); plt.savefig("stock_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
85
plt.tight_layout(); plt.savefig("stock_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "stock_trend.png"
85
plt.tight_layout(); plt.savefig("stock_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
86
inv.set_index("Item")["Value"].sort_values().plot(kind="barh", color="#00897b", title="Stock Value by Item (Rs.)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
87
plt.tight_layout(); plt.savefig("stock_value.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
87
plt.tight_layout(); plt.savefig("stock_value.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "stock_value.png"
87
plt.tight_layout(); plt.savefig("stock_value.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
col = ["#c62828" if s == "REORDER" else "#90caf9" for s in inv["Status"]]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension ["#c62828" if s == "REORDER" else "#90caf9" fโ€ฆ in variable col
89
plt.bar(inv["Item"], inv["Closing"], color=col, label="Closing stock")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of inv["Item"], inv["Closing"]
90
plt.plot(inv["Item"], inv["Reorder"], "k--o", label="Reorder level")
๐Ÿ–ฅ๏ธ Output Draws a line chart of inv["Item"], inv["Reorder"], "k--o"
91
plt.xticks(rotation=45); plt.title("Closing Stock vs Reorder Level (red = reorder)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
91
plt.xticks(rotation=45); plt.title("Closing Stock vs Reorder Level (red = reorder)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Closing Stock vs Reorder Level (red = reordeโ€ฆ as the title of the chart
91
plt.xticks(rotation=45); plt.title("Closing Stock vs Reorder Level (red = reorder)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
92
plt.tight_layout(); plt.savefig("reorder.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
92
plt.tight_layout(); plt.savefig("reorder.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "reorder.png"
92
plt.tight_layout(); plt.savefig("reorder.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
93
print("Charts saved: stock_trend.png, stock_value.png, reorder.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: stock_trend.png, stโ€ฆ" on the screen
save() - lines 96โ€“98
LineCodeWhat it does
96
def save():
๐Ÿงฉ Function DEFINES a function save(). Python only remembers it here - its body runs later, each time save() is called.
97
inv.to_csv("inventory_clean.csv", index=False)
๐Ÿงฎ Store / Calculate Saves the DataFrame into CSV file "inventory_clean.csv"
98
print("inventory_clean.csv saved with", inv.shape[1], "columns")
๐Ÿ–ฅ๏ธ Output Displays the text "inventory_clean.csv saved with", then the value of inv.shape[1], then the text "columns" on the screen
Q1. How do you find missing values?

df.isnull().sum() counts NaN values in each column.

Q2. How are missing values filled?

df['col'].fillna(value) - here with 0 for quantity and with the median for price.

Q3. How are negative values corrected?

Using abs() or clip(lower=0) depending on meaning; here wrong-sign entries are made positive with abs().

Q4. What is a rolling mean?

Average of the last n values moving one step at a time - smooths daily price changes.

Q5. What does pct_change() give?

Percentage change from the previous row.

06

Weather Data Analysis (Delhi)

PYTHON + PANDASDataFrame creationdescriptive statisticsidxmax/idxminboolean filteringMatplotlib line + bar charts
๐Ÿ“ 102 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 146 output lines๐Ÿ“„ 25+ page report

Analyses a year of monthly temperature, rainfall and humidity: finds the hottest and wettest month, filters monsoon months and plots two charts.

โœจ Features
  • Daily weather of Delhi for July 2026 (31 days) - max / min temperature, humidity, rainfall - built with date_range
  • Descriptive statistics and hottest / coolest / wettest day with idxmax / idxmin
  • Weekly summary using resample('W') and heat-wave / rainy-day filtering
  • Day classification (Hot, Humid, Rainy, Pleasant) with a function and value_counts
  • Search weather of any date; temperature range calculated column
  • Line, bar, scatter and pie charts
โ˜ฐ Main menu
1Show DataFull month DataFrame
2Statisticsdescribe()
3ExtremesHottest, coolest, wettest days
4Weekly Summaryresample('W')
5Filter DaysHot days / rainy days
6Search Dateloc[] on date index
7Day Typesapply + value_counts
8Charts4 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Use describe(), idxmax() and idxmin()
  • Filter rows with boolean conditions
  • Create line and bar charts with labels
๐Ÿ“š Data dictionary
NameTypePurpose
wDataFrameDate index; MaxT, MinT, Humidity, Rain_mm
RangecolumnMaxT - MinT
TypecolumnWeather type from rules
weeklyDataFrameWeekly mean / sum
Why it matters: An environmental-data project that uses nearly every Pandas operation prescribed in the syllabus.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import numpy as np
# =====================================================================
#   WEATHER DATA ANALYSIS - DELHI, JULY 2026  (Pandas + Matplotlib)
# =====================================================================
rng = np.random.default_rng(11)
dates = pd.date_range("2026-07-01", "2026-07-31", freq="D")
maxt = np.round(np.linspace(39, 33, 31) + rng.normal(0, 1.6, 31), 1)
rain = np.where(rng.random(31) < 0.42, np.round(rng.gamma(2, 9, 31), 1), 0.0)
w = pd.DataFrame({"MaxT": maxt, "MinT": np.round(maxt - rng.uniform(6, 10, 31), 1),
                  "Humidity": np.clip(np.round(55 + rain * 0.8 + rng.normal(8, 6, 31)), 40, 98).astype(int),
                  "Rain_mm": rain}, index=dates)
w.index.name = "Date"
w["Range"] = (w["MaxT"] - w["MinT"]).round(1)


def kind(r):
    if r.Rain_mm >= 10:
        return "Rainy"
    if r.MaxT >= 38:
        return "Hot"
    if r.Humidity >= 75:
        return "Humid"
    return "Pleasant"


w["Type"] = w.apply(kind, axis=1)


def show():
    print(w)


def stats():
    print(w[["MaxT", "MinT", "Humidity", "Rain_mm", "Range"]].describe().round(2))
    print(f"\nTotal rainfall: {w['Rain_mm'].sum():.1f} mm on {(w['Rain_mm'] > 0).sum()} days")


def extremes():
    print("Hottest day :", w["MaxT"].idxmax().date(), "-", w["MaxT"].max(), "C")
    print("Coolest night:", w["MinT"].idxmin().date(), "-", w["MinT"].min(), "C")
    print("Wettest day :", w["Rain_mm"].idxmax().date(), "-", w["Rain_mm"].max(), "mm")
    print("Most humid  :", w["Humidity"].idxmax().date(), "-", w["Humidity"].max(), "%")


def weekly():
    wk = w.resample("W").agg({"MaxT": "mean", "MinT": "mean", "Humidity": "mean", "Rain_mm": "sum"}).round(1)
    wk.index = wk.index.strftime("Week ending %d-%b")
    print(wk)


def filt():
    t = input("Filter hot / rain: ").strip().lower()
    r = w[w["MaxT"] >= 38] if t == "hot" else w[w["Rain_mm"] > 0]
    print(r[["MaxT", "Humidity", "Rain_mm", "Type"]])
    print(len(r), "days found")


def search():
    d = input("Date (yyyy-mm-dd): ").strip()
    try:
        print(w.loc[d].to_string())
    except KeyError:
        print("No data for", d)


def types():
    print(w["Type"].value_counts().to_string())
    print("\nAverage max temp by type:\n", w.groupby("Type")["MaxT"].mean().round(1).to_string())


def charts():
    plt.plot(w.index.day, w["MaxT"], "r-o", label="Max", markersize=4)
    plt.plot(w.index.day, w["MinT"], "b-o", label="Min", markersize=4)
    plt.fill_between(w.index.day, w["MinT"], w["MaxT"], color="orange", alpha=.15)
    plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
    plt.tight_layout(); plt.savefig("temperature.png"); plt.show()
    plt.bar(w.index.day, w["Rain_mm"], color="#1e88e5"); plt.title("Daily Rainfall (mm)"); plt.xlabel("Day")
    plt.tight_layout(); plt.savefig("rainfall.png"); plt.show()
    plt.scatter(w["Humidity"], w["MaxT"], c=w["Rain_mm"], cmap="Blues", edgecolors="k")
    plt.colorbar(label="Rain mm"); plt.title("Humidity vs Max Temperature"); plt.xlabel("Humidity %"); plt.ylabel("Max temp")
    plt.tight_layout(); plt.savefig("humidity_scatter.png"); plt.show()
    w["Type"].value_counts().plot(kind="pie", autopct="%1.0f%%", colors=["#ffb74d", "#64b5f6", "#81c784", "#e57373"], title="Type of Days")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("weather_types.png"); plt.show()
    print("Charts saved: temperature.png, rainfall.png, humidity_scatter.png, weather_types.png")


menu = {"1": show, "2": stats, "3": extremes, "4": weekly, "5": filt, "6": search, "7": types, "8": charts}
print("=" * 60)
print("WEATHER DATA ANALYSIS - DELHI".center(60))
print("=" * 60)
while True:
    print("\n1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Stay safe in the weather!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Create date-indexed DataFrame
  3. Add Range and Type columns
  4. Display menu and read choice
  5. Valid option? → No: 'Invalid choice'
  6. Analyse / filter / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Show data31 rowsPASS
2StatisticsMean max temp shownPASS
3ExtremesDates of max / minPASS
4Weekly5 weeksPASS
5Filter hot (>=38)Hot days listedPASS
6Search 2026-07-15That day's weatherPASS
7Search 2026-08-01'No data'PASS
8Day typesCounts of each typePASS
9Charts4 PNG filesPASS
โš  Limitations
  • Data generated to look like Delhi July weather (not official IMD values)
  • One city only
  • No forecasting
  • Daily data only
๐Ÿš€ Future scope
  • Download IMD / open-meteo data
  • Compare cities
  • Simple forecast with moving average
  • Monsoon onset analysis over years

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, numpy - fast arrays and maths are loaded.
  2. Global variables / constants are created: rng, dates, maxt, rain, w.
  3. 9 functions are defined (lines 20โ€“88) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
kind(r)20โ€“27Kindmain program (menu)
show()33โ€“34Showmain program (menu)
stats()37โ€“39Statsmain program (menu)
extremes()42โ€“46Extremesmain program (menu)
weekly()49โ€“52Weeklymain program (menu)
filt()55โ€“59Filtmain program (menu)
search()62โ€“67Searchmain program (menu)
types()70โ€“72Typesmain program (menu)
charts()75โ€“88Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ WEATHER DATA ANALYSIS - DELHI, JULY 2026 (Pandas + Matplotlib)
9
rng = np.random.default_rng(11)
๐Ÿ“ฆ Library / Data Creates a random number generator with seed 11; the result is stored in variable rng
10
dates = pd.date_range("2026-07-01", "2026-07-31", freq="D")
๐Ÿ“ฆ Library / Data Makes a list of dates; the result is stored in variable dates
11
maxt = np.round(np.linspace(39, 33, 31) + rng.normal(0, 1.6, 31), 1)
๐Ÿ“ฆ Library / Data Rounds the values of np to np.linspace(39, 33, 31) + rng.normal(0, 1.6, โ€ฆ decimal places; the result is stored in variable maxt
12
rain = np.where(rng.random(31) < 0.42, np.round(rng.gamma(2, 9, 31), 1), 0.0)
๐Ÿ“ฆ Library / Data Chooses values depending on condition rng.random(31) < 0.42; the result is stored in variable rain
13
w = pd.DataFrame({"MaxT": maxt, "MinT": np.round(maxt - rng.uniform(6, 10, 31), 1),
                  "Humidity": np.clip(np.round(55 + rain * 0.8 + rng.normโ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"MaxT": maxt, "MinT": np.round(maxt - rng.unโ€ฆ; the result is stored in variable w
16
w.index.name = "Date"
๐Ÿงฎ Store / Calculate Stores the text "Date" in w.index.name
17
w["Range"] = (w["MaxT"] - w["MinT"]).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of w["MaxT"] - w["MinT"] to 1 decimal places; the result is put into w["Range"] (item "Range" of w)
30
w["Type"] = w.apply(kind, axis=1)
๐Ÿงฎ Store / Calculate Applies kind on every value/row of w; the result is put into w["Type"] (item "Type" of w)
91
menu = {"1": show, "2": stats, "3": extremes, "4": weekly, "5": filt, "6": search, "7": types, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": show, "2": stats, "3": extremes, "4": wโ€ฆ in variable menu
92
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
93
print("WEATHER DATA ANALYSIS - DELHI".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "WEATHER DATA ANALYSIS - DELHI".center(60) on the screen
94
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
95
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
96
print("\n1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Stats 3.Extremes 4.Weeklโ€ฆ" on the screen
97
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
98
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
99
print("Stay safe in the weather!")
๐Ÿ–ฅ๏ธ Output Displays the text "Stay safe in the weather!" on the screen
100
break
๐Ÿ” Loop BREAK - leaves the loop immediately
101
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: kind() ร—31
    shows: WEATHER DATA ANALYSIS - DELHI (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show()
    shows: MaxT MinT Humidity Rain_mm Range Type (+33 more lines)
  3. You type 2 at Enter choice:
    runs: stats()
    shows: MaxT MinT Humidity Rain_mm Range (+10 more lines)
  4. You type 3 at Enter choice:
    runs: extremes()
    shows: Hottest day : 2026-07-02 - 41.0 C (+4 more lines)
  5. You type 4 at Enter choice:
    runs: weekly()
    shows: MaxT MinT Humidity Rain_mm (+7 more lines)
  6. You type 5 at Enter choice:
    runs: filt()
  7. You type hot at Filter hot / rain:
    shows: MaxT Humidity Rain_mm Type (+9 more lines)
  8. You type 5 at Enter choice:
    runs: filt()
  9. You type rain at Filter hot / rain:
    shows: MaxT Humidity Rain_mm Type (+21 more lines)
  10. You type 6 at Enter choice:
    runs: search()
  11. You type 2026-07-15 at Date (yyyy-mm-dd):
    shows: MaxT 35.6 (+6 more lines)
  12. You type 6 at Enter choice:
    runs: search()
  13. You type 2026-08-01 at Date (yyyy-mm-dd):
    shows: No data for 2026-08-01 (+1 more lines)
  14. You type 7 at Enter choice:
    runs: types()
    shows: Type (+11 more lines)
  15. You type 8 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+5 more lines)
  16. You type 0 at Enter choice:
    shows: Stay safe in the weather!
โ‘ค Inside each function - line by line
kind() - lines 20โ€“27
LineCodeWhat it does
20
def kind(r):
๐Ÿงฉ Function DEFINES a function kind(r). Python only remembers it here - its body runs later, each time kind() is called.
21
if r.Rain_mm >= 10:
๐Ÿ”€ Decision CHECKS whether r.Rain_mm is greater than or equal to 10. If True, the indented lines below run; otherwise they are skipped
22
return "Rainy"
๐Ÿงฉ Function Sends back (returns) the text "Rainy" to the line that called the function
23
if r.MaxT >= 38:
๐Ÿ”€ Decision CHECKS whether r.MaxT is greater than or equal to 38. If True, the indented lines below run; otherwise they are skipped
24
return "Hot"
๐Ÿงฉ Function Sends back (returns) the text "Hot" to the line that called the function
25
if r.Humidity >= 75:
๐Ÿ”€ Decision CHECKS whether r.Humidity is greater than or equal to 75. If True, the indented lines below run; otherwise they are skipped
26
return "Humid"
๐Ÿงฉ Function Sends back (returns) the text "Humid" to the line that called the function
27
return "Pleasant"
๐Ÿงฉ Function Sends back (returns) the text "Pleasant" to the line that called the function
show() - lines 33โ€“34
LineCodeWhat it does
33
def show():
๐Ÿงฉ Function DEFINES a function show(). Python only remembers it here - its body runs later, each time show() is called.
34
print(w)
๐Ÿ–ฅ๏ธ Output Displays the value of w on the screen
stats() - lines 37โ€“39
LineCodeWhat it does
37
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
38
print(w[["MaxT", "MinT", "Humidity", "Rain_mm", "Range"]].describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of w[["MaxT", "MinT", "Humidity", "Rain_mm", "Raโ€ฆ on the screen
39
print(f"\nTotal rainfall: {w['Rain_mm'].sum():.1f} mm on {(w['Rain_mm'] > 0).sum()} days")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nTotal rainfall: {w['Rain_mm'].sum():.1f} โ€ฆ with the values filled into { } on the screen
extremes() - lines 42โ€“46
LineCodeWhat it does
42
def extremes():
๐Ÿงฉ Function DEFINES a function extremes(). Python only remembers it here - its body runs later, each time extremes() is called.
43
print("Hottest day :", w["MaxT"].idxmax().date(), "-", w["MaxT"].max(), "C")
๐Ÿ–ฅ๏ธ Output Displays the text "Hottest day :", then the value of w["MaxT"].idxmax().date(), then the text "-", then the value of w["MaxT"].max(), then the text "C" on the screen
44
print("Coolest night:", w["MinT"].idxmin().date(), "-", w["MinT"].min(), "C")
๐Ÿ–ฅ๏ธ Output Displays the text "Coolest night:", then the value of w["MinT"].idxmin().date(), then the text "-", then the value of w["MinT"].min(), then the text "C" on the screen
45
print("Wettest day :", w["Rain_mm"].idxmax().date(), "-", w["Rain_mm"].max(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Wettest day :", then the value of w["Rain_mm"].idxmax().date(), then the text "-", then the value of w["Rain_mm"].max(), then the text "mm" on the screen
46
print("Most humid  :", w["Humidity"].idxmax().date(), "-", w["Humidity"].max(), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Most humid :", then the value of w["Humidity"].idxmax().date(), then the text "-", then the value of w["Humidity"].max(), then the text "%" on the screen
weekly() - lines 49โ€“52
LineCodeWhat it does
49
def weekly():
๐Ÿงฉ Function DEFINES a function weekly(). Python only remembers it here - its body runs later, each time weekly() is called.
50
wk = w.resample("W").agg({"MaxT": "mean", "MinT": "mean", "Humidity": "mean", "Rain_mm": "sum"}).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of w.resample("W").agg({"MaxT": "mean", "MinT": โ€ฆ to 1 decimal places; the result is stored in variable wk
51
wk.index = wk.index.strftime("Week ending %d-%b")
๐Ÿงฎ Store / Calculate Formats the date as text; the result is stored in wk.index
52
print(wk)
๐Ÿ–ฅ๏ธ Output Displays the value of wk on the screen
filt() - lines 55โ€“59
LineCodeWhat it does
55
def filt():
๐Ÿงฉ Function DEFINES a function filt(). Python only remembers it here - its body runs later, each time filt() is called.
56
t = input("Filter hot / rain: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable t
57
r = w[w["MaxT"] >= 38] if t == "hot" else w[w["Rain_mm"] > 0]
๐Ÿงฎ Store / Calculate Stores either w[w["MaxT"] >= 38] or w[w["Rain_mm"] > 0] depending on t == "hot" in variable r
58
print(r[["MaxT", "Humidity", "Rain_mm", "Type"]])
๐Ÿ–ฅ๏ธ Output Displays the value of r[["MaxT", "Humidity", "Rain_mm", "Type"]] on the screen
59
print(len(r), "days found")
๐Ÿ–ฅ๏ธ Output Displays the value of len(r), then the text "days found" on the screen
search() - lines 62โ€“67
LineCodeWhat it does
62
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
63
d = input("Date (yyyy-mm-dd): ").strip()
โŒจ๏ธ Input Shows "Date (yyyy-mm-dd): ", reads the typed text, removes extra spaces (strip) and stores it in variable d
64
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
65
print(w.loc[d].to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of w.loc[d].to_string() on the screen
66
except KeyError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if KeyError occurs - a key that is not in the dictionary
67
print("No data for", d)
๐Ÿ–ฅ๏ธ Output Displays the text "No data for", then the value of d on the screen
types() - lines 70โ€“72
LineCodeWhat it does
70
def types():
๐Ÿงฉ Function DEFINES a function types(). Python only remembers it here - its body runs later, each time types() is called.
71
print(w["Type"].value_counts().to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of w["Type"].value_counts().to_string() on the screen
72
print("\nAverage max temp by type:\n", w.groupby("Type")["MaxT"].mean().round(1).to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Average max temp by type:", then the value of w.groupby("Type")["MaxT"].mean().round(1).to_โ€ฆ on the screen
charts() - lines 75โ€“88
LineCodeWhat it does
75
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
76
plt.plot(w.index.day, w["MaxT"], "r-o", label="Max", markersize=4)
๐Ÿ–ฅ๏ธ Output Draws a line chart of w.index.day, w["MaxT"], "r-o"
77
plt.plot(w.index.day, w["MinT"], "b-o", label="Min", markersize=4)
๐Ÿ–ฅ๏ธ Output Draws a line chart of w.index.day, w["MinT"], "b-o"
78
plt.fill_between(w.index.day, w["MinT"], w["MaxT"], color="orange", alpha=.15)
๐Ÿ–ฅ๏ธ Output Shades the area between lines
79
plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Delhi Temperature - July 2026" as the title of the chart
79
plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Day" as the label of the X-axis
79
plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "deg C" as the label of the Y-axis
79
plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
79
plt.title("Delhi Temperature - July 2026"); plt.xlabel("Day"); plt.ylabel("deg C"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
80
plt.tight_layout(); plt.savefig("temperature.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
80
plt.tight_layout(); plt.savefig("temperature.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "temperature.png"
80
plt.tight_layout(); plt.savefig("temperature.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
plt.bar(w.index.day, w["Rain_mm"], color="#1e88e5"); plt.title("Daily Rainfall (mm)"); plt.xlabel("Day")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of w.index.day, w["Rain_mm"]
81
plt.bar(w.index.day, w["Rain_mm"], color="#1e88e5"); plt.title("Daily Rainfall (mm)"); plt.xlabel("Day")
๐Ÿ–ฅ๏ธ Output Writes "Daily Rainfall (mm)" as the title of the chart
81
plt.bar(w.index.day, w["Rain_mm"], color="#1e88e5"); plt.title("Daily Rainfall (mm)"); plt.xlabel("Day")
๐Ÿ–ฅ๏ธ Output Writes "Day" as the label of the X-axis
82
plt.tight_layout(); plt.savefig("rainfall.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
82
plt.tight_layout(); plt.savefig("rainfall.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "rainfall.png"
82
plt.tight_layout(); plt.savefig("rainfall.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
83
plt.scatter(w["Humidity"], w["MaxT"], c=w["Rain_mm"], cmap="Blues", edgecolors="k")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of w["Humidity"], w["MaxT"]
84
plt.colorbar(label="Rain mm"); plt.title("Humidity vs Max Temperature"); plt.xlabel("Humidity %"); plt.ylabel("Max temp")
๐Ÿ–ฅ๏ธ Output Shows a colour scale bar
84
plt.colorbar(label="Rain mm"); plt.title("Humidity vs Max Temperature"); plt.xlabel("Humidity %"); plt.ylabel("Max temp")
๐Ÿ–ฅ๏ธ Output Writes "Humidity vs Max Temperature" as the title of the chart
84
plt.colorbar(label="Rain mm"); plt.title("Humidity vs Max Temperature"); plt.xlabel("Humidity %"); plt.ylabel("Max temp")
๐Ÿ–ฅ๏ธ Output Writes "Humidity %" as the label of the X-axis
84
plt.colorbar(label="Rain mm"); plt.title("Humidity vs Max Temperature"); plt.xlabel("Humidity %"); plt.ylabel("Max temp")
๐Ÿ–ฅ๏ธ Output Writes "Max temp" as the label of the Y-axis
85
plt.tight_layout(); plt.savefig("humidity_scatter.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
85
plt.tight_layout(); plt.savefig("humidity_scatter.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "humidity_scatter.png"
85
plt.tight_layout(); plt.savefig("humidity_scatter.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
86
w["Type"].value_counts().plot(kind="pie", autopct="%1.0f%%", colors=["#ffb74d", "#64b5f6", "#81c784", "#e57373"], title="Type of Days")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
87
plt.ylabel(""); plt.tight_layout(); plt.savefig("weather_types.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
87
plt.ylabel(""); plt.tight_layout(); plt.savefig("weather_types.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
87
plt.ylabel(""); plt.tight_layout(); plt.savefig("weather_types.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "weather_types.png"
87
plt.ylabel(""); plt.tight_layout(); plt.savefig("weather_types.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
print("Charts saved: temperature.png, rainfall.png, humidity_scatter.png, weather_types.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: temperature.png, raโ€ฆ" on the screen
Q1. What is date_range()?

Creates a sequence of dates, used here as the DataFrame index for 31 days.

Q2. What does resample('W') do?

Groups a date-indexed DataFrame into weeks so mean() or sum() can be found per week.

Q3. How are hot days found?

Boolean indexing: w[w['MaxT'] >= 38].

Q4. What is idxmax()?

Returns the index (date) where a column has its maximum value.

Q5. Why use a scatter plot?

To see the relation between two numeric variables - here humidity and temperature.

07

Retail Sales Analysis (CSV)

PYTHON + PANDASCSV import/exportcalculated columngroupby/aggsort_valuespivot of monthly totals
๐Ÿ“ 107 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 107 output lines๐Ÿ“„ 25+ page report

Reads a shop's sales file, calculates revenue per sale, ranks products and categories, finds the best month and exports a summary report to CSV.

โœจ Features
  • 120 sales transactions (Jan-Jun) generated and saved to sales.csv, then imported with read_csv()
  • Calculated columns: Revenue = Qty x Price, Month name, Discount and Net
  • groupby / agg for category, region and salesperson performance
  • pivot_table of monthly revenue by region and month-on-month growth
  • Top products with nlargest and salesperson ranking
  • Exports summary to sales_summary.csv; 4 charts
โ˜ฐ Main menu
1Preview Datahead(), shape, dtypes
2Category Summarygroupby + agg
3Monthly Pivotpivot_table Region x Month
4Growthpct_change of monthly totals
5Top Productsnlargest(5)
6Salesperson Rankingsum + rank
7FilterBy region and minimum revenue
8Charts4 charts
9Export Summaryto_csv()
0ExitEnds program
๐ŸŽฏ Objectives
  • Import and export CSV files
  • Add calculated columns and use groupby() with sort_values()
  • Visualise trends and shares with charts
๐Ÿ“š Data dictionary
NameTypePurpose
salesDataFrameOrderID, Date, Region, Category, Product, Qty, Price, Salesperson
Revenue / NetcolumnQty x Price and after discount
sales.csvCSV fileRaw transactions
sales_summary.csvCSV fileExported category summary
Why it matters: A real business-analytics workflow: import CSV, clean, aggregate, visualise and export.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import numpy as np
# =====================================================================
#   RETAIL SALES ANALYSIS  (CSV + Pandas + Matplotlib)
# =====================================================================
rng = np.random.default_rng(42)
PRODUCTS = {"Electronics": [("Smartphone", 15999), ("Earbuds", 1999), ("Smart Watch", 3499)],
            "Clothing": [("Kurta", 899), ("Jeans", 1499), ("Jacket", 2499)],
            "Grocery": [("Basmati Rice 5kg", 649), ("Mustard Oil 1L", 189), ("Tea 500g", 245)],
            "Stationery": [("Notebook Pack", 320), ("Pen Set", 150), ("School Bag", 899)]}
rows = []
for i in range(120):
    cat = rng.choice(list(PRODUCTS))
    prod, price = PRODUCTS[cat][rng.integers(0, 3)]
    rows.append([1001 + i, pd.Timestamp("2026-01-01") + pd.Timedelta(days=int(rng.integers(0, 181))),
                 rng.choice(["North", "South", "East", "West"]), cat, prod, int(rng.integers(1, 8)), price,
                 rng.choice(["Asha", "Bharat", "Chetan", "Deepa", "Ehsaan"])])
pd.DataFrame(rows, columns=["OrderID", "Date", "Region", "Category", "Product", "Qty", "Price", "Salesperson"]).to_csv("sales.csv", index=False)

sales = pd.read_csv("sales.csv", parse_dates=["Date"])
sales["Revenue"] = sales["Qty"] * sales["Price"]
sales["Discount"] = np.where(sales["Revenue"] > 20000, 0.05, 0) * sales["Revenue"]
sales["Net"] = sales["Revenue"] - sales["Discount"]
sales["Month"] = sales["Date"].dt.strftime("%m-%b")


def preview():
    print("Shape:", sales.shape)
    print(sales.head(8).to_string(index=False))
    print("\nData types:\n", sales.dtypes.to_string())


def category():
    c = sales.groupby("Category").agg(Orders=("OrderID", "count"), Units=("Qty", "sum"), Revenue=("Net", "sum"), Avg_Order=("Net", "mean"))
    c["Share_%"] = (c["Revenue"] / c["Revenue"].sum() * 100).round(1)
    print(c.sort_values("Revenue", ascending=False).round(0))
    print(f"\nTotal net revenue: Rs. {sales['Net'].sum():,.0f}")


def pivot():
    p = sales.pivot_table(index="Region", columns="Month", values="Net", aggfunc="sum", fill_value=0).round(0)
    p["Total"] = p.sum(axis=1)
    print(p.sort_values("Total", ascending=False))


def growth():
    m = sales.groupby("Month")["Net"].sum()
    g = pd.DataFrame({"Revenue": m.round(0), "Growth_%": (m.pct_change() * 100).round(1)})
    print(g.fillna("-"))
    print("Best month:", m.idxmax(), "| Weakest:", m.idxmin())


def top_products():
    t = sales.groupby(["Category", "Product"])["Net"].sum().nlargest(5).round(0)
    print(t.to_string())


def ranking():
    r = sales.groupby("Salesperson").agg(Orders=("OrderID", "count"), Revenue=("Net", "sum"))
    r["Rank"] = r["Revenue"].rank(ascending=False).astype(int)
    print(r.sort_values("Rank").round(0))


def filt():
    reg = input("Region: ").strip().title()
    v = float(input("Minimum net revenue: "))
    r = sales[(sales["Region"] == reg) & (sales["Net"] >= v)]
    print(r[["OrderID", "Date", "Product", "Qty", "Net"]].to_string(index=False))
    print(len(r), "orders | total Rs.", round(r["Net"].sum()))


def charts():
    m = sales.groupby("Month")["Net"].sum() / 1000
    plt.plot(m.index, m.values, "g-o", linewidth=2); plt.title("Monthly Net Revenue (Rs. thousand)")
    plt.grid(alpha=.3); plt.tight_layout(); plt.savefig("monthly_revenue.png"); plt.show()
    sales.groupby("Category")["Net"].sum().plot(kind="pie", autopct="%1.1f%%", explode=[0.05] * 4, title="Category Share")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("category_share.png"); plt.show()
    (sales.pivot_table(index="Month", columns="Region", values="Net", aggfunc="sum") / 1000).plot(kind="bar", title="Region-wise Monthly Revenue (Rs. thousand)")
    plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("region_month.png"); plt.show()
    sales.groupby("Product")["Net"].sum().nlargest(5).sort_values().plot(kind="barh", color="#6a1b9a", title="Top 5 Products")
    plt.tight_layout(); plt.savefig("top_products.png"); plt.show()
    print("Charts saved: monthly_revenue.png, category_share.png, region_month.png, top_products.png")


def export():
    sales.groupby("Category")[["Qty", "Revenue", "Discount", "Net"]].sum().to_csv("sales_summary.csv")
    print(open("sales_summary.csv").read())


menu = {"1": preview, "2": category, "3": pivot, "4": growth, "5": top_products, "6": ranking, "7": filt, "8": charts, "9": export}
print("=" * 60)
print("RETAIL SALES ANALYSIS (Jan - Jun 2026)".center(60))
print("=" * 60)
while True:
    print("\n1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Report complete.")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except ValueError:
        print("Invalid value.")

        
  1. Start
  2. Generate data, save sales.csv, read it back
  3. Add calculated columns
  4. Display menu and read choice
  5. Valid option? → No: 'Invalid choice'
  6. Run groupby / pivot / filter / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Preview120 rows x 12 columnsPASS
2Category summaryRevenue per categoryPASS
3Pivot4 regions x 6 monthsPASS
4Growth% change per monthPASS
5Top products5 rowsPASS
6RankingRank 1 salespersonPASS
7Filter North, 20000Matching rowsPASS
8Charts4 PNG filesPASS
9ExportCSV savedPASS
โš  Limitations
  • Transactions generated with random seed for demo
  • Six months only
  • No returns
  • Single currency
๐Ÿš€ Future scope
  • Connect to a real POS database
  • Sales forecast
  • Interactive Plotly dashboard
  • Customer segmentation

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, numpy - fast arrays and maths are loaded.
  2. Global variables / constants are created: rng, PRODUCTS, rows, sales.
  3. 9 functions are defined (lines 30โ€“90) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
preview()30โ€“33Previewmain program (menu)
category()36โ€“40Categorymain program (menu)
pivot()43โ€“46Pivotmain program (menu)
growth()49โ€“53Growthmain program (menu)
top_products()56โ€“58Top productsmain program (menu)
ranking()61โ€“64Rankingmain program (menu)
filt()67โ€“72Filtmain program (menu)
charts()75โ€“85Chartsmain program (menu)
export()88โ€“90Exportmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ RETAIL SALES ANALYSIS (CSV + Pandas + Matplotlib)
9
rng = np.random.default_rng(42)
๐Ÿ“ฆ Library / Data Creates a random number generator with seed 42; the result is stored in variable rng
10
PRODUCTS = {"Electronics": [("Smartphone", 15999), ("Earbuds", 1999), ("Smart Watch", 3499)],
            "Clothing": [("Kurta", 899), ("Jeans", 1499), ("Jacโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Electronics": [("Smartphone", 15999), ("Earโ€ฆ in variable PRODUCTS
14
rows = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable rows
15
for i in range(120):
๐Ÿ” Loop LOOP: gives the numbers 0 to 119 (120 numbers); for each number, i takes that value and the indented block runs once
16
cat = rng.choice(list(PRODUCTS))
๐Ÿงฎ Store / Calculate Picks one random item from list(PRODUCTS); the result is stored in variable cat
17
prod, price = PRODUCTS[cat][rng.integers(0, 3)]
๐Ÿงฎ Store / Calculate Stores the item PRODUCTS[cat][rng.integers(0, 3)] in variables prod, price
18
rows.append([1001 + i, pd.Timestamp("2026-01-01") + pd.Timedelta(days=int(rng.integers(0, 181))),
             rng.choice(["North", "South", "East", "West"])โ€ฆ
๐Ÿ“ฆ Library / Data Adds [1001 + i, pd.Timestamp("2026-01-01") + pd.Tiโ€ฆ at the end of list rows
21
pd.DataFrame(rows, columns=["OrderID", "Date", "Region", "Category", "Product", "Qty", "Price", "Salesperson"]).to_csv("sales.csv", index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "sales.csv"
23
sales = pd.read_csv("sales.csv", parse_dates=["Date"])
๐Ÿ“ฆ Library / Data Reads the CSV file "sales.csv" into a DataFrame (table); the result is stored in variable sales
24
sales["Revenue"] = sales["Qty"] * sales["Price"]
๐Ÿงฎ Store / Calculate Puts the value of sales["Qty"] * sales["Price"] (calculated using ร—) into sales["Revenue"] (item "Revenue" of sales)
25
sales["Discount"] = np.where(sales["Revenue"] > 20000, 0.05, 0) * sales["Revenue"]
๐Ÿ“ฆ Library / Data Puts the value of np.where(sales["Revenue"] > 20000, 0.05, 0) *โ€ฆ (calculated using ร—) into sales["Discount"] (item "Discount" of sales)
26
sales["Net"] = sales["Revenue"] - sales["Discount"]
๐Ÿงฎ Store / Calculate Puts the value of sales["Revenue"] - sales["Discount"] (calculated using -) into sales["Net"] (item "Net" of sales)
27
sales["Month"] = sales["Date"].dt.strftime("%m-%b")
๐Ÿงฎ Store / Calculate Formats the date as text; the result is put into sales["Month"] (item "Month" of sales)
93
menu = {"1": preview, "2": category, "3": pivot, "4": growth, "5": top_products, "6": ranking, "7": filt, "8": charts, "9": export}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": preview, "2": category, "3": pivot, "4"โ€ฆ in variable menu
94
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
95
print("RETAIL SALES ANALYSIS (Jan - Jun 2026)".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "RETAIL SALES ANALYSIS (Jan - Jun 2026)".centโ€ฆ on the screen
96
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
97
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
98
print("\n1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Preview 2.Category 3.Pivot 4.Grโ€ฆ" on the screen
99
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
100
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
101
print("Report complete.")
๐Ÿ–ฅ๏ธ Output Displays the text "Report complete." on the screen
102
break
๐Ÿ” Loop BREAK - leaves the loop immediately
103
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
104
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
105
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
106
print("Invalid value.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid value." on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: RETAIL SALES ANALYSIS (Jan - Jun 2026) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: preview()
    shows: Shape: (120, 12) (+23 more lines)
  3. You type 2 at Enter choice:
    runs: category()
    shows: Orders Units Revenue Avg_Order Share_% (+7 more lines)
  4. You type 3 at Enter choice:
    runs: pivot()
    shows: Month 01-Jan 02-Feb 03-Mar 04-Apr 05-May 06-Jun Total (+6 more lines)
  5. You type 4 at Enter choice:
    runs: growth()
    shows: Revenue Growth_% (+9 more lines)
  6. You type 5 at Enter choice:
    runs: top_products()
    shows: Category Product (+6 more lines)
  7. You type 6 at Enter choice:
    runs: ranking()
    shows: Orders Revenue Rank (+7 more lines)
  8. You type 7 at Enter choice:
    runs: filt()
  9. You type North at Region:
  10. You type 20000 at Minimum net revenue:
    shows: OrderID Date Product Qty Net (+4 more lines)
  11. You type 8 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+5 more lines)
  12. You type 9 at Enter choice:
    runs: export()
    shows: Category,Qty,Revenue,Discount,Net (+5 more lines)
  13. You type 0 at Enter choice:
    shows: Report complete.
โ‘ค Inside each function - line by line
preview() - lines 30โ€“33
LineCodeWhat it does
30
def preview():
๐Ÿงฉ Function DEFINES a function preview(). Python only remembers it here - its body runs later, each time preview() is called.
31
print("Shape:", sales.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Shape:", then the value of sales.shape on the screen
32
print(sales.head(8).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of sales.head(8).to_string(index=False) on the screen
33
print("\nData types:\n", sales.dtypes.to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Data types:", then the value of sales.dtypes.to_string() on the screen
category() - lines 36โ€“40
LineCodeWhat it does
36
def category():
๐Ÿงฉ Function DEFINES a function category(). Python only remembers it here - its body runs later, each time category() is called.
37
c = sales.groupby("Category").agg(Orders=("OrderID", "count"), Units=("Qty", "sum"), Revenue=("Net", "sum"), Avg_Order=("Net", "mean"))
๐Ÿงฎ Store / Calculate Calculates the given summary values for every group; the result is stored in variable c
38
c["Share_%"] = (c["Revenue"] / c["Revenue"].sum() * 100).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of c["Revenue"] / c["Revenue"].sum() * 100 to 1 decimal places; the result is put into c["Share_%"] (item "Share_%" of c)
39
print(c.sort_values("Revenue", ascending=False).round(0))
๐Ÿ–ฅ๏ธ Output Displays the value of c.sort_values("Revenue", ascending=False).rouโ€ฆ on the screen
40
print(f"\nTotal net revenue: Rs. {sales['Net'].sum():,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nTotal net revenue: Rs. {sales['Net'].sum(โ€ฆ with the values filled into { } on the screen
pivot() - lines 43โ€“46
LineCodeWhat it does
43
def pivot():
๐Ÿงฉ Function DEFINES a function pivot(). Python only remembers it here - its body runs later, each time pivot() is called.
44
p = sales.pivot_table(index="Region", columns="Month", values="Net", aggfunc="sum", fill_value=0).round(0)
๐Ÿงฎ Store / Calculate Rounds the values of sales.pivot_table(index="Region", columns="Moโ€ฆ to 0 decimal places; the result is stored in variable p
45
p["Total"] = p.sum(axis=1)
๐Ÿงฎ Store / Calculate Adds up all values of p; the result is put into p["Total"] (item "Total" of p)
46
print(p.sort_values("Total", ascending=False))
๐Ÿ–ฅ๏ธ Output Displays the value of p.sort_values("Total", ascending=False) on the screen
growth() - lines 49โ€“53
LineCodeWhat it does
49
def growth():
๐Ÿงฉ Function DEFINES a function growth(). Python only remembers it here - its body runs later, each time growth() is called.
50
m = sales.groupby("Month")["Net"].sum()
๐Ÿงฎ Store / Calculate Adds up all values of sales.groupby("Month")["Net"]; the result is stored in variable m
51
g = pd.DataFrame({"Revenue": m.round(0), "Growth_%": (m.pct_change() * 100).round(1)})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Revenue": m.round(0), "Growth_%": (m.pct_chโ€ฆ; the result is stored in variable g
52
print(g.fillna("-"))
๐Ÿ–ฅ๏ธ Output Displays the value of g.fillna("-") on the screen
53
print("Best month:", m.idxmax(), "| Weakest:", m.idxmin())
๐Ÿ–ฅ๏ธ Output Displays the text "Best month:", then the value of m.idxmax(), then the text "| Weakest:", then the value of m.idxmin() on the screen
top_products() - lines 56โ€“58
LineCodeWhat it does
56
def top_products():
๐Ÿงฉ Function DEFINES a function top_products(). Python only remembers it here - its body runs later, each time top_products() is called.
57
t = sales.groupby(["Category", "Product"])["Net"].sum().nlargest(5).round(0)
๐Ÿงฎ Store / Calculate Rounds the values of sales.groupby(["Category", "Product"])["Net"]โ€ฆ to 0 decimal places; the result is stored in variable t
58
print(t.to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of t.to_string() on the screen
ranking() - lines 61โ€“64
LineCodeWhat it does
61
def ranking():
๐Ÿงฉ Function DEFINES a function ranking(). Python only remembers it here - its body runs later, each time ranking() is called.
62
r = sales.groupby("Salesperson").agg(Orders=("OrderID", "count"), Revenue=("Net", "sum"))
๐Ÿงฎ Store / Calculate Calculates the given summary values for every group; the result is stored in variable r
63
r["Rank"] = r["Revenue"].rank(ascending=False).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of r["Revenue"].rank(ascending=False) to int; the result is put into r["Rank"] (item "Rank" of r)
64
print(r.sort_values("Rank").round(0))
๐Ÿ–ฅ๏ธ Output Displays the value of r.sort_values("Rank").round(0) on the screen
filt() - lines 67โ€“72
LineCodeWhat it does
67
def filt():
๐Ÿงฉ Function DEFINES a function filt(). Python only remembers it here - its body runs later, each time filt() is called.
68
reg = input("Region: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable reg
69
v = float(input("Minimum net revenue: "))
โŒจ๏ธ Input Shows "Minimum net revenue: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable v
70
r = sales[(sales["Region"] == reg) & (sales["Net"] >= v)]
๐Ÿงฎ Store / Calculate Stores the item sales[(sales["Region"] == reg) & (sales["Net"โ€ฆ in variable r
71
print(r[["OrderID", "Date", "Product", "Qty", "Net"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of r[["OrderID", "Date", "Product", "Qty", "Net"โ€ฆ on the screen
72
print(len(r), "orders | total Rs.", round(r["Net"].sum()))
๐Ÿ–ฅ๏ธ Output Displays the value of len(r), then the text "orders | total Rs.", then the value of round(r["Net"].sum()) on the screen
charts() - lines 75โ€“85
LineCodeWhat it does
75
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
76
m = sales.groupby("Month")["Net"].sum() / 1000
๐Ÿงฎ Store / Calculate Stores the value of sales.groupby("Month")["Net"].sum() / 1000 (calculated using รท) in variable m
77
plt.plot(m.index, m.values, "g-o", linewidth=2); plt.title("Monthly Net Revenue (Rs. thousand)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of m.index, m.values, "g-o"
77
plt.plot(m.index, m.values, "g-o", linewidth=2); plt.title("Monthly Net Revenue (Rs. thousand)")
๐Ÿ–ฅ๏ธ Output Writes "Monthly Net Revenue (Rs. thousand)" as the title of the chart
78
plt.grid(alpha=.3); plt.tight_layout(); plt.savefig("monthly_revenue.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
78
plt.grid(alpha=.3); plt.tight_layout(); plt.savefig("monthly_revenue.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
78
plt.grid(alpha=.3); plt.tight_layout(); plt.savefig("monthly_revenue.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "monthly_revenue.png"
78
plt.grid(alpha=.3); plt.tight_layout(); plt.savefig("monthly_revenue.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
79
sales.groupby("Category")["Net"].sum().plot(kind="pie", autopct="%1.1f%%", explode=[0.05] * 4, title="Category Share")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
80
plt.ylabel(""); plt.tight_layout(); plt.savefig("category_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
80
plt.ylabel(""); plt.tight_layout(); plt.savefig("category_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
80
plt.ylabel(""); plt.tight_layout(); plt.savefig("category_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "category_share.png"
80
plt.ylabel(""); plt.tight_layout(); plt.savefig("category_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
(sales.pivot_table(index="Month", columns="Region", values="Net", aggfunc="sum") / 1000).plot(kind="bar", title="Region-wise Monthly Revenue (Rs. thousand)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("region_month.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("region_month.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("region_month.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "region_month.png"
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("region_month.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
83
sales.groupby("Product")["Net"].sum().nlargest(5).sort_values().plot(kind="barh", color="#6a1b9a", title="Top 5 Products")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
84
plt.tight_layout(); plt.savefig("top_products.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
84
plt.tight_layout(); plt.savefig("top_products.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "top_products.png"
84
plt.tight_layout(); plt.savefig("top_products.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
85
print("Charts saved: monthly_revenue.png, category_share.png, region_month.png, top_products.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: monthly_revenue.pngโ€ฆ" on the screen
export() - lines 88โ€“90
LineCodeWhat it does
88
def export():
๐Ÿงฉ Function DEFINES a function export(). Python only remembers it here - its body runs later, each time export() is called.
89
sales.groupby("Category")[["Qty", "Revenue", "Discount", "Net"]].sum().to_csv("sales_summary.csv")
๐Ÿงฎ Store / Calculate Saves the DataFrame into CSV file "sales_summary.csv"
90
print(open("sales_summary.csv").read())
๐Ÿ“ File Displays the value of open("sales_summary.csv").read() on the screen
Q1. Difference between groupby and pivot_table?

groupby gives a grouped Series / DataFrame; pivot_table arranges the result as a 2-D table with rows and columns from two fields.

Q2. What does agg() allow?

Several aggregate functions at once, e.g. agg(['sum', 'mean', 'count']).

Q3. What is parse_dates in read_csv()?

It converts the given column to datetime while reading the CSV.

Q4. How is the month extracted?

sales['Date'].dt.month_name() or dt.strftime('%b').

Q5. How do you sort a DataFrame?

sort_values(by='Revenue', ascending=False).

08

Employee Payroll Analytics (MySQL + Pandas)

PYTHON + MySQLPython-MySQL connectionSQL aggregate queriesDataFrame from fetchall()calculated columnsgroupby
๐Ÿ“ 124 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 119 output lines๐Ÿ“„ 25+ page report

Stores employees in MySQL, loads them into Pandas, calculates DA/HRA/net salary and compares department-wise payroll with a chart.

โœจ Features
  • Employee table (12 rows) in MySQL with dept, designation, basic, join date and city
  • SQL aggregate queries: COUNT, SUM, AVG, MAX per department with GROUP BY / HAVING / ORDER BY
  • Result of fetchall() converted to a DataFrame; DA, HRA, PF and Net calculated in Pandas
  • Experience from join date; increment simulation (what-if 8 %)
  • Hire employee and give raise from the menu (INSERT / UPDATE)
  • Bar, histogram and scatter charts
โ˜ฐ Main menu
1Employee ListSELECT * as DataFrame
2SQL Dept SummaryGROUP BY dept
3Payroll SheetDA / HRA / PF / Net in Pandas
4Experience AnalysisYears of service and bands
5Hire EmployeeINSERT
6Give RaiseUPDATE basic by %
7What-if IncrementCost of 8 % raise
8Charts3 charts
0ExitCloses connection
๐ŸŽฏ Objectives
  • Combine MySQL storage with Pandas analysis
  • Create calculated columns in a DataFrame
  • Summarise with groupby() and agg()
๐Ÿ“š Data dictionary
NameTypePurpose
empMySQL tableeid PK, name, dept, desig, basic, doj DATE, city
dfDataFrameFrom fetchall() + cursor.description
DA / HRA / PFfloat0.46 / 0.24 / 0.12 of basic
Exp_YrscolumnYears since joining
Why it matters: Shows how SQL and Pandas complement each other in an IT-application project.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import mysql.connector
# =====================================================================
#   EMPLOYEE PAYROLL ANALYTICS  (MySQL + Pandas + Matplotlib)
# =====================================================================
TODAY = pd.Timestamp("2026-07-31")
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
cur = conn.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS company_ip")
cur.execute("USE company_ip")
cur.execute("""CREATE TABLE IF NOT EXISTS emp (eid CHAR(4) PRIMARY KEY, name VARCHAR(20), dept VARCHAR(10),
               desig VARCHAR(15), basic INT, doj DATE, city VARCHAR(12))""")
cur.execute("SELECT COUNT(*) FROM emp")
if cur.fetchone()[0] == 0:
    cur.executemany("INSERT INTO emp VALUES (%s,%s,%s,%s,%s,%s,%s)", [
        ("E101", "Arvind Rao", "IT", "Manager", 92000, "2012-06-11", "Bengaluru"), ("E102", "Bina Shah", "IT", "Developer", 61000, "2018-08-01", "Pune"),
        ("E103", "Chandan Roy", "IT", "Developer", 58000, "2020-01-15", "Pune"), ("E104", "Dolly Paul", "HR", "Manager", 74000, "2014-03-20", "Delhi"),
        ("E105", "Ekta Jain", "HR", "Executive", 38000, "2022-07-04", "Delhi"), ("E106", "Faisal Khan", "Sales", "Manager", 81000, "2013-11-30", "Mumbai"),
        ("E107", "Geeta Nair", "Sales", "Executive", 42000, "2021-05-17", "Kochi"), ("E108", "Harsh Vora", "Sales", "Executive", 40000, "2023-02-01", "Ahmedabad"),
        ("E109", "Indu Bala", "Finance", "Accountant", 55000, "2016-09-12", "Chandigarh"), ("E110", "Jai Thakur", "Finance", "Analyst", 63000, "2019-10-21", "Mumbai"),
        ("E111", "Kriti Das", "IT", "Tester", 47000, "2021-12-06", "Kolkata"), ("E112", "Lalit Mohan", "Sales", "Executive", 39000, "2024-06-10", "Jaipur")])
    conn.commit()


def frame(sql, p=()):
    cur.execute(sql, p)
    return pd.DataFrame(cur.fetchall(), columns=[d[0] for d in cur.description])


def payroll():
    df = frame("SELECT * FROM emp")
    df["DA"] = df["basic"] * 0.46
    df["HRA"] = df["basic"] * 0.24
    df["PF"] = df["basic"] * 0.12
    df["Gross"] = df["basic"] + df["DA"] + df["HRA"]
    df["Net"] = df["Gross"] - df["PF"]
    return df


def emp_list():
    print(frame("SELECT * FROM emp ORDER BY eid").to_string(index=False))


def dept_summary():
    print(frame("""SELECT dept, COUNT(*) AS staff, SUM(basic) AS total_basic, ROUND(AVG(basic)) AS avg_basic,
                   MAX(basic) AS max_basic FROM emp GROUP BY dept ORDER BY total_basic DESC""").to_string(index=False))
    print("\nDepartments with more than 2 employees (HAVING):")
    print(frame("SELECT dept, COUNT(*) AS staff FROM emp GROUP BY dept HAVING COUNT(*) > 2").to_string(index=False))


def sheet():
    df = payroll()
    print(df[["eid", "name", "dept", "basic", "DA", "HRA", "PF", "Gross", "Net"]].round(0).to_string(index=False))
    print(f"\nMonthly payroll (Net): Rs. {df['Net'].sum():,.0f} | Annual: Rs. {df['Net'].sum() * 12:,.0f}")


def experience():
    df = frame("SELECT eid, name, dept, doj, basic FROM emp")
    df["doj"] = pd.to_datetime(df["doj"])
    df["Exp_Yrs"] = ((TODAY - df["doj"]).dt.days / 365.25).round(1)
    df["Band"] = pd.cut(df["Exp_Yrs"], [0, 3, 7, 50], labels=["0-3 yrs", "3-7 yrs", "7+ yrs"])
    print(df.sort_values("Exp_Yrs", ascending=False).to_string(index=False))
    print("\nEmployees per band:\n", df["Band"].value_counts().sort_index().to_string())
    print("\nAverage basic per band:\n", df.groupby("Band", observed=True)["basic"].mean().round(0).to_string())


def hire():
    r = (input("Emp ID: ").strip().upper(), input("Name: ").strip().title(), input("Dept: ").strip(), input("Designation: ").strip(),
         int(input("Basic: ")), input("Date of joining (yyyy-mm-dd): ").strip(), input("City: ").strip())
    cur.execute("INSERT INTO emp VALUES (%s,%s,%s,%s,%s,%s,%s)", r)
    conn.commit()
    print("Hired", r[1], "-", cur.rowcount, "row inserted")


def raise_pay():
    eid, pct = input("Emp ID: ").strip().upper(), float(input("Raise %: "))
    cur.execute("UPDATE emp SET basic = ROUND(basic * (1 + %s / 100)) WHERE eid = %s", (pct, eid))
    conn.commit()
    print(cur.rowcount, "row(s) updated")


def what_if():
    df = payroll()
    new = df["Net"] * 1.08
    d = pd.DataFrame({"Current": df.groupby("dept")["Net"].sum(), "After_8%": new.groupby(df["dept"]).sum()})
    d["Extra"] = d["After_8%"] - d["Current"]
    print(d.round(0))
    print(f"Extra monthly cost of 8% raise: Rs. {d['Extra'].sum():,.0f}")


def charts():
    df = payroll()
    df.groupby("dept")[["basic", "DA", "HRA"]].sum().plot(kind="bar", stacked=True, title="Department Payroll Components")
    plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
    plt.hist(df["Net"], bins=6, color="#26a69a", edgecolor="k"); plt.title("Net Salary Distribution"); plt.xlabel("Net pay")
    plt.tight_layout(); plt.savefig("salary_hist.png"); plt.show()
    exp = (TODAY - pd.to_datetime(df["doj"])).dt.days / 365.25
    plt.scatter(exp, df["basic"], c="crimson")
    for x, y, n in zip(exp, df["basic"], df["name"]):
        plt.annotate(n.split()[0], (x, y), fontsize=7)
    plt.title("Experience vs Basic Pay"); plt.xlabel("Years"); plt.ylabel("Basic")
    plt.tight_layout(); plt.savefig("exp_vs_salary.png"); plt.show()
    print("Charts saved: dept_payroll.png, salary_hist.png, exp_vs_salary.png")


menu = {"1": emp_list, "2": dept_summary, "3": sheet, "4": experience, "5": hire, "6": raise_pay, "7": what_if, "8": charts}
print("=" * 60)
print("EMPLOYEE PAYROLL ANALYTICS (MySQL + Pandas)".center(60))
print("=" * 60)
while True:
    print("\n1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        conn.close()
        print("Connection closed.")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except (ValueError, mysql.connector.Error) as e:
        print("Error:", e)

        
  1. Start
  2. Connect, create table and insert 12 rows
  3. Display menu and read choice
  4. DML option? → No: SELECT into DataFrame
  5. execute + commit
  6. Calculate payroll columns / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Employee list12 rowsPASS
2Dept summarySQL GROUP BY resultPASS
3Payroll sheetNet pay columnPASS
4ExperienceBand countsPASS
5Hire E113Row insertedPASS
6Raise 10 % to E1051 row updatedPASS
7Raise to E9990 rowsPASS
8What-ifExtra monthly costPASS
9Charts3 PNG filesPASS
โš  Limitations
  • Allowance rates fixed
  • No tax / attendance
  • Password in code
  • Sample company data
๐Ÿš€ Future scope
  • pd.read_sql with SQLAlchemy
  • Payslip generation
  • Attrition analysis
  • Department budget alerts

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, mysql.connector - connecting Python with MySQL are loaded.
  2. Global variables / constants are created: TODAY, conn, cur.
  3. 10 functions are defined (lines 28โ€“106) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
frame(sql, p)28โ€“30Framepayroll(), emp_list(), dept_summary(), experience()
payroll()33โ€“40Payrollsheet(), what_if(), charts()
emp_list()43โ€“44Emp listmain program (menu)
dept_summary()47โ€“51Dept summarymain program (menu)
sheet()54โ€“57Sheetmain program (menu)
experience()60โ€“67Experiencemain program (menu)
hire()70โ€“75Hiremain program (menu)
raise_pay()78โ€“82Raise paymain program (menu)
what_if()85โ€“91What ifmain program (menu)
charts()94โ€“106Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import mysql.connector
๐Ÿ“ฆ Library / Data Loads the module mysql.connector - connecting Python with MySQL
๐Ÿ“Œ EMPLOYEE PAYROLL ANALYTICS (MySQL + Pandas + Matplotlib)
9
TODAY = pd.Timestamp("2026-07-31")
๐Ÿ“ฆ Library / Data Calls pd.Timestamp("2026-07-31"); the result is stored in variable TODAY
10
conn = mysql.connector.connect(host="localhost", user="root", password="computer")
๐Ÿฌ Database Connects Python to the MySQL server using host, user, password; the result is stored in variable conn
11
cur = conn.cursor()
๐Ÿฌ Database Creates a cursor - the object that carries SQL queries to MySQL; the result is stored in variable cur
12
cur.execute("CREATE DATABASE IF NOT EXISTS company_ip")
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
13
cur.execute("USE company_ip")
๐Ÿฌ Database Sends USE (selects the database) to MySQL through the cursor
14
cur.execute("""CREATE TABLE IF NOT EXISTS emp (eid CHAR(4) PRIMARY KEY, name VARCHAR(20), dept VARCHAR(10),
               desig VARCHAR(15), basic INT, doj โ€ฆ
๐Ÿฌ Database Sends a CREATE command to MySQL through the cursor
16
cur.execute("SELECT COUNT(*) FROM emp")
๐Ÿฌ Database Sends a SELECT query (fetches rows) to MySQL through the cursor
17
if cur.fetchone()[0] == 0:
๐Ÿ”€ Decision CHECKS whether cur.fetchone()[0] is equal to 0. If True, the indented lines below run; otherwise they are skipped
18
cur.executemany("INSERT INTO emp VALUES (%s,%s,%s,%s,%s,%s,%s)", [
    ("E101", "Arvind Rao", "IT", "Manager", 92000, "2012-06-11", "Bengaluru"), ("E102", "Bโ€ฆ
๐Ÿฌ Database Runs the same SQL for every row of [ ("E101", "Arvind Rao", "IT", "Manager", 920โ€ฆ
25
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
109
menu = {"1": emp_list, "2": dept_summary, "3": sheet, "4": experience, "5": hire, "6": raise_pay, "7": what_if, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": emp_list, "2": dept_summary, "3": sheetโ€ฆ in variable menu
110
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
111
print("EMPLOYEE PAYROLL ANALYTICS (MySQL + Pandas)".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "EMPLOYEE PAYROLL ANALYTICS (MySQL + Pandas)"โ€ฆ on the screen
112
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
113
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
114
print("\n1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.List 2.Dept Summary 3.Payroll 4โ€ฆ" on the screen
115
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
116
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
117
conn.close()
๐Ÿงฎ Store / Calculate Closes conn
118
print("Connection closed.")
๐Ÿ–ฅ๏ธ Output Displays the text "Connection closed." on the screen
119
break
๐Ÿ” Loop BREAK - leaves the loop immediately
120
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
121
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
122
except (ValueError, mysql.connector.Error) as e:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if (ValueError, mysql.connector.Error) occurs - that error
123
print("Error:", e)
๐Ÿ–ฅ๏ธ Output Displays the text "Error:", then the value of e on the screen
โ‘ฃ Inside each function - line by line
frame() - lines 28โ€“30
LineCodeWhat it does
28
def frame(sql, p=()):
๐Ÿงฉ Function DEFINES a function frame(sql, p). Python only remembers it here - its body runs later, each time frame() is called.
29
cur.execute(sql, p)
๐Ÿฌ Database Sends the SQL statement to MySQL through the cursor; the %s places are filled safely with the values p
30
return pd.DataFrame(cur.fetchall(), columns=[d[0] for d in cur.description])
๐Ÿงฉ Function Sends back (returns) the result of: creates a pandas DataFrame (table) from cur.fetchall() to the line that called the function
payroll() - lines 33โ€“40
LineCodeWhat it does
33
def payroll():
๐Ÿงฉ Function DEFINES a function payroll(). Python only remembers it here - its body runs later, each time payroll() is called.
34
df = frame("SELECT * FROM emp")
๐Ÿงฎ Store / Calculate Calls our own function frame("SELECT * FROM emp"); the result is stored in variable df
35
df["DA"] = df["basic"] * 0.46
๐Ÿงฎ Store / Calculate Puts the value of df["basic"] * 0.46 (calculated using ร—) into df["DA"] (item "DA" of df)
36
df["HRA"] = df["basic"] * 0.24
๐Ÿงฎ Store / Calculate Puts the value of df["basic"] * 0.24 (calculated using ร—) into df["HRA"] (item "HRA" of df)
37
df["PF"] = df["basic"] * 0.12
๐Ÿงฎ Store / Calculate Puts the value of df["basic"] * 0.12 (calculated using ร—) into df["PF"] (item "PF" of df)
38
df["Gross"] = df["basic"] + df["DA"] + df["HRA"]
๐Ÿงฎ Store / Calculate Puts the value of df["basic"] + df["DA"] + df["HRA"] (calculated using +) into df["Gross"] (item "Gross" of df)
39
df["Net"] = df["Gross"] - df["PF"]
๐Ÿงฎ Store / Calculate Puts the value of df["Gross"] - df["PF"] (calculated using -) into df["Net"] (item "Net" of df)
40
return df
๐Ÿงฉ Function Sends back (returns) the value of df to the line that called the function
emp_list() - lines 43โ€“44
LineCodeWhat it does
43
def emp_list():
๐Ÿงฉ Function DEFINES a function emp_list(). Python only remembers it here - its body runs later, each time emp_list() is called.
44
print(frame("SELECT * FROM emp ORDER BY eid").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of frame("SELECT * FROM emp ORDER BY eid").to_stโ€ฆ on the screen
dept_summary() - lines 47โ€“51
LineCodeWhat it does
47
def dept_summary():
๐Ÿงฉ Function DEFINES a function dept_summary(). Python only remembers it here - its body runs later, each time dept_summary() is called.
48
print(frame("""SELECT dept, COUNT(*) AS staff, SUM(basic) AS total_basic, ROUND(AVG(basic)) AS avg_basic,
               MAX(basic) AS max_basic FROM emp GROโ€ฆ
๐Ÿ–ฅ๏ธ Output Displays the value of frame("""SELECT dept, COUNT(*) AS staff, SUM(โ€ฆ on the screen
50
print("\nDepartments with more than 2 employees (HAVING):")
๐Ÿ–ฅ๏ธ Output Displays the text "Departments with more than 2 emplโ€ฆ" on the screen
51
print(frame("SELECT dept, COUNT(*) AS staff FROM emp GROUP BY dept HAVING COUNT(*) > 2").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of frame("SELECT dept, COUNT(*) AS staff FROM emโ€ฆ on the screen
sheet() - lines 54โ€“57
LineCodeWhat it does
54
def sheet():
๐Ÿงฉ Function DEFINES a function sheet(). Python only remembers it here - its body runs later, each time sheet() is called.
55
df = payroll()
๐Ÿงฎ Store / Calculate Calls our own function payroll(); the result is stored in variable df
56
print(df[["eid", "name", "dept", "basic", "DA", "HRA", "PF", "Gross", "Net"]].round(0).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df[["eid", "name", "dept", "basic", "DA", "HRโ€ฆ on the screen
57
print(f"\nMonthly payroll (Net): Rs. {df['Net'].sum():,.0f} | Annual: Rs. {df['Net'].sum() * 12:,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nMonthly payroll (Net): Rs. {df['Net'].sumโ€ฆ with the values filled into { } on the screen
experience() - lines 60โ€“67
LineCodeWhat it does
60
def experience():
๐Ÿงฉ Function DEFINES a function experience(). Python only remembers it here - its body runs later, each time experience() is called.
61
df = frame("SELECT eid, name, dept, doj, basic FROM emp")
๐Ÿงฎ Store / Calculate Calls our own function frame("SELECT eid, name, โ€ฆ); the result is stored in variable df
62
df["doj"] = pd.to_datetime(df["doj"])
๐Ÿ“ฆ Library / Data Converts the text into dates; the result is put into df["doj"] (item "doj" of df)
63
df["Exp_Yrs"] = ((TODAY - df["doj"]).dt.days / 365.25).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of (TODAY - df["doj"]).dt.days / 365.25 to 1 decimal places; the result is put into df["Exp_Yrs"] (item "Exp_Yrs" of df)
64
df["Band"] = pd.cut(df["Exp_Yrs"], [0, 3, 7, 50], labels=["0-3 yrs", "3-7 yrs", "7+ yrs"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["Band"] (item "Band" of df)
65
print(df.sort_values("Exp_Yrs", ascending=False).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.sort_values("Exp_Yrs", ascending=False).toโ€ฆ on the screen
66
print("\nEmployees per band:\n", df["Band"].value_counts().sort_index().to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Employees per band:", then the value of df["Band"].value_counts().sort_index().to_strโ€ฆ on the screen
67
print("\nAverage basic per band:\n", df.groupby("Band", observed=True)["basic"].mean().round(0).to_string())
๐Ÿ–ฅ๏ธ Output Displays the text "Average basic per band:", then the value of df.groupby("Band", observed=True)["basic"].meโ€ฆ on the screen
hire() - lines 70โ€“75
LineCodeWhat it does
70
def hire():
๐Ÿงฉ Function DEFINES a function hire(). Python only remembers it here - its body runs later, each time hire() is called.
71
r = (input("Emp ID: ").strip().upper(), input("Name: ").strip().title(), input("Dept: ").strip(), input("Designation: ").strip(),
     int(input("Basic: ")),โ€ฆ
โŒจ๏ธ Input Stores the tuple (input("Emp ID: ").strip().upper(), input("Naโ€ฆ in variable r
73
cur.execute("INSERT INTO emp VALUES (%s,%s,%s,%s,%s,%s,%s)", r)
๐Ÿฌ Database Sends an INSERT query (adds a row) to MySQL through the cursor; the %s places are filled safely with the values r
74
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
75
print("Hired", r[1], "-", cur.rowcount, "row inserted")
๐Ÿ–ฅ๏ธ Output Displays the text "Hired", then the value of r[1], then the text "-", then the value of cur.rowcount, then the text "row inserted" on the screen
raise_pay() - lines 78โ€“82
LineCodeWhat it does
78
def raise_pay():
๐Ÿงฉ Function DEFINES a function raise_pay(). Python only remembers it here - its body runs later, each time raise_pay() is called.
79
eid, pct = input("Emp ID: ").strip().upper(), float(input("Raise %: "))
โŒจ๏ธ Input Stores input("Emp ID: ").strip().upper(), float(input("Raise %: ")) into eid, pct respectively
80
cur.execute("UPDATE emp SET basic = ROUND(basic * (1 + %s / 100)) WHERE eid = %s", (pct, eid))
๐Ÿฌ Database Sends an UPDATE query (changes rows) to MySQL through the cursor; the %s places are filled safely with the values (pct, eid)
81
conn.commit()
๐Ÿฌ Database Saves (commits) the changes permanently in the database
82
print(cur.rowcount, "row(s) updated")
๐Ÿ–ฅ๏ธ Output Displays the value of cur.rowcount, then the text "row(s) updated" on the screen
what_if() - lines 85โ€“91
LineCodeWhat it does
85
def what_if():
๐Ÿงฉ Function DEFINES a function what_if(). Python only remembers it here - its body runs later, each time what_if() is called.
86
df = payroll()
๐Ÿงฎ Store / Calculate Calls our own function payroll(); the result is stored in variable df
87
new = df["Net"] * 1.08
๐Ÿงฎ Store / Calculate Stores the value of df["Net"] * 1.08 (calculated using ร—) in variable new
88
d = pd.DataFrame({"Current": df.groupby("dept")["Net"].sum(), "After_8%": new.groupby(df["dept"]).sum()})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Current": df.groupby("dept")["Net"].sum(), โ€ฆ; the result is stored in variable d
89
d["Extra"] = d["After_8%"] - d["Current"]
๐Ÿงฎ Store / Calculate Puts the value of d["After_8%"] - d["Current"] (calculated using -) into d["Extra"] (item "Extra" of d)
90
print(d.round(0))
๐Ÿ–ฅ๏ธ Output Displays the value of d.round(0) on the screen
91
print(f"Extra monthly cost of 8% raise: Rs. {d['Extra'].sum():,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Extra monthly cost of 8% raise: Rs. {d['Extโ€ฆ with the values filled into { } on the screen
charts() - lines 94โ€“106
LineCodeWhat it does
94
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
95
df = payroll()
๐Ÿงฎ Store / Calculate Calls our own function payroll(); the result is stored in variable df
96
df.groupby("dept")[["basic", "DA", "HRA"]].sum().plot(kind="bar", stacked=True, title="Department Payroll Components")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
97
plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Rs." as the label of the Y-axis
97
plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
97
plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
97
plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "dept_payroll.png"
97
plt.ylabel("Rs."); plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("dept_payroll.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
98
plt.hist(df["Net"], bins=6, color="#26a69a", edgecolor="k"); plt.title("Net Salary Distribution"); plt.xlabel("Net pay")
๐Ÿ–ฅ๏ธ Output Draws a histogram of df["Net"]
98
plt.hist(df["Net"], bins=6, color="#26a69a", edgecolor="k"); plt.title("Net Salary Distribution"); plt.xlabel("Net pay")
๐Ÿ–ฅ๏ธ Output Writes "Net Salary Distribution" as the title of the chart
98
plt.hist(df["Net"], bins=6, color="#26a69a", edgecolor="k"); plt.title("Net Salary Distribution"); plt.xlabel("Net pay")
๐Ÿ–ฅ๏ธ Output Writes "Net pay" as the label of the X-axis
99
plt.tight_layout(); plt.savefig("salary_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
99
plt.tight_layout(); plt.savefig("salary_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "salary_hist.png"
99
plt.tight_layout(); plt.savefig("salary_hist.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
100
exp = (TODAY - pd.to_datetime(df["doj"])).dt.days / 365.25
๐Ÿ“ฆ Library / Data Stores the value of (TODAY - pd.to_datetime(df["doj"])).dt.days /โ€ฆ (calculated using รท) in variable exp
101
plt.scatter(exp, df["basic"], c="crimson")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of exp, df["basic"]
102
for x, y, n in zip(exp, df["basic"], df["name"]):
๐Ÿ” Loop LOOP that walks through exp, df["basic"], df["name"] together; x, y, n get one item from each
103
plt.annotate(n.split()[0], (x, y), fontsize=7)
๐Ÿ–ฅ๏ธ Output Writes a note with an arrow on the chart
104
plt.title("Experience vs Basic Pay"); plt.xlabel("Years"); plt.ylabel("Basic")
๐Ÿ–ฅ๏ธ Output Writes "Experience vs Basic Pay" as the title of the chart
104
plt.title("Experience vs Basic Pay"); plt.xlabel("Years"); plt.ylabel("Basic")
๐Ÿ–ฅ๏ธ Output Writes "Years" as the label of the X-axis
104
plt.title("Experience vs Basic Pay"); plt.xlabel("Years"); plt.ylabel("Basic")
๐Ÿ–ฅ๏ธ Output Writes "Basic" as the label of the Y-axis
105
plt.tight_layout(); plt.savefig("exp_vs_salary.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
105
plt.tight_layout(); plt.savefig("exp_vs_salary.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "exp_vs_salary.png"
105
plt.tight_layout(); plt.savefig("exp_vs_salary.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
106
print("Charts saved: dept_payroll.png, salary_hist.png, exp_vs_salary.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: dept_payroll.png, sโ€ฆ" on the screen
Q1. How do you get column names of a query result?

[d[0] for d in cur.description].

Q2. Why calculate allowances in Pandas and not SQL?

Both are possible; Pandas makes it easy to add many calculated columns and plot them.

Q3. What is TIMESTAMPDIFF / date difference?

In Pandas: (today - df['doj']).dt.days / 365 gives years of service.

Q4. What does HAVING COUNT(*) > 2 do?

Shows only departments with more than two employees.

Q5. What is pd.cut()?

It divides numeric values into bins (bands) like 0-3, 3-7, 7+ years.

09

Cricket Player Statistics Analyzer

PYTHON + PANDASDataFrame with calculated columnssort_valuesboolean filteringnlargestcorrelation
๐Ÿ“ 103 lines of codeโ˜ฐ 10 menu options๐Ÿ–ฅ๏ธ 94 output lines๐Ÿ“„ 25+ page report

Ranks ten batters by runs, average and strike-rate, filters players averaging above 40 and plots runs against strike-rate.

โœจ Features
  • Statistics of 15 Indian players (matches, innings, not outs, runs, balls, 4s, 6s, wickets)
  • Calculated columns: Average, Strike rate, Boundary %, Runs per match
  • Role-wise (Batter / All-rounder / Bowler) groupby analysis
  • Search player, compare two players side by side
  • Rankings with nlargest, filters for 'impact players', correlation
  • Bar, scatter, pie and stacked bar charts
โ˜ฐ Main menu
1Player TableDataFrame with calculated columns
2Top Run Scorersnlargest(5, 'Runs')
3Best Strike Ratemin 500 balls
4Role Analysisgroupby Role
5Search Playerstr.contains
6Compare TwoSide-by-side using loc
7Impact PlayersAvg >= 35 and SR >= 135
8Correlationcorr()
9Charts4 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Create calculated columns in a DataFrame
  • Use nlargest(), filtering and corr()
  • Plot bar and scatter charts with annotations
๐Ÿ“š Data dictionary
NameTypePurpose
crDataFramePlayer, Role, M, Inn, NO, Runs, Balls, Fours, Sixes, Wkts
AveragecolumnRuns / (Inn - NO)
SRcolumnRuns / Balls x 100
Boundary_%column(4s x 4 + 6s x 6) / Runs x 100
Why it matters: Uses a topic students love to practise filtering, sorting and Matplotlib customisation.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
# =====================================================================
#   CRICKET PLAYER STATISTICS ANALYZER  (Pandas + Matplotlib)
#   Figures are illustrative T20-style career numbers for practice.
# =====================================================================
cr = pd.DataFrame({
    "Player": ["Virat Kohli", "Rohit Sharma", "Suryakumar Yadav", "Shubman Gill", "Yashasvi Jaiswal", "Rishabh Pant", "KL Rahul",
               "Hardik Pandya", "Ravindra Jadeja", "Axar Patel", "Shivam Dube", "Tilak Varma", "Jasprit Bumrah", "Kuldeep Yadav", "Ishan Kishan"],
    "Role": ["Batter", "Batter", "Batter", "Batter", "Batter", "Batter", "Batter", "All-rounder", "All-rounder", "All-rounder",
             "All-rounder", "Batter", "Bowler", "Bowler", "Batter"],
    "M": [125, 159, 83, 35, 23, 76, 72, 114, 74, 70, 35, 25, 70, 40, 32],
    "Inn": [117, 151, 79, 35, 22, 66, 68, 90, 50, 45, 30, 24, 8, 10, 32],
    "NO": [31, 18, 12, 4, 3, 13, 8, 24, 21, 15, 10, 6, 6, 5, 2],
    "Runs": [4188, 4231, 2598, 1068, 723, 1209, 2265, 1803, 515, 535, 531, 749, 8, 35, 796],
    "Balls": [3065, 2973, 1553, 760, 440, 948, 1625, 1288, 409, 380, 380, 498, 15, 38, 640],
    "Fours": [369, 383, 236, 115, 81, 112, 199, 120, 37, 33, 31, 62, 0, 2, 86],
    "Sixes": [124, 205, 146, 33, 37, 44, 99, 98, 16, 24, 32, 41, 0, 1, 36],
    "Wkts": [4, 1, 0, 0, 0, 0, 0, 94, 54, 71, 11, 2, 89, 69, 0]})
cr["Average"] = (cr["Runs"] / (cr["Inn"] - cr["NO"])).round(2)
cr["SR"] = (cr["Runs"] / cr["Balls"] * 100).round(2)
cr["Boundary_%"] = ((cr["Fours"] * 4 + cr["Sixes"] * 6) / cr["Runs"] * 100).round(1)
cr["Runs_per_M"] = (cr["Runs"] / cr["M"]).round(1)
cr.index = range(1, len(cr) + 1)


def table():
    print(cr[["Player", "Role", "M", "Runs", "Average", "SR", "Boundary_%", "Wkts"]])


def top_runs():
    print(cr.nlargest(5, "Runs")[["Player", "Runs", "Average", "SR"]].to_string(index=False))


def best_sr():
    print(cr[cr["Balls"] >= 500].sort_values("SR", ascending=False)[["Player", "Balls", "Runs", "SR"]].head(5).to_string(index=False))


def roles():
    r = cr.groupby("Role").agg(Players=("Player", "count"), Runs=("Runs", "sum"), Avg_SR=("SR", "mean"), Wkts=("Wkts", "sum"))
    print(r.round(1))


def search():
    k = input("Player name contains: ").strip()
    r = cr[cr["Player"].str.contains(k, case=False)]
    print(r[["Player", "Role", "Runs", "Average", "SR", "Wkts"]].to_string(index=False) if len(r) else "No player found.")


def compare():
    a, b = input("First player : ").strip(), input("Second player: ").strip()
    t = cr.set_index("Player").loc[[a, b], ["M", "Runs", "Average", "SR", "Fours", "Sixes", "Boundary_%"]].T
    t["Better"] = [a if t.loc[i, a] > t.loc[i, b] else b for i in t.index]
    print(t)


def impact():
    r = cr[(cr["Average"] >= 35) & (cr["SR"] >= 135)]
    print(r[["Player", "Average", "SR"]].to_string(index=False))
    print(len(r), "impact batters (Average >= 35 and SR >= 135)")


def correlation():
    print(cr[["Runs", "Average", "SR", "Sixes", "Boundary_%"]].corr().round(2))


def charts():
    t = cr.nlargest(5, "Runs")
    plt.bar(t["Player"], t["Runs"], color="#1565c0")
    for x, y in zip(t["Player"], t["Runs"]):
        plt.text(x, y + 50, y, ha="center")
    plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
    b = cr[cr["Balls"] >= 300]
    plt.scatter(b["Average"], b["SR"], s=b["Runs"] / 10, c="orange", edgecolors="k")
    for _, r in b.iterrows():
        plt.annotate(r["Player"].split()[-1], (r["Average"], r["SR"]), fontsize=7)
    plt.title("Average vs Strike Rate (bubble = runs)"); plt.xlabel("Average"); plt.ylabel("Strike rate")
    plt.tight_layout(); plt.savefig("avg_vs_sr.png"); plt.show()
    cr.groupby("Role")["Runs"].sum().plot(kind="pie", autopct="%1.0f%%", title="Runs by Role")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("role_runs.png"); plt.show()
    s = cr.nlargest(8, "Runs").set_index("Player")
    pd.DataFrame({"Runs from 4s": s["Fours"] * 4, "Runs from 6s": s["Sixes"] * 6}).plot(kind="barh", stacked=True, title="Boundary Runs")
    plt.tight_layout(); plt.savefig("boundaries.png"); plt.show()
    print("Charts saved: top5_runs.png, avg_vs_sr.png, role_runs.png, boundaries.png")


menu = {"1": table, "2": top_runs, "3": best_sr, "4": roles, "5": search, "6": compare, "7": impact, "8": correlation, "9": charts}
print("=" * 60)
print("CRICKET PLAYER STATISTICS ANALYZER".center(60))
print("=" * 60)
while True:
    print("\n1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Well played!")
        break
    try:
        menu.get(ch, lambda: print("Invalid choice"))()
    except KeyError:
        print("Player not found - type the full name exactly.")

        
  1. Start
  2. Create DataFrame and calculated columns
  3. Display menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. Sort / filter / group / plot
  6. Choice is 0? → No: show menu
  7. Stop
#Test case / inputExpected resultStatus
1Player table15 rows with Average and SRPASS
2Top scorers5 rowsPASS
3Best SRPlayers with 500+ ballsPASS
4Role analysis3 rolesPASS
5Search 'sharma'Matching playersPASS
6Compare twoSide-by-side tablePASS
7Impact playersFiltered rowsPASS
8CorrelationMatrixPASS
9Charts4 PNG filesPASS
โš  Limitations
  • Illustrative T20 career-style figures for teaching (not official records)
  • No match-by-match data
  • Only 15 players
  • Bowling economy not included
๐Ÿš€ Future scope
  • Import ball-by-ball data from Cricsheet
  • Fantasy-team selector
  • Bowling analysis
  • Dashboard per tournament

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: cr.
  3. 9 functions are defined (lines 29โ€“86) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
table()29โ€“30Tablemain program (menu)
top_runs()33โ€“34Top runsmain program (menu)
best_sr()37โ€“38Best srmain program (menu)
roles()41โ€“43Rolesmain program (menu)
search()46โ€“49Searchmain program (menu)
compare()52โ€“56Comparemain program (menu)
impact()59โ€“62Impactmain program (menu)
correlation()65โ€“66Correlationmain program (menu)
charts()69โ€“86Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
๐Ÿ“Œ CRICKET PLAYER STATISTICS ANALYZER (Pandas + Matplotlib)
๐Ÿ“Œ Figures are illustrative T20-style career numbers for practice.
9
cr = pd.DataFrame({
    "Player": ["Virat Kohli", "Rohit Sharma", "Suryakumar Yadav", "Shubman Gill", "Yashasvi Jaiswal", "Rishabh Pant", "KL Rahul",
       โ€ฆ
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from { "Player": ["Virat Kohli", "Rohit Sharma", "โ€ฆ; the result is stored in variable cr
22
cr["Average"] = (cr["Runs"] / (cr["Inn"] - cr["NO"])).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of cr["Runs"] / (cr["Inn"] - cr["NO"]) to 2 decimal places; the result is put into cr["Average"] (item "Average" of cr)
23
cr["SR"] = (cr["Runs"] / cr["Balls"] * 100).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of cr["Runs"] / cr["Balls"] * 100 to 2 decimal places; the result is put into cr["SR"] (item "SR" of cr)
24
cr["Boundary_%"] = ((cr["Fours"] * 4 + cr["Sixes"] * 6) / cr["Runs"] * 100).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of (cr["Fours"] * 4 + cr["Sixes"] * 6) / cr["Runโ€ฆ to 1 decimal places; the result is put into cr["Boundary_%"] (item "Boundary_%" of cr)
25
cr["Runs_per_M"] = (cr["Runs"] / cr["M"]).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of cr["Runs"] / cr["M"] to 1 decimal places; the result is put into cr["Runs_per_M"] (item "Runs_per_M" of cr)
26
cr.index = range(1, len(cr) + 1)
๐Ÿงฎ Store / Calculate Gives the numbers from 1 up to len(cr) + 1 - 1; the result is stored in cr.index
89
menu = {"1": table, "2": top_runs, "3": best_sr, "4": roles, "5": search, "6": compare, "7": impact, "8": correlation, "9": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": table, "2": top_runs, "3": best_sr, "4"โ€ฆ in variable menu
90
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
91
print("CRICKET PLAYER STATISTICS ANALYZER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "CRICKET PLAYER STATISTICS ANALYZER".center(6โ€ฆ on the screen
92
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
93
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
94
print("\n1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Table 2.Top Runs 3.Best SR 4.Roโ€ฆ" on the screen
95
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
96
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
97
print("Well played!")
๐Ÿ–ฅ๏ธ Output Displays the text "Well played!" on the screen
98
break
๐Ÿ” Loop BREAK - leaves the loop immediately
99
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
100
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
101
except KeyError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if KeyError occurs - a key that is not in the dictionary
102
print("Player not found - type the full name exactly.")
๐Ÿ–ฅ๏ธ Output Displays the text "Player not found - type the full โ€ฆ" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CRICKET PLAYER STATISTICS ANALYZER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: table()
    shows: Player Role M Runs Average SR Boundary_% Wkts (+16 more lines)
  3. You type 2 at Enter choice:
    runs: top_runs()
    shows: Player Runs Average SR (+6 more lines)
  4. You type 3 at Enter choice:
    runs: best_sr()
    shows: Player Balls Runs SR (+6 more lines)
  5. You type 4 at Enter choice:
    runs: roles()
    shows: Players Runs Avg_SR Wkts (+5 more lines)
  6. You type 5 at Enter choice:
    runs: search()
  7. You type sharma at Player name contains:
    shows: Player Role Runs Average SR Wkts (+2 more lines)
  8. You type 6 at Enter choice:
    runs: compare()
  9. You type Virat Kohli at First player :
  10. You type Shubman Gill at Second player:
    shows: Player Virat Kohli Shubman Gill Better (+8 more lines)
  11. You type 7 at Enter choice:
    runs: impact()
    shows: Player Average SR (+7 more lines)
  12. You type 8 at Enter choice:
    runs: correlation()
    shows: Runs Average SR Sixes Boundary_% (+6 more lines)
  13. You type 9 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+5 more lines)
  14. You type 0 at Enter choice:
    shows: Well played!
โ‘ค Inside each function - line by line
table() - lines 29โ€“30
LineCodeWhat it does
29
def table():
๐Ÿงฉ Function DEFINES a function table(). Python only remembers it here - its body runs later, each time table() is called.
30
print(cr[["Player", "Role", "M", "Runs", "Average", "SR", "Boundary_%", "Wkts"]])
๐Ÿ–ฅ๏ธ Output Displays the value of cr[["Player", "Role", "M", "Runs", "Average",โ€ฆ on the screen
top_runs() - lines 33โ€“34
LineCodeWhat it does
33
def top_runs():
๐Ÿงฉ Function DEFINES a function top_runs(). Python only remembers it here - its body runs later, each time top_runs() is called.
34
print(cr.nlargest(5, "Runs")[["Player", "Runs", "Average", "SR"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of cr.nlargest(5, "Runs")[["Player", "Runs", "Avโ€ฆ on the screen
best_sr() - lines 37โ€“38
LineCodeWhat it does
37
def best_sr():
๐Ÿงฉ Function DEFINES a function best_sr(). Python only remembers it here - its body runs later, each time best_sr() is called.
38
print(cr[cr["Balls"] >= 500].sort_values("SR", ascending=False)[["Player", "Balls", "Runs", "SR"]].head(5).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of cr[cr["Balls"] >= 500].sort_values("SR", asceโ€ฆ on the screen
roles() - lines 41โ€“43
LineCodeWhat it does
41
def roles():
๐Ÿงฉ Function DEFINES a function roles(). Python only remembers it here - its body runs later, each time roles() is called.
42
r = cr.groupby("Role").agg(Players=("Player", "count"), Runs=("Runs", "sum"), Avg_SR=("SR", "mean"), Wkts=("Wkts", "sum"))
๐Ÿงฎ Store / Calculate Calculates the given summary values for every group; the result is stored in variable r
43
print(r.round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of r.round(1) on the screen
search() - lines 46โ€“49
LineCodeWhat it does
46
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
47
k = input("Player name contains: ").strip()
โŒจ๏ธ Input Shows "Player name contains: ", reads the typed text, removes extra spaces (strip) and stores it in variable k
48
r = cr[cr["Player"].str.contains(k, case=False)]
๐Ÿงฎ Store / Calculate Stores the item cr[cr["Player"].str.contains(k, case=False)] in variable r
49
print(r[["Player", "Role", "Runs", "Average", "SR", "Wkts"]].to_string(index=False) if len(r) else "No player found.")
๐Ÿ–ฅ๏ธ Output Displays the value of r[["Player", "Role", "Runs", "Average", "SR",โ€ฆ on the screen
compare() - lines 52โ€“56
LineCodeWhat it does
52
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
53
a, b = input("First player : ").strip(), input("Second player: ").strip()
โŒจ๏ธ Input Stores input("First player : ").strip(), input("Second player: ").strip() into a, b respectively
54
t = cr.set_index("Player").loc[[a, b], ["M", "Runs", "Average", "SR", "Fours", "Sixes", "Boundary_%"]].T
๐Ÿงฎ Store / Calculate Stores cr.set_index("Player").loc[[a, b], ["M", "Runโ€ฆ in variable t
55
t["Better"] = [a if t.loc[i, a] > t.loc[i, b] else b for i in t.index]
๐Ÿงฎ Store / Calculate Puts a new list made by a list comprehension [a if t.loc[i, a] > t.loc[i, b] else b for i โ€ฆ into t["Better"] (item "Better" of t)
56
print(t)
๐Ÿ–ฅ๏ธ Output Displays the value of t on the screen
impact() - lines 59โ€“62
LineCodeWhat it does
59
def impact():
๐Ÿงฉ Function DEFINES a function impact(). Python only remembers it here - its body runs later, each time impact() is called.
60
r = cr[(cr["Average"] >= 35) & (cr["SR"] >= 135)]
๐Ÿงฎ Store / Calculate Stores the item cr[(cr["Average"] >= 35) & (cr["SR"] >= 135)] in variable r
61
print(r[["Player", "Average", "SR"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of r[["Player", "Average", "SR"]].to_string(indeโ€ฆ on the screen
62
print(len(r), "impact batters (Average >= 35 and SR >= 135)")
๐Ÿ–ฅ๏ธ Output Displays the value of len(r), then the text "impact batters (Average >= 35 andโ€ฆ" on the screen
correlation() - lines 65โ€“66
LineCodeWhat it does
65
def correlation():
๐Ÿงฉ Function DEFINES a function correlation(). Python only remembers it here - its body runs later, each time correlation() is called.
66
print(cr[["Runs", "Average", "SR", "Sixes", "Boundary_%"]].corr().round(2))
๐Ÿ–ฅ๏ธ Output Displays the value of cr[["Runs", "Average", "SR", "Sixes", "Boundaโ€ฆ on the screen
charts() - lines 69โ€“86
LineCodeWhat it does
69
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
70
t = cr.nlargest(5, "Runs")
๐Ÿงฎ Store / Calculate Gives the 5 largest values of cr; the result is stored in variable t
71
plt.bar(t["Player"], t["Runs"], color="#1565c0")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of t["Player"], t["Runs"]
72
for x, y in zip(t["Player"], t["Runs"]):
๐Ÿ” Loop LOOP that walks through t["Player"], t["Runs"] together; x, y get one item from each
73
plt.text(x, y + 50, y, ha="center")
๐Ÿ–ฅ๏ธ Output Writes text on the chart
74
plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Top 5 Run Scorers" as the title of the chart
74
plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
74
plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
74
plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "top5_runs.png"
74
plt.title("Top 5 Run Scorers"); plt.xticks(rotation=15); plt.tight_layout(); plt.savefig("top5_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
75
b = cr[cr["Balls"] >= 300]
๐Ÿงฎ Store / Calculate Stores the item cr[cr["Balls"] >= 300] in variable b
76
plt.scatter(b["Average"], b["SR"], s=b["Runs"] / 10, c="orange", edgecolors="k")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of b["Average"], b["SR"]
77
for _, r in b.iterrows():
๐Ÿ” Loop LOOP over each row of b; _, r get (index, row)
78
plt.annotate(r["Player"].split()[-1], (r["Average"], r["SR"]), fontsize=7)
๐Ÿ–ฅ๏ธ Output Writes a note with an arrow on the chart
79
plt.title("Average vs Strike Rate (bubble = runs)"); plt.xlabel("Average"); plt.ylabel("Strike rate")
๐Ÿ–ฅ๏ธ Output Writes "Average vs Strike Rate (bubble = runs)" as the title of the chart
79
plt.title("Average vs Strike Rate (bubble = runs)"); plt.xlabel("Average"); plt.ylabel("Strike rate")
๐Ÿ–ฅ๏ธ Output Writes "Average" as the label of the X-axis
79
plt.title("Average vs Strike Rate (bubble = runs)"); plt.xlabel("Average"); plt.ylabel("Strike rate")
๐Ÿ–ฅ๏ธ Output Writes "Strike rate" as the label of the Y-axis
80
plt.tight_layout(); plt.savefig("avg_vs_sr.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
80
plt.tight_layout(); plt.savefig("avg_vs_sr.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "avg_vs_sr.png"
80
plt.tight_layout(); plt.savefig("avg_vs_sr.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
cr.groupby("Role")["Runs"].sum().plot(kind="pie", autopct="%1.0f%%", title="Runs by Role")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
82
plt.ylabel(""); plt.tight_layout(); plt.savefig("role_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
82
plt.ylabel(""); plt.tight_layout(); plt.savefig("role_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
82
plt.ylabel(""); plt.tight_layout(); plt.savefig("role_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "role_runs.png"
82
plt.ylabel(""); plt.tight_layout(); plt.savefig("role_runs.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
83
s = cr.nlargest(8, "Runs").set_index("Player")
๐Ÿงฎ Store / Calculate Makes column "Player" the index (row labels) of cr.nlargest(8, "Runs"); the result is stored in variable s
84
pd.DataFrame({"Runs from 4s": s["Fours"] * 4, "Runs from 6s": s["Sixes"] * 6}).plot(kind="barh", stacked=True, title="Boundary Runs")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
85
plt.tight_layout(); plt.savefig("boundaries.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
85
plt.tight_layout(); plt.savefig("boundaries.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "boundaries.png"
85
plt.tight_layout(); plt.savefig("boundaries.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
86
print("Charts saved: top5_runs.png, avg_vs_sr.png, role_runs.png, boundaries.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: top5_runs.png, avg_โ€ฆ" on the screen
Q1. How is batting average calculated?

Runs divided by the number of times out = Runs / (Innings - Not outs).

Q2. What is strike rate?

Runs scored per 100 balls = Runs / Balls x 100.

Q3. How do you filter with two conditions?

Use & with brackets: cr[(cr['Average'] >= 40) & (cr['SR'] >= 130)].

Q4. What does str.contains() do?

Checks whether each string contains a substring - useful for searching names.

Q5. Why use a scatter plot for Average vs SR?

It shows consistency and speed of each batter together and spots outliers.

10

Air Quality Index (AQI) Analyzer

PYTHON + PANDASpd.cut for categoriesvalue_countsboolean filteringrolling meanline and pie charts
๐Ÿ“ 97 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 101 output lines๐Ÿ“„ 25+ page report

Classifies daily AQI readings into CPCB categories, counts days in each category, finds the worst days and plots the trend with a 3-day moving average.

โœจ Features
  • Daily AQI of 4 cities (Delhi, Mumbai, Bengaluru, Kolkata) for November 2026 with PM2.5 and PM10
  • AQI category with pd.cut using CPCB bands (Good to Severe) and value_counts
  • 7-day rolling mean and worst / best days
  • City comparison with groupby and pivot
  • Health advisory for any date and city
  • Line, pie, box and bar charts
โ˜ฐ Main menu
1View DataHead of the long DataFrame
2City Summarygroupby city mean / max
3Category Countpd.cut + value_counts per city
4Rolling Average7-day rolling mean for a city
5Worst / Best Daysnlargest / nsmallest
6Health AdvisoryLookup by city and date
7Severe DaysBoolean filter AQI > 400
8Charts4 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Categorise numeric data with pd.cut()
  • Use value_counts() and rolling().mean()
  • Create a line chart with threshold line and a pie chart
๐Ÿ“š Data dictionary
NameTypePurpose
aqiDataFrameDate, City, PM25, PM10, AQI
Categorycolumnpd.cut of AQI into CPCB bands
BANDS / LABELSlists0,50,100,200,300,400,500 and names
ADVICEdictCategory -> health message
Why it matters: A socially relevant Delhi-NCR project that applies Pandas categorisation and visualisation.
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
import numpy as np
# =====================================================================
#   AIR QUALITY INDEX (AQI) ANALYZER  (Pandas + Matplotlib)
#   Values simulated to resemble November pollution patterns.
# =====================================================================
rng = np.random.default_rng(3)
days = pd.date_range("2026-11-01", "2026-11-30")
BASE = {"Delhi": 330, "Kolkata": 190, "Mumbai": 140, "Bengaluru": 85}
frames = []
for city, base in BASE.items():
    wave = base * (1 + 0.25 * np.sin(np.arange(30) / 4)) + rng.normal(0, base * 0.12, 30)
    pm25 = np.clip(wave * 0.55, 10, None).round(0)
    frames.append(pd.DataFrame({"Date": days, "City": city, "PM25": pm25, "PM10": (pm25 * 1.7).round(0), "AQI": np.clip(wave, 20, 500).round(0).astype(int)}))
aqi = pd.concat(frames, ignore_index=True)
BANDS = [0, 50, 100, 200, 300, 400, 500]
LABELS = ["Good", "Satisfactory", "Moderate", "Poor", "Very Poor", "Severe"]
aqi["Category"] = pd.cut(aqi["AQI"], BANDS, labels=LABELS)
ADVICE = {"Good": "Minimal impact. Enjoy outdoor activities.", "Satisfactory": "Minor breathing discomfort to sensitive people.",
          "Moderate": "Discomfort to people with asthma / heart disease.", "Poor": "Avoid long outdoor exercise; wear a mask.",
          "Very Poor": "Respiratory illness on long exposure. Stay indoors.", "Severe": "Health emergency! Avoid going out; use air purifiers."}


def view():
    print(aqi.head(10).to_string(index=False))
    print("... total rows:", len(aqi))


def summary():
    s = aqi.groupby("City")["AQI"].agg(["mean", "min", "max", "std"]).round(1).sort_values("mean", ascending=False)
    print(s)
    print("\nMost polluted city:", s.index[0], "| Cleanest:", s.index[-1])


def categories():
    print(pd.crosstab(aqi["City"], aqi["Category"]))


def rolling():
    c = input("City: ").strip().title()
    d = aqi[aqi["City"] == c].set_index("Date")["AQI"]
    r = pd.DataFrame({"AQI": d, "7-day mean": d.rolling(7).mean().round(1)})
    print(r.iloc[6::3])


def worst_best():
    cols = ["Date", "City", "AQI", "Category"]
    print("WORST 5 DAYS\n", aqi.nlargest(5, "AQI")[cols].to_string(index=False))
    print("\nBEST 5 DAYS\n", aqi.nsmallest(5, "AQI")[cols].to_string(index=False))


def advisory():
    c, d = input("City: ").strip().title(), input("Date (yyyy-mm-dd): ").strip()
    r = aqi[(aqi["City"] == c) & (aqi["Date"] == d)]
    if r.empty:
        print("No data for", c, "on", d)
    else:
        cat = r["Category"].iloc[0]
        print(f"{c} on {d}: AQI {r['AQI'].iloc[0]} ({cat}) | PM2.5 {r['PM25'].iloc[0]:.0f}")
        print("Advice:", ADVICE[cat])


def severe():
    s = aqi[aqi["AQI"] > 400]
    print(s[["Date", "City", "AQI"]].to_string(index=False) if len(s) else "No severe days.")
    print(len(s), "severe days in the month")


def charts():
    p = aqi.pivot(index="Date", columns="City", values="AQI")
    p.plot(figsize=(9, 4.5), title="Daily AQI - November 2026")
    for y, c in zip([100, 200, 300, 400], ["green", "orange", "red", "purple"]):
        plt.axhline(y, color=c, linestyle=":", linewidth=1)
    plt.ylabel("AQI"); plt.tight_layout(); plt.savefig("aqi_trend.png"); plt.show()
    aqi[aqi["City"] == "Delhi"]["Category"].value_counts().loc[lambda s: s > 0].plot(kind="pie", autopct="%1.0f%%", title="Delhi - Share of AQI Categories")
    plt.ylabel(""); plt.tight_layout(); plt.savefig("aqi_share.png"); plt.show()
    p.plot(kind="box", title="AQI Spread by City"); plt.tight_layout(); plt.savefig("city_compare.png"); plt.show()
    aqi.groupby("City")[["PM25", "PM10"]].mean().plot(kind="bar", color=["#8d6e63", "#bdbdbd"], title="Average PM2.5 and PM10")
    plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("pollutants.png"); plt.show()
    print("Charts saved: aqi_trend.png, aqi_share.png, city_compare.png, pollutants.png")


menu = {"1": view, "2": summary, "3": categories, "4": rolling, "5": worst_best, "6": advisory, "7": severe, "8": charts}
print("=" * 60)
print("AIR QUALITY INDEX ANALYZER".center(60))
print("=" * 60)
while True:
    print("\n1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit")
    ch = input("Enter choice: ").strip()
    if ch == "0":
        print("Breathe safe!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Create AQI data for 4 cities
  3. Add Category with pd.cut
  4. Display menu and read choice
  5. Valid option? → No: 'Invalid choice'
  6. Analyse / filter / plot
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1View data120 rowsPASS
2City summaryDelhi highest meanPASS
3Category countTable of bandsPASS
4Rolling Delhi7-day meanPASS
5Worst daysTop 5 AQIPASS
6Advisory Delhi 2026-11-05Category + advicePASS
7Advisory with wrong city'No data'PASS
8Severe daysRows with AQI > 400PASS
9Charts4 PNG filesPASS
โš  Limitations
  • AQI values simulated to resemble seasonal patterns (not official CPCB data)
  • Only 4 cities
  • AQI computed from PM only
  • One month
๐Ÿš€ Future scope
  • Fetch real data from CPCB / data.gov.in API
  • Alert via SMS / e-mail
  • Correlate with stubble burning / weather
  • Map of stations

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 1): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, numpy - fast arrays and maths are loaded.
  2. Global variables / constants are created: rng, days, BASE, frames, aqi, BANDS, LABELS, ADVICE.
  3. 8 functions are defined (lines 27โ€“83) - Python stores them but does NOT run them yet.
  4. Main program starts at line 3: pd.set_option("display.width", 120) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
view()27โ€“29Viewmain program (menu)
summary()32โ€“35Summarymain program (menu)
categories()38โ€“39Categoriesmain program (menu)
rolling()42โ€“46Rollingmain program (menu)
worst_best()49โ€“52Worst bestmain program (menu)
advisory()55โ€“63Advisorymain program (menu)
severe()66โ€“69Severemain program (menu)
charts()72โ€“83Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
3
pd.set_option("display.width", 120)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
4
pd.set_option("display.max_columns", 20)
๐Ÿ“ฆ Library / Data Changes a pandas display setting
5
import numpy as np
๐Ÿ“ฆ Library / Data Loads the module numpy (nick-name np) - fast arrays and maths
๐Ÿ“Œ AIR QUALITY INDEX (AQI) ANALYZER (Pandas + Matplotlib)
๐Ÿ“Œ Values simulated to resemble November pollution patterns.
10
rng = np.random.default_rng(3)
๐Ÿ“ฆ Library / Data Creates a random number generator with seed 3; the result is stored in variable rng
11
days = pd.date_range("2026-11-01", "2026-11-30")
๐Ÿ“ฆ Library / Data Makes a list of dates; the result is stored in variable days
12
BASE = {"Delhi": 330, "Kolkata": 190, "Mumbai": 140, "Bengaluru": 85}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Delhi": 330, "Kolkata": 190, "Mumbai": 140,โ€ฆ in variable BASE
13
frames = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable frames
14
for city, base in BASE.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary BASE; city, base get one pair each round
15
wave = base * (1 + 0.25 * np.sin(np.arange(30) / 4)) + rng.normal(0, base * 0.12, 30)
๐Ÿ“ฆ Library / Data Stores the value of base * (1 + 0.25 * np.sin(np.arange(30) / 4))โ€ฆ (calculated using +) in variable wave
16
pm25 = np.clip(wave * 0.55, 10, None).round(0)
๐Ÿ“ฆ Library / Data Rounds the values of np.clip(wave * 0.55, 10, None) to 0 decimal places; the result is stored in variable pm25
17
frames.append(pd.DataFrame({"Date": days, "City": city, "PM25": pm25, "PM10": (pm25 * 1.7).round(0), "AQI": np.clip(wave, 20, 500).round(0).astype(int)}))
๐Ÿ“ฆ Library / Data Adds pd.DataFrame({"Date": days, "City": city, "PMโ€ฆ at the end of list frames
18
aqi = pd.concat(frames, ignore_index=True)
๐Ÿ“ฆ Library / Data Joins DataFrames one below the other; the result is stored in variable aqi
19
BANDS = [0, 50, 100, 200, 300, 400, 500]
๐Ÿงฎ Store / Calculate Stores a list [0, 50, 100, 200, 300, 400, 500] in variable BANDS
20
LABELS = ["Good", "Satisfactory", "Moderate", "Poor", "Very Poor", "Severe"]
๐Ÿงฎ Store / Calculate Stores a list ["Good", "Satisfactory", "Moderate", "Poor", โ€ฆ in variable LABELS
21
aqi["Category"] = pd.cut(aqi["AQI"], BANDS, labels=LABELS)
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into aqi["Category"] (item "Category" of aqi)
22
ADVICE = {"Good": "Minimal impact. Enjoy outdoor activities.", "Satisfactory": "Minor breathing discomfort to sensitive people.",
          "Moderate": "Discโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Good": "Minimal impact. Enjoy outdoor activโ€ฆ in variable ADVICE
86
menu = {"1": view, "2": summary, "3": categories, "4": rolling, "5": worst_best, "6": advisory, "7": severe, "8": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": summary, "3": categories, "4โ€ฆ in variable menu
87
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
88
print("AIR QUALITY INDEX ANALYZER".center(60))
๐Ÿ–ฅ๏ธ Output Displays the value of "AIR QUALITY INDEX ANALYZER".center(60) on the screen
89
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
90
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
91
print("\n1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.City Summary 3.Categorieโ€ฆ" on the screen
92
ch = input("Enter choice: ").strip()
โŒจ๏ธ Input Shows "Enter choice: ", reads the typed text, removes extra spaces (strip) and stores it in variable ch
93
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
94
print("Breathe safe!")
๐Ÿ–ฅ๏ธ Output Displays the text "Breathe safe!" on the screen
95
break
๐Ÿ” Loop BREAK - leaves the loop immediately
96
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: AIR QUALITY INDEX ANALYZER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: view()
    shows: Date City PM25 PM10 AQI Category (+12 more lines)
  3. You type 2 at Enter choice:
    runs: summary()
    shows: mean min max std (+7 more lines)
  4. You type 3 at Enter choice:
    runs: categories()
    shows: Category Good Satisfactory Moderate Poor Very Poor Severe (+6 more lines)
  5. You type 4 at Enter choice:
    runs: rolling()
  6. You type Delhi at City:
    shows: AQI 7-day mean (+10 more lines)
  7. You type 5 at Enter choice:
    runs: worst_best()
    shows: WORST 5 DAYS (+14 more lines)
  8. You type 6 at Enter choice:
    runs: advisory()
  9. You type Delhi at City:
  10. You type 2026-11-05 at Date (yyyy-mm-dd):
    shows: Delhi on 2026-11-05: AQI 381 (Very Poor) | PM2.5 210 (+2 more lines)
  11. You type 6 at Enter choice:
    runs: advisory()
  12. You type Chennai at City:
  13. You type 2026-11-05 at Date (yyyy-mm-dd):
    shows: No data for Chennai on 2026-11-05 (+1 more lines)
  14. You type 7 at Enter choice:
    runs: severe()
    shows: Date City AQI (+7 more lines)
  15. You type 8 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+5 more lines)
  16. You type 0 at Enter choice:
    shows: Breathe safe!
โ‘ค Inside each function - line by line
view() - lines 27โ€“29
LineCodeWhat it does
27
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
28
print(aqi.head(10).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of aqi.head(10).to_string(index=False) on the screen
29
print("... total rows:", len(aqi))
๐Ÿ–ฅ๏ธ Output Displays the text "... total rows:", then the value of len(aqi) on the screen
summary() - lines 32โ€“35
LineCodeWhat it does
32
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
33
s = aqi.groupby("City")["AQI"].agg(["mean", "min", "max", "std"]).round(1).sort_values("mean", ascending=False)
๐Ÿงฎ Store / Calculate Sorts aqi.groupby("City")["AQI"].agg(["mean", "min"โ€ฆ by "mean" in descending order; the result is stored in variable s
34
print(s)
๐Ÿ–ฅ๏ธ Output Displays the value of s on the screen
35
print("\nMost polluted city:", s.index[0], "| Cleanest:", s.index[-1])
๐Ÿ–ฅ๏ธ Output Displays the text "Most polluted city:", then the value of s.index[0], then the text "| Cleanest:", then the value of s.index[-1] on the screen
categories() - lines 38โ€“39
LineCodeWhat it does
38
def categories():
๐Ÿงฉ Function DEFINES a function categories(). Python only remembers it here - its body runs later, each time categories() is called.
39
print(pd.crosstab(aqi["City"], aqi["Category"]))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.crosstab(aqi["City"], aqi["Category"]) on the screen
rolling() - lines 42โ€“46
LineCodeWhat it does
42
def rolling():
๐Ÿงฉ Function DEFINES a function rolling(). Python only remembers it here - its body runs later, each time rolling() is called.
43
c = input("City: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable c
44
d = aqi[aqi["City"] == c].set_index("Date")["AQI"]
๐Ÿงฎ Store / Calculate Stores the item aqi[aqi["City"] == c].set_index("Date")["AQI"] in variable d
45
r = pd.DataFrame({"AQI": d, "7-day mean": d.rolling(7).mean().round(1)})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"AQI": d, "7-day mean": d.rolling(7).mean().โ€ฆ; the result is stored in variable r
46
print(r.iloc[6::3])
๐Ÿ–ฅ๏ธ Output Displays the value of r.iloc[6::3] on the screen
worst_best() - lines 49โ€“52
LineCodeWhat it does
49
def worst_best():
๐Ÿงฉ Function DEFINES a function worst_best(). Python only remembers it here - its body runs later, each time worst_best() is called.
50
cols = ["Date", "City", "AQI", "Category"]
๐Ÿงฎ Store / Calculate Stores a list ["Date", "City", "AQI", "Category"] in variable cols
51
print("WORST 5 DAYS\n", aqi.nlargest(5, "AQI")[cols].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "WORST 5 DAYS", then the value of aqi.nlargest(5, "AQI")[cols].to_string(index=โ€ฆ on the screen
52
print("\nBEST 5 DAYS\n", aqi.nsmallest(5, "AQI")[cols].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "BEST 5 DAYS", then the value of aqi.nsmallest(5, "AQI")[cols].to_string(indexโ€ฆ on the screen
advisory() - lines 55โ€“63
LineCodeWhat it does
55
def advisory():
๐Ÿงฉ Function DEFINES a function advisory(). Python only remembers it here - its body runs later, each time advisory() is called.
56
c, d = input("City: ").strip().title(), input("Date (yyyy-mm-dd): ").strip()
โŒจ๏ธ Input Stores input("City: ").strip().title(), input("Date (yyyy-mm-dd): ").strip() into c, d respectively
57
r = aqi[(aqi["City"] == c) & (aqi["Date"] == d)]
๐Ÿงฎ Store / Calculate Stores the item aqi[(aqi["City"] == c) & (aqi["Date"] == d)] in variable r
58
if r.empty:
๐Ÿ”€ Decision CHECKS whether r.empty is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
59
print("No data for", c, "on", d)
๐Ÿ–ฅ๏ธ Output Displays the text "No data for", then the value of c, then the text "on", then the value of d on the screen
60
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
61
cat = r["Category"].iloc[0]
๐Ÿงฎ Store / Calculate Stores the item r["Category"].iloc[0] in variable cat
62
print(f"{c} on {d}: AQI {r['AQI'].iloc[0]} ({cat}) | PM2.5 {r['PM25'].iloc[0]:.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c} on {d}: AQI {r['AQI'].iloc[0]} ({cat}) โ€ฆ with the values filled into { } on the screen
63
print("Advice:", ADVICE[cat])
๐Ÿ–ฅ๏ธ Output Displays the text "Advice:", then the value of ADVICE[cat] on the screen
severe() - lines 66โ€“69
LineCodeWhat it does
66
def severe():
๐Ÿงฉ Function DEFINES a function severe(). Python only remembers it here - its body runs later, each time severe() is called.
67
s = aqi[aqi["AQI"] > 400]
๐Ÿงฎ Store / Calculate Stores the item aqi[aqi["AQI"] > 400] in variable s
68
print(s[["Date", "City", "AQI"]].to_string(index=False) if len(s) else "No severe days.")
๐Ÿ–ฅ๏ธ Output Displays the value of s[["Date", "City", "AQI"]].to_string(index=Faโ€ฆ on the screen
69
print(len(s), "severe days in the month")
๐Ÿ–ฅ๏ธ Output Displays the value of len(s), then the text "severe days in the month" on the screen
charts() - lines 72โ€“83
LineCodeWhat it does
72
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
73
p = aqi.pivot(index="Date", columns="City", values="AQI")
๐Ÿงฎ Store / Calculate Calls aqi.pivot(); the result is stored in variable p
74
p.plot(figsize=(9, 4.5), title="Daily AQI - November 2026")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
75
for y, c in zip([100, 200, 300, 400], ["green", "orange", "red", "purple"]):
๐Ÿ” Loop LOOP that walks through [100, 200, 300, 400], ["green", "orange", "red", "purple"] together; y, c get one item from each
76
plt.axhline(y, color=c, linestyle=":", linewidth=1)
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
77
plt.ylabel("AQI"); plt.tight_layout(); plt.savefig("aqi_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "AQI" as the label of the Y-axis
77
plt.ylabel("AQI"); plt.tight_layout(); plt.savefig("aqi_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
77
plt.ylabel("AQI"); plt.tight_layout(); plt.savefig("aqi_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "aqi_trend.png"
77
plt.ylabel("AQI"); plt.tight_layout(); plt.savefig("aqi_trend.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
78
aqi[aqi["City"] == "Delhi"]["Category"].value_counts().loc[lambda s: s > 0].plot(kind="pie", autopct="%1.0f%%", title="Delhi - Share of AQI Categories")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
79
plt.ylabel(""); plt.tight_layout(); plt.savefig("aqi_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "" as the label of the Y-axis
79
plt.ylabel(""); plt.tight_layout(); plt.savefig("aqi_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
79
plt.ylabel(""); plt.tight_layout(); plt.savefig("aqi_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "aqi_share.png"
79
plt.ylabel(""); plt.tight_layout(); plt.savefig("aqi_share.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
80
p.plot(kind="box", title="AQI Spread by City"); plt.tight_layout(); plt.savefig("city_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
80
p.plot(kind="box", title="AQI Spread by City"); plt.tight_layout(); plt.savefig("city_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
80
p.plot(kind="box", title="AQI Spread by City"); plt.tight_layout(); plt.savefig("city_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "city_compare.png"
80
p.plot(kind="box", title="AQI Spread by City"); plt.tight_layout(); plt.savefig("city_compare.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
aqi.groupby("City")[["PM25", "PM10"]].mean().plot(kind="bar", color=["#8d6e63", "#bdbdbd"], title="Average PM2.5 and PM10")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("pollutants.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("pollutants.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("pollutants.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "pollutants.png"
82
plt.xticks(rotation=0); plt.tight_layout(); plt.savefig("pollutants.png"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
83
print("Charts saved: aqi_trend.png, aqi_share.png, city_compare.png, pollutants.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: aqi_trend.png, aqi_โ€ฆ" on the screen
Q1. What is AQI?

Air Quality Index - a single number that shows how polluted the air is; CPCB bands are Good (0-50) to Severe (401-500).

Q2. How does pd.cut work?

It puts each value in a bin given by edges, e.g. pd.cut(aqi, [0,50,100,...], labels=[...]).

Q3. What is a rolling mean used for?

To smooth daily ups and downs and see the trend over 7 days.

Q4. How is a pivot useful here?

It changes the long table (Date, City) into a wide table with one column per city for comparison.

Q5. What is a box plot?

A chart showing median, quartiles and outliers - good for comparing spread of AQI across cities.

๐Ÿค– Class IX Artificial Intelligence (417) โ€” 10 SDG Python Projects 10 projects

01

Smart Water Usage Tracker (SDG 6)

PYTHONSDG 6 - Clean Water and Sanitationinput()listsfor loopsum()max()
๐Ÿ“ 118 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

Records the water used by a family for 7 days, finds the total, daily average, highest and lowest day, compares with the recommended 135 litres per person per day and gives saving tips.

โœจ Features
  • Daily water use of a family recorded for 7 days (lists)
  • Weekly report with total, average, highest and lowest day and a text bar chart
  • Per-person use compared with the 135 L/person/day norm
  • Activity-wise break-up (bathing, washing, cooking, garden...) to find where water is wasted
  • Saving goal planner: litres and money saved if use is cut by a chosen %
  • Leak detector rule: day usage more than 15 % above the average is flagged
โ˜ฐ Main menu
1Enter Weekly DataFamily members and 7 days of usage
2Weekly ReportTotal, average, max, min, bar chart
3Compare with Norm135 L per person per day
4Activity Break-upLitres per activity and share
5Leak / Spike DetectorDays above average + 15 %
6Saving PlannerSaving for a chosen % cut
7Water TipsTips based on largest activity
0ExitEnds program
๐ŸŽฏ Objectives
  • Collect a week of water-usage data and store it in a Python list
  • Analyse the data using total, average, maximum and minimum
  • Suggest water-saving actions based on the analysis (rule-based decision)
๐Ÿ“š Data dictionary
NameTypePurpose
dayslist7 day names
usagelist of floatLitres used each day
membersintFamily size
acts / sharelistsActivity names and % share
NORMint135 litres per person per day (urban norm)
Why it matters: Builds data literacy - students collect real household data and turn it into an actionable insight for water conservation.
# =====================================================================
#   SMART WATER USAGE TRACKER   (SDG 6 : Clean Water and Sanitation)
#   Concepts: lists, loops, functions, if-elif, menu with while loop
# =====================================================================
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
NORM, RATE = 135, 0.05            # litres/person/day, Rs. per litre (approx.)
acts = ["Bathing", "Toilet flush", "Washing clothes", "Cooking & drinking", "Utensils", "Cleaning/garden"]
share = [30, 22, 18, 8, 12, 10]   # typical % share of household water use
usage = []
members = 0


def read_number(msg):
    """Keeps asking until a non-negative number is typed."""
    while True:
        v = float(input(msg))
        if v >= 0:
            return v
        print("  Invalid value! Please enter a positive number.")


def enter_data():
    global members
    usage.clear()
    members = int(input("Number of family members: "))
    for d in days:
        usage.append(read_number("Water used on " + d + " (litres): "))
    print("Data saved for", len(usage), "days.")


def report():
    total = sum(usage)
    avg = total / len(usage)
    print("\n----- WEEKLY REPORT -----")
    for i in range(7):
        print(f"{days[i]:<10} {usage[i]:>6.0f} L  " + "#" * int(usage[i] // 50))
    print("Total water used   :", total, "litres")
    print("Average per day    :", round(avg, 2), "litres")
    print("Highest usage day  :", days[usage.index(max(usage))], "(", max(usage), "L )")
    print("Lowest usage day   :", days[usage.index(min(usage))], "(", min(usage), "L )")


def norm_check():
    pp = sum(usage) / 7 / members
    print("Per person per day :", round(pp, 2), "litres  (norm =", NORM, "L)")
    if pp > NORM:
        extra = (pp - NORM) * members * 7
        print("ABOVE NORM by", round(pp - NORM, 1), "L/person/day")
        print("Extra water used this week:", round(extra, 1), "litres")
    else:
        print("Well done! Your family is within the recommended limit.")


def breakup():
    total = sum(usage)
    print(f"{'Activity':<20}{'Share':>6}{'Litres':>9}")
    for i in range(len(acts)):
        lit = total * share[i] / 100
        print(f"{acts[i]:<20}{share[i]:>5}%{lit:>9.0f}  " + "*" * (share[i] // 2))


def spikes():
    avg = sum(usage) / 7
    found = 0
    for i in range(7):
        if usage[i] > 1.15 * avg:
            print(f"ALERT: {days[i]} used {usage[i]:.0f} L (average {avg:.0f} L) - check for leaks / wastage")
            found += 1
    if found == 0:
        print("No unusual spike found. Usage is steady.")


def planner():
    pct = float(input("Target reduction (%): "))
    week = sum(usage)
    saved = week * pct / 100
    print("Litres saved per week :", round(saved, 1))
    print("Litres saved per year :", round(saved * 52))
    print("Money saved per year  : Rs.", round(saved * 52 * RATE, 2))
    print("That is enough drinking water for", round(saved * 52 / (3 * 365), 1), "people for a year!")


def tips():
    big = share.index(max(share))
    print("Largest use:", acts[big])
    print("Tips: 1) Use a bucket instead of a shower  2) Fix leaking taps (a drip wastes ~30 L/day)")
    print("      3) Reuse RO waste water for mopping   4) Run washing machine on full load")


print("=" * 50)
print("   SMART WATER USAGE TRACKER  (SDG 6)")
print("=" * 50)
while True:
    print("\n1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Every drop counts. Goodbye!")
        break
    elif ch == "1":
        enter_data()
    elif ch in ["2", "3", "4", "5", "6", "7"]:
        if len(usage) == 0:
            print("Please enter data first (option 1).")
        elif ch == "2":
            report()
        elif ch == "3":
            norm_check()
        elif ch == "4":
            breakup()
        elif ch == "5":
            spikes()
        elif ch == "6":
            planner()
        else:
            tips()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is 1 (enter data)? → No: check data exists and run report
  4. Read members and 7 daily values
  5. Compute total, average, max, min
  6. Per person > 135 L? → No: 'Within limit'
  7. Show saving and tips
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Report before entering data'Enter data first'PASS
2Members 4, 7 valuesData storedPASS
3Weekly reportTotal 4180 L, highest SaturdayPASS
4Norm check149.3 L/person - above normPASS
5Spike detectorSaturday (700 L) flaggedPASS
6Saving 15 %Litres and Rs. savedPASS
7Negative litres'Invalid value' re-askedPASS
8Choice 9'Invalid choice'PASS
โš  Limitations
  • Values typed by the user - no smart meter
  • Activity share is an estimate
  • One week of data only
  • Water cost rate assumed
๐Ÿš€ Future scope
  • Read data from an IoT flow sensor
  • Store weeks in a CSV file and compare
  • Mobile alert when usage spikes
  • Society-level comparison dashboard

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: days, acts, share, usage, members.
  2. 8 functions are defined (lines 13โ€“87) - Python stores them but does NOT run them yet.
  3. Main program starts at line 6: NORM, RATE = 135, 0.05 # litres/person/day, Rs. per litre ( - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
read_number(msg)13โ€“19Keeps asking until a non-negative number is typed.enter_data()
enter_data()22โ€“28Enter datamain program
report()31โ€“40Reportmain program
norm_check()43โ€“51Norm checkmain program
breakup()54โ€“59Breakupmain program
spikes()62โ€“70Spikesmain program
planner()73โ€“80Plannermain program
tips()83โ€“87Tipsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
6
NORM, RATE = 135, 0.05            # litres/person/day, Rs. per litre (approx.)
๐Ÿงฎ Store / Calculate Stores 135, 0.05 into NORM, RATE respectively
7
acts = ["Bathing", "Toilet flush", "Washing clothes", "Cooking & drinking", "Utensils", "Cleaning/garden"]
๐Ÿงฎ Store / Calculate Stores a list ["Bathing", "Toilet flush", "Washing clothes"โ€ฆ in variable acts
8
share = [30, 22, 18, 8, 12, 10]   # typical % share of household water use
๐Ÿงฎ Store / Calculate Stores a list [30, 22, 18, 8, 12, 10] in variable share
9
usage = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable usage
10
members = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable members
90
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
91
print("   SMART WATER USAGE TRACKER  (SDG 6)")
๐Ÿ–ฅ๏ธ Output Displays the text "SMART WATER USAGE TRACKER (SDG 6)" on the screen
92
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
93
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
94
print("\n1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Enter Data 2.Report 3.Norm Checโ€ฆ" on the screen
95
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
96
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
97
print("Every drop counts. Goodbye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Every drop counts. Goodbye!" on the screen
98
break
๐Ÿ” Loop BREAK - leaves the loop immediately
99
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
100
enter_data()
๐Ÿงฎ Store / Calculate Calls our own function enter_data()
101
elif ch in ["2", "3", "4", "5", "6", "7"]:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is present in ["2", "3", "4", "5", "6", "7"]
102
if len(usage) == 0:
๐Ÿ”€ Decision CHECKS whether len(usage) is equal to 0. If True, the indented lines below run; otherwise Python jumps to the elif/else part
103
print("Please enter data first (option 1).")
๐Ÿ–ฅ๏ธ Output Displays the text "Please enter data first (option 1โ€ฆ" on the screen
104
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
105
report()
๐Ÿงฎ Store / Calculate Calls our own function report()
106
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
107
norm_check()
๐Ÿงฎ Store / Calculate Calls our own function norm_check()
108
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
109
breakup()
๐Ÿงฎ Store / Calculate Calls our own function breakup()
110
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
111
spikes()
๐Ÿงฎ Store / Calculate Calls our own function spikes()
112
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
113
planner()
๐Ÿงฎ Store / Calculate Calls our own function planner()
114
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
115
tips()
๐Ÿงฎ Store / Calculate Calls our own function tips()
116
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
117
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: SMART WATER USAGE TRACKER (SDG 6) (+1 more lines)
  2. You type 2 at Enter choice:
    shows: Please enter data first (option 1). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: enter_data()
  4. You type 4 at Number of family members:
    runs: read_number()
  5. You type 560 at Water used on Monday (litres):
    runs: read_number()
  6. You type 610 at Water used on Tuesday (litres):
    runs: read_number()
  7. You type 585 at Water used on Wednesday (litres):
    runs: read_number()
  8. You type -20 at Water used on Thursday (litres):
    shows: Invalid value! Please enter a positive number.
  9. You type 540 at Water used on Thursday (litres):
    runs: read_number()
  10. You type 620 at Water used on Friday (litres):
    runs: read_number()
  11. You type 700 at Water used on Saturday (litres):
    runs: read_number()
  12. You type 565 at Water used on Sunday (litres):
    shows: Data saved for 7 days. (+1 more lines)
  13. You type 2 at Enter choice:
    runs: report()
    shows: ----- WEEKLY REPORT ----- (+12 more lines)
  14. You type 3 at Enter choice:
    runs: norm_check()
    shows: Per person per day : 149.29 litres (norm = 135 L) (+3 more lines)
  15. You type 4 at Enter choice:
    runs: breakup()
    shows: Activity Share Litres (+7 more lines)
  16. You type 5 at Enter choice:
    runs: spikes()
    shows: ALERT: Saturday used 700 L (average 597 L) - check for leaks / wastage (+1 more lines)
  17. You type 6 at Enter choice:
    runs: planner()
  18. You type 15 at Target reduction (%):
    shows: Litres saved per week : 627.0 (+4 more lines)
  19. You type 7 at Enter choice:
    runs: tips()
    shows: Largest use: Bathing (+3 more lines)
  20. You type 9 at Enter choice:
    shows: Invalid choice (+1 more lines)
  21. You type 0 at Enter choice:
    shows: Every drop counts. Goodbye!
โ‘ค Inside each function - line by line
read_number() - lines 13โ€“19
LineCodeWhat it does
13
def read_number(msg):
๐Ÿงฉ Function DEFINES a function read_number(msg). Python only remembers it here - its body runs later, each time read_number() is called.
15
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
16
v = float(input(msg))
โŒจ๏ธ Input Shows msg, reads what the user types, and float() converts that text into a decimal number; the number is stored in variable v
17
if v >= 0:
๐Ÿ”€ Decision CHECKS whether v is greater than or equal to 0. If True, the indented lines below run; otherwise they are skipped
18
return v
๐Ÿงฉ Function Sends back (returns) the value of v to the line that called the function
19
print("  Invalid value! Please enter a positive number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid value! Please enter a posโ€ฆ" on the screen
enter_data() - lines 22โ€“28
LineCodeWhat it does
22
def enter_data():
๐Ÿงฉ Function DEFINES a function enter_data(). Python only remembers it here - its body runs later, each time enter_data() is called.
23
global members
๐Ÿงฉ Function Tells Python that members means the GLOBAL variable (outside the function)
24
usage.clear()
๐Ÿงฎ Store / Calculate Removes all items from usage
25
members = int(input("Number of family members: "))
โŒจ๏ธ Input Shows "Number of family members: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable members
26
for d in days:
๐Ÿ” Loop LOOP: takes each item of days one-by-one into d and runs the indented block for it
27
usage.append(read_number("Water used on " + d + " (litres): "))
๐Ÿงฎ Store / Calculate Adds read_number("Water used on " + d + " (litres)โ€ฆ at the end of list usage
28
print("Data saved for", len(usage), "days.")
๐Ÿ–ฅ๏ธ Output Displays the text "Data saved for", then the value of len(usage), then the text "days." on the screen
report() - lines 31โ€“40
LineCodeWhat it does
31
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
32
total = sum(usage)
๐Ÿงฎ Store / Calculate Adds up all the values in usage; the result is stored in variable total
33
avg = total / len(usage)
๐Ÿงฎ Store / Calculate Stores the value of total / len(usage) (calculated using รท) in variable avg
34
print("\n----- WEEKLY REPORT -----")
๐Ÿ–ฅ๏ธ Output Displays the text "----- WEEKLY REPORT -----" on the screen
35
for i in range(7):
๐Ÿ” Loop LOOP: gives the numbers 0 to 6 (7 numbers); for each number, i takes that value and the indented block runs once
36
print(f"{days[i]:<10} {usage[i]:>6.0f} L  " + "#" * int(usage[i] // 50))
๐Ÿ–ฅ๏ธ Output Displays the value of f"{days[i]:<10} {usage[i]:>6.0f} L " + "#" * โ€ฆ on the screen
37
print("Total water used   :", total, "litres")
๐Ÿ–ฅ๏ธ Output Displays the text "Total water used :", then the value of total, then the text "litres" on the screen
38
print("Average per day    :", round(avg, 2), "litres")
๐Ÿ–ฅ๏ธ Output Displays the text "Average per day :", then the value of round(avg, 2), then the text "litres" on the screen
39
print("Highest usage day  :", days[usage.index(max(usage))], "(", max(usage), "L )")
๐Ÿ–ฅ๏ธ Output Displays the text "Highest usage day :", then the value of days[usage.index(max(usage))], then the text "(", then the value of max(usage), then the text "L )" on the screen
40
print("Lowest usage day   :", days[usage.index(min(usage))], "(", min(usage), "L )")
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest usage day :", then the value of days[usage.index(min(usage))], then the text "(", then the value of min(usage), then the text "L )" on the screen
norm_check() - lines 43โ€“51
LineCodeWhat it does
43
def norm_check():
๐Ÿงฉ Function DEFINES a function norm_check(). Python only remembers it here - its body runs later, each time norm_check() is called.
44
pp = sum(usage) / 7 / members
๐Ÿงฎ Store / Calculate Stores the value of sum(usage) / 7 / members (calculated using รท) in variable pp
45
print("Per person per day :", round(pp, 2), "litres  (norm =", NORM, "L)")
๐Ÿ–ฅ๏ธ Output Displays the text "Per person per day :", then the value of round(pp, 2), then the text "litres (norm =", then the value of NORM, then the text "L)" on the screen
46
if pp > NORM:
๐Ÿ”€ Decision CHECKS whether pp is greater than NORM. If True, the indented lines below run; otherwise Python jumps to the elif/else part
47
extra = (pp - NORM) * members * 7
๐Ÿงฎ Store / Calculate Stores the value of (pp - NORM) * members * 7 (calculated using ร—) in variable extra
48
print("ABOVE NORM by", round(pp - NORM, 1), "L/person/day")
๐Ÿ–ฅ๏ธ Output Displays the text "ABOVE NORM by", then the value of round(pp - NORM, 1), then the text "L/person/day" on the screen
49
print("Extra water used this week:", round(extra, 1), "litres")
๐Ÿ–ฅ๏ธ Output Displays the text "Extra water used this week:", then the value of round(extra, 1), then the text "litres" on the screen
50
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
51
print("Well done! Your family is within the recommended limit.")
๐Ÿ–ฅ๏ธ Output Displays the text "Well done! Your family is within โ€ฆ" on the screen
breakup() - lines 54โ€“59
LineCodeWhat it does
54
def breakup():
๐Ÿงฉ Function DEFINES a function breakup(). Python only remembers it here - its body runs later, each time breakup() is called.
55
total = sum(usage)
๐Ÿงฎ Store / Calculate Adds up all the values in usage; the result is stored in variable total
56
print(f"{'Activity':<20}{'Share':>6}{'Litres':>9}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Activity':<20}{'Share':>6}{'Litres':>9}" with the values filled into { } on the screen
57
for i in range(len(acts)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(acts) - 1; for each number, i takes that value and the indented block runs once
58
lit = total * share[i] / 100
๐Ÿงฎ Store / Calculate Stores the value of total * share[i] / 100 (calculated using รท) in variable lit
59
print(f"{acts[i]:<20}{share[i]:>5}%{lit:>9.0f}  " + "*" * (share[i] // 2))
๐Ÿ–ฅ๏ธ Output Displays the value of f"{acts[i]:<20}{share[i]:>5}%{lit:>9.0f} " + โ€ฆ on the screen
spikes() - lines 62โ€“70
LineCodeWhat it does
62
def spikes():
๐Ÿงฉ Function DEFINES a function spikes(). Python only remembers it here - its body runs later, each time spikes() is called.
63
avg = sum(usage) / 7
๐Ÿงฎ Store / Calculate Stores the value of sum(usage) / 7 (calculated using รท) in variable avg
64
found = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable found
65
for i in range(7):
๐Ÿ” Loop LOOP: gives the numbers 0 to 6 (7 numbers); for each number, i takes that value and the indented block runs once
66
if usage[i] > 1.15 * avg:
๐Ÿ”€ Decision CHECKS whether usage[i] is greater than 1.15 * avg. If True, the indented lines below run; otherwise they are skipped
67
print(f"ALERT: {days[i]} used {usage[i]:.0f} L (average {avg:.0f} L) - check for leaks / wastage")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"ALERT: {days[i]} used {usage[i]:.0f} L (aveโ€ฆ with the values filled into { } on the screen
68
found += 1
๐Ÿงฎ Store / Calculate Adds 1 to found (same as found = found + 1)
69
if found == 0:
๐Ÿ”€ Decision CHECKS whether found is equal to 0. If True, the indented lines below run; otherwise they are skipped
70
print("No unusual spike found. Usage is steady.")
๐Ÿ–ฅ๏ธ Output Displays the text "No unusual spike found. Usage is โ€ฆ" on the screen
planner() - lines 73โ€“80
LineCodeWhat it does
73
def planner():
๐Ÿงฉ Function DEFINES a function planner(). Python only remembers it here - its body runs later, each time planner() is called.
74
pct = float(input("Target reduction (%): "))
โŒจ๏ธ Input Shows "Target reduction (%): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable pct
75
week = sum(usage)
๐Ÿงฎ Store / Calculate Adds up all the values in usage; the result is stored in variable week
76
saved = week * pct / 100
๐Ÿงฎ Store / Calculate Stores the value of week * pct / 100 (calculated using รท) in variable saved
77
print("Litres saved per week :", round(saved, 1))
๐Ÿ–ฅ๏ธ Output Displays the text "Litres saved per week :", then the value of round(saved, 1) on the screen
78
print("Litres saved per year :", round(saved * 52))
๐Ÿ–ฅ๏ธ Output Displays the text "Litres saved per year :", then the value of round(saved * 52) on the screen
79
print("Money saved per year  : Rs.", round(saved * 52 * RATE, 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Money saved per year : Rs.", then the value of round(saved * 52 * RATE, 2) on the screen
80
print("That is enough drinking water for", round(saved * 52 / (3 * 365), 1), "people for a year!")
๐Ÿ–ฅ๏ธ Output Displays the text "That is enough drinking water for", then the value of round(saved * 52 / (3 * 365), 1), then the text "people for a year!" on the screen
tips() - lines 83โ€“87
LineCodeWhat it does
83
def tips():
๐Ÿงฉ Function DEFINES a function tips(). Python only remembers it here - its body runs later, each time tips() is called.
84
big = share.index(max(share))
๐Ÿงฎ Store / Calculate Gives the position of max(share) in share; the result is stored in variable big
85
print("Largest use:", acts[big])
๐Ÿ–ฅ๏ธ Output Displays the text "Largest use:", then the value of acts[big] on the screen
86
print("Tips: 1) Use a bucket instead of a shower  2) Fix leaking taps (a drip wastes ~30 L/day)")
๐Ÿ–ฅ๏ธ Output Displays the text "Tips: 1) Use a bucket instead of โ€ฆ" on the screen
87
print("      3) Reuse RO waste water for mopping   4) Run washing machine on full load")
๐Ÿ–ฅ๏ธ Output Displays the text "3) Reuse RO waste water for moppiโ€ฆ" on the screen
Q1. Which SDG does the project support?

SDG 6 - Clean Water and Sanitation, by helping families reduce water wastage.

Q2. How is the average calculated?

sum(usage) / len(usage) - total litres divided by 7 days.

Q3. How is the highest usage day found?

max(usage) gives the value; usage.index(max(usage)) gives its position to pick the day name from days.

Q4. What is the spike rule?

If a day's use is more than 1.15 x average, it is flagged as a possible leak or wastage.

Q5. Is this AI?

It is a rule-based system - the first step towards AI; a learning model could learn the family's normal pattern from data.

02

Home Electricity Saver (SDG 7)

PYTHONSDG 7 - Affordable and Clean Energylistswhile looparithmetic expressionsif-elseformatted output
๐Ÿ“ 125 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 90 output lines๐Ÿ“„ 25+ page report

Takes the wattage and daily usage hours of home appliances, calculates monthly units (kWh) and the bill, identifies the appliance that consumes the most energy and estimates savings if its use is reduced by one hour a day.

โœจ Features
  • Any number of appliances with power (W) and daily hours stored in lists
  • Monthly units (kWh) and cost for each appliance with slab-wise tariff
  • Highest consumer and its share of the bill
  • What-if analysis: reduce hours or replace with a 5-star / LED appliance
  • Carbon footprint: kg CO2 per month (0.82 kg per unit)
  • Text bar chart of units
โ˜ฐ Main menu
1Add ApplianceName, watts, hours per day
2Show Bill TableUnits and cost per appliance
3Slab BillSlab-wise bill calculation
4Highest ConsumerShare of the bill
5What-if: Fewer HoursSaving if used less
6What-if: ReplaceSaving with efficient appliance
7Carbon Footprintkg CO2 and trees needed
0ExitEnds program
๐ŸŽฏ Objectives
  • Apply the formula units = watts x hours x days / 1000
  • Find the highest energy-consuming appliance using lists
  • Estimate money saved by reducing usage (what-if analysis)
๐Ÿ“š Data dictionary
NameTypePurpose
names, watts_list, hours_listlistsAppliance details
units()functionwatts x hours x 30 / 1000
SLABSlistUnits limit and rate per slab
CO2float0.82 kg CO2 per kWh
Why it matters: Shows how simple data analysis can guide energy-saving decisions at home.
# =====================================================================
#   HOME ELECTRICITY SAVER   (SDG 7 : Affordable and Clean Energy)
#   Concepts: lists, functions, loops, if-elif, what-if analysis
# =====================================================================
names, watts_list, hours_list = [], [], []
SLABS = [(200, 3.0), (200, 4.5), (400, 6.5), (100000, 7.0)]   # (units in slab, rate)
CO2 = 0.82


def units(i):
    return watts_list[i] * hours_list[i] * 30 / 1000


def add():
    name = input("Appliance name : ")
    w = float(input("Power (watts)  : "))
    h = float(input("Hours per day  : "))
    if w <= 0 or not 0 <= h <= 24:
        print("Hours must be 0-24 and watts positive. Not added.")
        return
    names.append(name); watts_list.append(w); hours_list.append(h)
    print(name, "added ->", round(w * h * 30 / 1000, 1), "units per month")


def total_units():
    return sum(units(i) for i in range(len(names)))


def slab_bill(u):
    bill, left = 0, u
    for size, rate in SLABS:
        part = min(left, size)
        bill += part * rate
        left -= part
        if left <= 0:
            break
    return bill


def table():
    tu = total_units()
    avg_rate = slab_bill(tu) / tu
    print("{:<14}{:>7}{:>7}{:>10}{:>11}  Chart".format("Appliance", "Watts", "Hrs", "Units/mo", "Cost(Rs.)"))
    print("-" * 60)
    for i in range(len(names)):
        print("{:<14}{:>7.0f}{:>7.1f}{:>10.1f}{:>11.2f}  {}".format(names[i], watts_list[i], hours_list[i], units(i), units(i) * avg_rate, "#" * int(units(i) // 10)))
    print("-" * 60)
    print("{:<28}{:>10.1f}{:>11.2f}".format("TOTAL", tu, slab_bill(tu)))


def show_slabs():
    left, tu, start = total_units(), total_units(), 0
    print("Total units:", round(tu, 1))
    for size, rate in SLABS:
        part = min(left, size)
        if part <= 0:
            break
        print(f"  Units {start + 1:>4} - {start + part:>6.1f} @ Rs. {rate} = Rs. {part * rate:.2f}")
        left -= part; start += size
    print("Bill amount: Rs.", round(slab_bill(tu), 2))


def highest():
    u = [units(i) for i in range(len(names))]
    top = u.index(max(u))
    print("Highest consumer:", names[top], "-", round(u[top] / sum(u) * 100, 1), "% of units")


def fewer_hours():
    n = input("Appliance: ")
    cut = float(input("Reduce by hours/day: "))
    if n not in names:
        print("Not found."); return
    i = names.index(n)
    saved_u = watts_list[i] * cut * 30 / 1000
    tu = total_units()
    saved_rs = slab_bill(tu) - slab_bill(tu - saved_u)
    print(f"Units saved per month: {saved_u:.1f}  |  Money saved: Rs. {saved_rs:.2f}/month, Rs. {saved_rs * 12:.2f}/year")


def replace():
    n = input("Appliance: ")
    pct = float(input("New appliance uses what % less power? "))
    if n not in names:
        print("Not found."); return
    i = names.index(n)
    saved_u = units(i) * pct / 100
    tu = total_units()
    print(f"{n}: {units(i):.1f} -> {units(i) - saved_u:.1f} units; saving Rs. {slab_bill(tu) - slab_bill(tu - saved_u):.2f} per month")


def carbon():
    kg = total_units() * CO2
    print(f"Monthly CO2: {kg:.1f} kg  |  Yearly: {kg * 12 / 1000:.2f} tonnes")
    print(f"Trees needed to absorb it: about {round(kg * 12 / 21)} (a tree absorbs ~21 kg CO2/year)")


print("=" * 52)
print("   HOME ELECTRICITY SAVER  (SDG 7)")
print("=" * 52)
while True:
    print("\n1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Save energy, save money!")
        break
    elif ch == "1":
        add()
    elif ch in "234567" and len(names) == 0:
        print("Add appliances first.")
    elif ch == "2":
        table()
    elif ch == "3":
        show_slabs()
    elif ch == "4":
        highest()
    elif ch == "5":
        fewer_hours()
    elif ch == "6":
        replace()
    elif ch == "7":
        carbon()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Add? → No: run selected report
  4. Read name, watts, hours
  5. Valid values? → No: show error
  6. Append to lists
  7. Show bill / saving
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Add Fan 75 W 10 h22.5 units/monthPASS
2Hours 30'Hours must be 0-24'PASS
3Bill tableRows for 5 appliancesPASS
4Slab billSlab-wise amountsPASS
5Highest consumerACPASS
6Reduce AC by 2 hUnits and Rs. savedPASS
7Replace 'LED Bulbs' with 30 % powerSaving shownPASS
8Carbonkg CO2 and treesPASS
โš  Limitations
  • Assumes 30 days and fixed daily hours
  • Tariff slabs are sample values
  • Standby power ignored
  • Manual entry
๐Ÿš€ Future scope
  • Read smart-meter data
  • Solar panel payback calculator
  • Store monthly bills to compare
  • Voice assistant tips

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: SLABS, CO2.
  2. 10 functions are defined (lines 10โ€“95) - Python stores them but does NOT run them yet.
  3. Main program starts at line 5: names, watts_list, hours_list = [], [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
units(i)10โ€“11Unitstotal_units(), table(), highest(), replace()
add()14โ€“22Addmain program
total_units()25โ€“26Total unitstable(), show_slabs(), fewer_hours(), replace()
slab_bill(u)29โ€“37Slab billtable(), show_slabs(), fewer_hours(), replace()
table()40โ€“48Tablemain program
show_slabs()51โ€“60Show slabsmain program
highest()63โ€“66Highestmain program
fewer_hours()69โ€“78Fewer hoursmain program
replace()81โ€“89Replacemain program
carbon()92โ€“95Carbonmain program
โ‘ข Main program - line by line
LineCodeWhat it does
5
names, watts_list, hours_list = [], [], []
๐Ÿงฎ Store / Calculate Stores [], [], [] into names, watts_list, hours_list respectively
6
SLABS = [(200, 3.0), (200, 4.5), (400, 6.5), (100000, 7.0)]   # (units in slab, rate)
๐Ÿงฎ Store / Calculate Stores a list [(200, 3.0), (200, 4.5), (400, 6.5), (100000,โ€ฆ in variable SLABS
7
CO2 = 0.82
๐Ÿงฎ Store / Calculate Stores the number 0.82 in variable CO2
98
print("=" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "=" signs on the screen
99
print("   HOME ELECTRICITY SAVER  (SDG 7)")
๐Ÿ–ฅ๏ธ Output Displays the text "HOME ELECTRICITY SAVER (SDG 7)" on the screen
100
print("=" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "=" signs on the screen
101
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
102
print("\n1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add 2.Bill Table 3.Slab Bill 4.โ€ฆ" on the screen
103
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
104
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
105
print("Save energy, save money!")
๐Ÿ–ฅ๏ธ Output Displays the text "Save energy, save money!" on the screen
106
break
๐Ÿ” Loop BREAK - leaves the loop immediately
107
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
108
add()
๐Ÿงฎ Store / Calculate Calls our own function add()
109
elif ch in "234567" and len(names) == 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (ch is present in "234567" AND len(names) is equal to 0)
110
print("Add appliances first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Add appliances first." on the screen
111
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
112
table()
๐Ÿงฎ Store / Calculate Calls our own function table()
113
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
114
show_slabs()
๐Ÿงฎ Store / Calculate Calls our own function show_slabs()
115
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
116
highest()
๐Ÿงฎ Store / Calculate Calls our own function highest()
117
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
118
fewer_hours()
๐Ÿงฎ Store / Calculate Calls our own function fewer_hours()
119
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
120
replace()
๐Ÿงฎ Store / Calculate Calls our own function replace()
121
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
122
carbon()
๐Ÿงฎ Store / Calculate Calls our own function carbon()
123
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
124
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HOME ELECTRICITY SAVER (SDG 7) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: add()
  3. You type Fan at Appliance name :
  4. You type 75 at Power (watts) :
  5. You type 10 at Hours per day :
    shows: Fan added -> 22.5 units per month (+1 more lines)
  6. You type 1 at Enter choice:
    runs: add()
  7. You type LED Bulbs at Appliance name :
  8. You type 40 at Power (watts) :
  9. You type 6 at Hours per day :
    shows: LED Bulbs added -> 7.2 units per month (+1 more lines)
  10. You type 1 at Enter choice:
    runs: add()
  11. You type Refrigerator at Appliance name :
  12. You type 150 at Power (watts) :
  13. You type 24 at Hours per day :
    shows: Refrigerator added -> 108.0 units per month (+1 more lines)
  14. You type 1 at Enter choice:
    runs: add()
  15. You type AC at Appliance name :
  16. You type 1500 at Power (watts) :
  17. You type 6 at Hours per day :
    shows: AC added -> 270.0 units per month (+1 more lines)
  18. You type 1 at Enter choice:
    runs: add()
  19. You type TV at Appliance name :
  20. You type 100 at Power (watts) :
  21. You type 30 at Hours per day :
    shows: Hours must be 0-24 and watts positive. Not added. (+1 more lines)
  22. You type 1 at Enter choice:
    runs: add()
  23. You type TV at Appliance name :
  24. You type 100 at Power (watts) :
  25. You type 4 at Hours per day :
    shows: TV added -> 12.0 units per month (+1 more lines)
  26. You type 2 at Enter choice:
    runs: table() โ†’ total_units() โ†’ units() ร—5 โ†’ slab_bill() โ†’ units() ร—15 โ†’ slab_bill()
    shows: Appliance Watts Hrs Units/mo Cost(Rs.) Chart (+7 more lines)
  27. You type 3 at Enter choice:
    runs: show_slabs() โ†’ total_units() โ†’ units() ร—5 โ†’ total_units() โ†’ units() ร—5 โ†’ slab_bill()
    shows: Total units: 419.7 (+5 more lines)
  28. You type 4 at Enter choice:
    runs: highest() โ†’ units() ร—5
    shows: Highest consumer: AC - 64.3 % of units (+1 more lines)
  29. You type 5 at Enter choice:
    runs: fewer_hours()
  30. You type AC at Appliance:
  31. You type 2 at Reduce by hours/day:
    runs: total_units() โ†’ units() ร—5 โ†’ slab_bill() ร—2
    shows: Units saved per month: 90.0 | Money saved: Rs. 444.40/month, Rs. 5332.80/year (+1 more lines)
  32. You type 6 at Enter choice:
    runs: replace()
  33. You type LED Bulbs at Appliance:
  34. You type 30 at New appliance uses what % less power?
    runs: units() โ†’ total_units() โ†’ units() ร—7 โ†’ slab_bill() ร—2
    shows: LED Bulbs: 7.2 -> 5.0 units; saving Rs. 14.04 per month (+1 more lines)
  35. You type 7 at Enter choice:
    runs: carbon() โ†’ total_units() โ†’ units() ร—5
    shows: Monthly CO2: 344.2 kg | Yearly: 4.13 tonnes (+2 more lines)
  36. You type 0 at Enter choice:
    shows: Save energy, save money!
โ‘ค Inside each function - line by line
units() - lines 10โ€“11
LineCodeWhat it does
10
def units(i):
๐Ÿงฉ Function DEFINES a function units(i). Python only remembers it here - its body runs later, each time units() is called.
11
return watts_list[i] * hours_list[i] * 30 / 1000
๐Ÿงฉ Function Sends back (returns) the value of watts_list[i] * hours_list[i] * 30 / 1000 (calculated using รท) to the line that called the function
add() - lines 14โ€“22
LineCodeWhat it does
14
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
15
name = input("Appliance name : ")
โŒจ๏ธ Input Shows the message "Appliance name : " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
16
w = float(input("Power (watts)  : "))
โŒจ๏ธ Input Shows "Power (watts) : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable w
17
h = float(input("Hours per day  : "))
โŒจ๏ธ Input Shows "Hours per day : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable h
18
if w <= 0 or not 0 <= h <= 24:
๐Ÿ”€ Decision CHECKS whether (w is less than or equal to 0 OR NOT 0 <= h <= 24 is True). If True, the indented lines below run; otherwise they are skipped
19
print("Hours must be 0-24 and watts positive. Not added.")
๐Ÿ–ฅ๏ธ Output Displays the text "Hours must be 0-24 and watts posiโ€ฆ" on the screen
20
return
๐Ÿงฉ Function Ends the function and goes back to the caller
21
names.append(name); watts_list.append(w); hours_list.append(h)
๐Ÿงฎ Store / Calculate Adds name at the end of list names
21
names.append(name); watts_list.append(w); hours_list.append(h)
๐Ÿงฎ Store / Calculate Adds w at the end of list watts_list
21
names.append(name); watts_list.append(w); hours_list.append(h)
๐Ÿงฎ Store / Calculate Adds h at the end of list hours_list
22
print(name, "added ->", round(w * h * 30 / 1000, 1), "units per month")
๐Ÿ–ฅ๏ธ Output Displays the value of name, then the text "added ->", then the value of round(w * h * 30 / 1000, 1), then the text "units per month" on the screen
total_units() - lines 25โ€“26
LineCodeWhat it does
25
def total_units():
๐Ÿงฉ Function DEFINES a function total_units(). Python only remembers it here - its body runs later, each time total_units() is called.
26
return sum(units(i) for i in range(len(names)))
๐Ÿงฉ Function Sends back (returns) the result of: adds up all the values in (units(i) for i in range(len(names))) to the line that called the function
slab_bill() - lines 29โ€“37
LineCodeWhat it does
29
def slab_bill(u):
๐Ÿงฉ Function DEFINES a function slab_bill(u). Python only remembers it here - its body runs later, each time slab_bill() is called.
30
bill, left = 0, u
๐Ÿงฎ Store / Calculate Stores 0, u into bill, left respectively
31
for size, rate in SLABS:
๐Ÿ” Loop LOOP: takes each item of SLABS one-by-one into size, rate and runs the indented block for it
32
part = min(left, size)
๐Ÿงฎ Store / Calculate Finds the smallest value among left, size; the result is stored in variable part
33
bill += part * rate
๐Ÿงฎ Store / Calculate Adds part * rate to bill (same as bill = bill + part * rate)
34
left -= part
๐Ÿงฎ Store / Calculate Subtracts part from left (same as left = left - part)
35
if left <= 0:
๐Ÿ”€ Decision CHECKS whether left is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
36
break
๐Ÿ” Loop BREAK - leaves the loop immediately
37
return bill
๐Ÿงฉ Function Sends back (returns) the value of bill to the line that called the function
table() - lines 40โ€“48
LineCodeWhat it does
40
def table():
๐Ÿงฉ Function DEFINES a function table(). Python only remembers it here - its body runs later, each time table() is called.
41
tu = total_units()
๐Ÿงฎ Store / Calculate Calls our own function total_units(); the result is stored in variable tu
42
avg_rate = slab_bill(tu) / tu
๐Ÿงฎ Store / Calculate Stores the value of slab_bill(tu) / tu (calculated using รท) in variable avg_rate
43
print("{:<14}{:>7}{:>7}{:>10}{:>11}  Chart".format("Appliance", "Watts", "Hrs", "Units/mo", "Cost(Rs.)"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<14}{:>7}{:>7}{:>10}{:>11} Chart".format("โ€ฆ on the screen
44
print("-" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "-" signs on the screen
45
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
46
print("{:<14}{:>7.0f}{:>7.1f}{:>10.1f}{:>11.2f}  {}".format(names[i], watts_list[i], hours_list[i], units(i), units(i) * avg_rate, "#" * int(units(i) // 10)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<14}{:>7.0f}{:>7.1f}{:>10.1f}{:>11.2f} {}"โ€ฆ on the screen
47
print("-" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "-" signs on the screen
48
print("{:<28}{:>10.1f}{:>11.2f}".format("TOTAL", tu, slab_bill(tu)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<28}{:>10.1f}{:>11.2f}".format("TOTAL", tuโ€ฆ on the screen
show_slabs() - lines 51โ€“60
LineCodeWhat it does
51
def show_slabs():
๐Ÿงฉ Function DEFINES a function show_slabs(). Python only remembers it here - its body runs later, each time show_slabs() is called.
52
left, tu, start = total_units(), total_units(), 0
๐Ÿงฎ Store / Calculate Stores total_units(), total_units(), 0 into left, tu, start respectively
53
print("Total units:", round(tu, 1))
๐Ÿ–ฅ๏ธ Output Displays the text "Total units:", then the value of round(tu, 1) on the screen
54
for size, rate in SLABS:
๐Ÿ” Loop LOOP: takes each item of SLABS one-by-one into size, rate and runs the indented block for it
55
part = min(left, size)
๐Ÿงฎ Store / Calculate Finds the smallest value among left, size; the result is stored in variable part
56
if part <= 0:
๐Ÿ”€ Decision CHECKS whether part is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
57
break
๐Ÿ” Loop BREAK - leaves the loop immediately
58
print(f"  Units {start + 1:>4} - {start + part:>6.1f} @ Rs. {rate} = Rs. {part * rate:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Units {start + 1:>4} - {start + part:>6.1fโ€ฆ with the values filled into { } on the screen
59
left -= part; start += size
๐Ÿงฎ Store / Calculate Subtracts part from left (same as left = left - part)
59
left -= part; start += size
๐Ÿงฎ Store / Calculate Adds size to start (same as start = start + size)
60
print("Bill amount: Rs.", round(slab_bill(tu), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Bill amount: Rs.", then the value of round(slab_bill(tu), 2) on the screen
highest() - lines 63โ€“66
LineCodeWhat it does
63
def highest():
๐Ÿงฉ Function DEFINES a function highest(). Python only remembers it here - its body runs later, each time highest() is called.
64
u = [units(i) for i in range(len(names))]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [units(i) for i in range(len(names))] in variable u
65
top = u.index(max(u))
๐Ÿงฎ Store / Calculate Gives the position of max(u) in u; the result is stored in variable top
66
print("Highest consumer:", names[top], "-", round(u[top] / sum(u) * 100, 1), "% of units")
๐Ÿ–ฅ๏ธ Output Displays the text "Highest consumer:", then the value of names[top], then the text "-", then the value of round(u[top] / sum(u) * 100, 1), then the text "% of units" on the screen
fewer_hours() - lines 69โ€“78
LineCodeWhat it does
69
def fewer_hours():
๐Ÿงฉ Function DEFINES a function fewer_hours(). Python only remembers it here - its body runs later, each time fewer_hours() is called.
70
n = input("Appliance: ")
โŒจ๏ธ Input Shows the message "Appliance: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable n
71
cut = float(input("Reduce by hours/day: "))
โŒจ๏ธ Input Shows "Reduce by hours/day: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable cut
72
if n not in names:
๐Ÿ”€ Decision CHECKS whether n is not present in names. If True, the indented lines below run; otherwise they are skipped
73
print("Not found."); return
๐Ÿ–ฅ๏ธ Output Displays the text "Not found." on the screen
73
print("Not found."); return
๐Ÿ–ฅ๏ธ Output Ends the function and goes back to the caller
74
i = names.index(n)
๐Ÿงฎ Store / Calculate Gives the position of n in names; the result is stored in variable i
75
saved_u = watts_list[i] * cut * 30 / 1000
๐Ÿงฎ Store / Calculate Stores the value of watts_list[i] * cut * 30 / 1000 (calculated using รท) in variable saved_u
76
tu = total_units()
๐Ÿงฎ Store / Calculate Calls our own function total_units(); the result is stored in variable tu
77
saved_rs = slab_bill(tu) - slab_bill(tu - saved_u)
๐Ÿงฎ Store / Calculate Stores the value of slab_bill(tu) - slab_bill(tu - saved_u) (calculated using -) in variable saved_rs
78
print(f"Units saved per month: {saved_u:.1f}  |  Money saved: Rs. {saved_rs:.2f}/month, Rs. {saved_rs * 12:.2f}/year")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Units saved per month: {saved_u:.1f} | Moneโ€ฆ with the values filled into { } on the screen
replace() - lines 81โ€“89
LineCodeWhat it does
81
def replace():
๐Ÿงฉ Function DEFINES a function replace(). Python only remembers it here - its body runs later, each time replace() is called.
82
n = input("Appliance: ")
โŒจ๏ธ Input Shows the message "Appliance: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable n
83
pct = float(input("New appliance uses what % less power? "))
โŒจ๏ธ Input Shows "New appliance uses what % less power? ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable pct
84
if n not in names:
๐Ÿ”€ Decision CHECKS whether n is not present in names. If True, the indented lines below run; otherwise they are skipped
85
print("Not found."); return
๐Ÿ–ฅ๏ธ Output Displays the text "Not found." on the screen
85
print("Not found."); return
๐Ÿ–ฅ๏ธ Output Ends the function and goes back to the caller
86
i = names.index(n)
๐Ÿงฎ Store / Calculate Gives the position of n in names; the result is stored in variable i
87
saved_u = units(i) * pct / 100
๐Ÿงฎ Store / Calculate Stores the value of units(i) * pct / 100 (calculated using รท) in variable saved_u
88
tu = total_units()
๐Ÿงฎ Store / Calculate Calls our own function total_units(); the result is stored in variable tu
89
print(f"{n}: {units(i):.1f} -> {units(i) - saved_u:.1f} units; saving Rs. {slab_bill(tu) - slab_bill(tu - saved_u):.2f} per month")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n}: {units(i):.1f} -> {units(i) - saved_u:โ€ฆ with the values filled into { } on the screen
carbon() - lines 92โ€“95
LineCodeWhat it does
92
def carbon():
๐Ÿงฉ Function DEFINES a function carbon(). Python only remembers it here - its body runs later, each time carbon() is called.
93
kg = total_units() * CO2
๐Ÿงฎ Store / Calculate Stores the value of total_units() * CO2 (calculated using ร—) in variable kg
94
print(f"Monthly CO2: {kg:.1f} kg  |  Yearly: {kg * 12 / 1000:.2f} tonnes")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Monthly CO2: {kg:.1f} kg | Yearly: {kg * 12โ€ฆ with the values filled into { } on the screen
95
print(f"Trees needed to absorb it: about {round(kg * 12 / 21)} (a tree absorbs ~21 kg CO2/year)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Trees needed to absorb it: about {round(kg โ€ฆ with the values filled into { } on the screen
Q1. What is a unit of electricity?

1 kWh = 1000 watts used for 1 hour.

Q2. Formula for monthly units?

watts x hours per day x 30 / 1000.

Q3. What is slab-wise billing?

Different rates for different ranges of units, e.g. first 200 units cheaper than the next 200.

Q4. How is carbon footprint estimated?

Units x emission factor (about 0.82 kg CO2 per unit from coal-based power).

Q5. Which SDG is addressed?

SDG 7 - Affordable and Clean Energy, and SDG 13 Climate Action.

03

Car Spotting and Tabulating - Probability Analyser

PYTHONSDG 11 - Sustainable Cities and Communitieslistscount()dictionaries-free tabulationprobabilityfor loop
๐Ÿ“ 110 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 90 output lines๐Ÿ“„ 25+ page report

Based on the CBSE 'Car Spotting and Tabulating' activity: the colours/types of vehicles passing the school gate are entered, the program tabulates the frequency, finds the mode, calculates the probability of each colour and prints a text bar chart.

โœจ Features
  • Car colours observed at the school gate entered as comma-separated text
  • Frequency table with probability and percentage of each colour
  • Mode, least common colour, P(colour) and P(not colour)
  • Probability of two events: P(A or B) for two colours
  • Simulation: next 20 cars predicted using random.choices with observed probabilities
  • Compare two survey sessions (morning vs evening)
โ˜ฐ Main menu
1Enter ObservationsComma separated car colours
2Frequency TableCount, probability, %, bar
3Mode & LeastMost / least common colour
4Probability QueryP(colour) and P(not colour)
5P(A or B)Addition rule for two colours
6Simulate Next Carsrandom.choices with weights
7Add Evening SurveySecond session and comparison
0ExitEnds program
๐ŸŽฏ Objectives
  • Collect and tabulate real-world data using lists
  • Find frequency, mode and probability of each category
  • Interpret the data with a text-based bar chart
๐Ÿ“š Data dictionary
NameTypePurpose
carslistObserved colours (title case)
colourslistUnique colours in order
countslistCount of each colour
eveninglistSecond survey
Why it matters: Connects statistics and probability with real data collected by students - the foundation of how AI makes predictions.
# =====================================================================
#   CAR SPOTTING AND TABULATING - PROBABILITY ANALYSER
#   Concepts: string split, lists, count(), functions, random module
# =====================================================================
import random

cars = []


def to_list(text):
    return [c.strip().title() for c in text.split(",") if c.strip()]


def unique(lst):
    out = []
    for c in lst:
        if c not in out:
            out.append(c)
    return out


def enter():
    cars.clear()
    cars.extend(to_list(input("Enter car colours seen (comma separated):\n")))
    print("Total cars observed:", len(cars))


def table(data):
    total = len(data)
    print("{:<8}{:>6}{:>13}{:>7}  Bar".format("Colour", "Count", "Probability", "%"))
    print("-" * 52)
    for c in sorted(unique(data), key=lambda x: -data.count(x)):
        n = data.count(c)
        print("{:<8}{:>6}{:>13.3f}{:>6.1f}%  {}".format(c, n, n / total, n / total * 100, "*" * n))
    print("-" * 52)
    print("Sum of all probabilities = 1.0 (always)")


def mode_least():
    cols = unique(cars)
    cnt = [cars.count(c) for c in cols]
    print("Mode (most common) :", cols[cnt.index(max(cnt))], "-", max(cnt), "cars")
    print("Least common       :", [c for c in cols if cars.count(c) == min(cnt)])


def p(colour):
    return cars.count(colour.title()) / len(cars)


def query():
    c = input("Colour: ").strip()
    pc = p(c)
    print(f"P({c.title()}) = {cars.count(c.title())}/{len(cars)} = {pc:.3f}")
    print(f"P(not {c.title()}) = 1 - {pc:.3f} = {1 - pc:.3f}")
    if pc == 0:
        print("This is an IMPOSSIBLE event in our data.")


def p_or():
    a, b = input("Colour A: ").strip(), input("Colour B: ").strip()
    print(f"P({a.title()} or {b.title()}) = {p(a):.3f} + {p(b):.3f} = {p(a) + p(b):.3f}")


def simulate():
    n = int(input("How many next cars to simulate? "))
    cols = unique(cars)
    weights = [cars.count(c) for c in cols]
    nxt = random.choices(cols, weights=weights, k=n)
    print("Simulated:", ", ".join(nxt))
    for c in cols:
        print(f"  {c:<7} expected {p(c) * n:4.1f}  simulated {nxt.count(c)}")


def evening():
    ev = to_list(input("Evening colours (comma separated):\n"))
    print("\nEVENING SURVEY")
    table(ev)
    print("\n{:<8}{:>10}{:>10}".format("Colour", "Morning", "Evening"))
    for c in unique(cars + ev):
        print("{:<8}{:>10.2f}{:>10.2f}".format(c, cars.count(c) / len(cars), ev.count(c) / len(ev)))


print("=" * 52)
print("   CAR SPOTTING & TABULATING - PROBABILITY")
print("=" * 52)
while True:
    print("\n1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        enter()
    elif len(cars) == 0:
        print("Enter observations first (option 1).")
    elif ch == "2":
        table(cars)
    elif ch == "3":
        mode_least()
    elif ch == "4":
        query()
    elif ch == "5":
        p_or()
    elif ch == "6":
        simulate()
    elif ch == "7":
        evening()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Observations entered? → No: ask to enter
  4. Count each colour and divide by total
  5. Show table / probability
  6. Choice is 0? → No: show menu
  7. Stop
#Test case / inputExpected resultStatus
130 coloursTotal 30PASS
2Frequency tableWhite 11 -> 0.367PASS
3ModeWhitePASS
4P(Red)0.133PASS
5P(Purple)0 (impossible event)PASS
6P(White or Silver)0.567PASS
7Simulate 20Predicted countsPASS
8Evening surveyComparison tablePASS
โš  Limitations
  • Small sample - probabilities change with more data
  • Colour names must be typed consistently
  • No time of day recorded per car
  • Simulation is random
๐Ÿš€ Future scope
  • Count cars automatically with a camera (computer vision)
  • Store surveys in CSV
  • Chart with matplotlib
  • Predict traffic by hour

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 5): random - random number functions are loaded.
  2. Global variables / constants are created: cars.
  3. 10 functions are defined (lines 10โ€“80) - Python stores them but does NOT run them yet.
  4. Main program starts at line 83: print("=" * 52) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
to_list(text)10โ€“11To listenter(), evening()
unique(lst)14โ€“19Uniquetable(), mode_least(), simulate(), evening()
enter()22โ€“25Entermain program
table(data)28โ€“36Tableevening(), main program
mode_least()39โ€“43Mode leastmain program
p(colour)46โ€“47Pquery(), p_or(), simulate()
query()50โ€“56Querymain program
p_or()59โ€“61P ormain program
simulate()64โ€“71Simulatemain program
evening()74โ€“80Eveningmain program
โ‘ข Main program - line by line
LineCodeWhat it does
83
print("=" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "=" signs on the screen
84
print("   CAR SPOTTING & TABULATING - PROBABILITY")
๐Ÿ–ฅ๏ธ Output Displays the text "CAR SPOTTING & TABULATING - PROBAโ€ฆ" on the screen
85
print("=" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "=" signs on the screen
86
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
87
print("\n1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Enter 2.Table 3.Mode 4.P(colourโ€ฆ" on the screen
88
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
89
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
90
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
91
break
๐Ÿ” Loop BREAK - leaves the loop immediately
92
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
93
enter()
๐Ÿงฎ Store / Calculate Calls our own function enter()
94
elif len(cars) == 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether len(cars) is equal to 0
95
print("Enter observations first (option 1).")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter observations first (option โ€ฆ" on the screen
96
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
97
table(cars)
๐Ÿงฎ Store / Calculate Calls our own function table(cars)
98
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
99
mode_least()
๐Ÿงฎ Store / Calculate Calls our own function mode_least()
100
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
101
query()
๐Ÿงฎ Store / Calculate Calls our own function query()
102
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
103
p_or()
๐Ÿงฎ Store / Calculate Calls our own function p_or()
104
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
105
simulate()
๐Ÿงฎ Store / Calculate Calls our own function simulate()
106
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
107
evening()
๐Ÿงฎ Store / Calculate Calls our own function evening()
108
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
109
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CAR SPOTTING & TABULATING - PROBABILITY (+1 more lines)
  2. You type 2 at Enter choice:
    shows: Enter observations first (option 1). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: enter()
  4. You type white, silver, black, white, red, white, blue, silver, white, black, white, red, silver, white, grey, white, black, silver, white, blue, red, white, silver, black, white, grey, silver, white, red, blue at Enter car colours seen (comma separated):
    runs: to_list()
    shows: Total cars observed: 30 (+1 more lines)
  5. You type 2 at Enter choice:
    runs: table() โ†’ unique()
    shows: Colour Count Probability % Bar (+8 more lines)
  6. You type 3 at Enter choice:
    runs: mode_least() โ†’ unique()
    shows: Mode (most common) : White - 11 cars (+2 more lines)
  7. You type 4 at Enter choice:
    runs: query()
  8. You type red at Colour:
    runs: p()
    shows: P(Red) = 4/30 = 0.133 (+2 more lines)
  9. You type 4 at Enter choice:
    runs: query()
  10. You type purple at Colour:
    runs: p()
    shows: P(Purple) = 0/30 = 0.000 (+3 more lines)
  11. You type 5 at Enter choice:
    runs: p_or()
  12. You type white at Colour A:
  13. You type silver at Colour B:
    runs: p() ร—4
    shows: P(White or Silver) = 0.367 + 0.200 = 0.567 (+1 more lines)
  14. You type 6 at Enter choice:
    runs: simulate()
  15. You type 20 at How many next cars to simulate?
    runs: unique() โ†’ p() ร—6
    shows: Simulated: White, Silver, Silver, Blue, White, White, Black, Silver, Red, Silver, Red, Red (+7 more lines)
  16. You type 7 at Enter choice:
    runs: evening()
  17. You type black, white, black, silver, black, red, white, black, grey, black, white, silver, black, blue, white at Evening colours (comma separated):
    runs: to_list() โ†’ table() โ†’ unique() ร—2
    shows: EVENING SURVEY (+16 more lines)
  18. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
to_list() - lines 10โ€“11
LineCodeWhat it does
10
def to_list(text):
๐Ÿงฉ Function DEFINES a function to_list(text). Python only remembers it here - its body runs later, each time to_list() is called.
11
return [c.strip().title() for c in text.split(",") if c.strip()]
๐Ÿงฉ Function Sends back (returns) a new list made by a list comprehension [c.strip().title() for c in text.split(",") iโ€ฆ to the line that called the function
unique() - lines 14โ€“19
LineCodeWhat it does
14
def unique(lst):
๐Ÿงฉ Function DEFINES a function unique(lst). Python only remembers it here - its body runs later, each time unique() is called.
15
out = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable out
16
for c in lst:
๐Ÿ” Loop LOOP: takes each item of lst one-by-one into c and runs the indented block for it
17
if c not in out:
๐Ÿ”€ Decision CHECKS whether c is not present in out. If True, the indented lines below run; otherwise they are skipped
18
out.append(c)
๐Ÿงฎ Store / Calculate Adds c at the end of list out
19
return out
๐Ÿงฉ Function Sends back (returns) the value of out to the line that called the function
enter() - lines 22โ€“25
LineCodeWhat it does
22
def enter():
๐Ÿงฉ Function DEFINES a function enter(). Python only remembers it here - its body runs later, each time enter() is called.
23
cars.clear()
๐Ÿงฎ Store / Calculate Removes all items from cars
24
cars.extend(to_list(input("Enter car colours seen (comma separated):\n")))
โŒจ๏ธ Input Adds all items of to_list(input("Enter car colours seen (comma โ€ฆ at the end of cars
25
print("Total cars observed:", len(cars))
๐Ÿ–ฅ๏ธ Output Displays the text "Total cars observed:", then the value of len(cars) on the screen
table() - lines 28โ€“36
LineCodeWhat it does
28
def table(data):
๐Ÿงฉ Function DEFINES a function table(data). Python only remembers it here - its body runs later, each time table() is called.
29
total = len(data)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in data; the result is stored in variable total
30
print("{:<8}{:>6}{:>13}{:>7}  Bar".format("Colour", "Count", "Probability", "%"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>6}{:>13}{:>7} Bar".format("Colour", โ€ฆ on the screen
31
print("-" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "-" signs on the screen
32
for c in sorted(unique(data), key=lambda x: -data.count(x)):
๐Ÿ” Loop LOOP: takes each item of sorted(unique(data), key=lambda x: -data.counโ€ฆ one-by-one into c and runs the indented block for it
33
n = data.count(c)
๐Ÿงฎ Store / Calculate Counts how many times c occurs in data; the result is stored in variable n
34
print("{:<8}{:>6}{:>13.3f}{:>6.1f}%  {}".format(c, n, n / total, n / total * 100, "*" * n))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>6}{:>13.3f}{:>6.1f}% {}".format(c, nโ€ฆ on the screen
35
print("-" * 52)
๐Ÿ–ฅ๏ธ Output Displays a line of 52 "-" signs on the screen
36
print("Sum of all probabilities = 1.0 (always)")
๐Ÿ–ฅ๏ธ Output Displays the text "Sum of all probabilities = 1.0 (aโ€ฆ" on the screen
mode_least() - lines 39โ€“43
LineCodeWhat it does
39
def mode_least():
๐Ÿงฉ Function DEFINES a function mode_least(). Python only remembers it here - its body runs later, each time mode_least() is called.
40
cols = unique(cars)
๐Ÿงฎ Store / Calculate Calls our own function unique(cars); the result is stored in variable cols
41
cnt = [cars.count(c) for c in cols]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [cars.count(c) for c in cols] in variable cnt
42
print("Mode (most common) :", cols[cnt.index(max(cnt))], "-", max(cnt), "cars")
๐Ÿ–ฅ๏ธ Output Displays the text "Mode (most common) :", then the value of cols[cnt.index(max(cnt))], then the text "-", then the value of max(cnt), then the text "cars" on the screen
43
print("Least common       :", [c for c in cols if cars.count(c) == min(cnt)])
๐Ÿ–ฅ๏ธ Output Displays the text "Least common :", then the value of [c for c in cols if cars.count(c) == min(cnt)] on the screen
p() - lines 46โ€“47
LineCodeWhat it does
46
def p(colour):
๐Ÿงฉ Function DEFINES a function p(colour). Python only remembers it here - its body runs later, each time p() is called.
47
return cars.count(colour.title()) / len(cars)
๐Ÿงฉ Function Sends back (returns) the value of cars.count(colour.title()) / len(cars) (calculated using รท) to the line that called the function
query() - lines 50โ€“56
LineCodeWhat it does
50
def query():
๐Ÿงฉ Function DEFINES a function query(). Python only remembers it here - its body runs later, each time query() is called.
51
c = input("Colour: ").strip()
โŒจ๏ธ Input Shows "Colour: ", reads the typed text, removes extra spaces (strip) and stores it in variable c
52
pc = p(c)
๐Ÿงฎ Store / Calculate Calls our own function p(c); the result is stored in variable pc
53
print(f"P({c.title()}) = {cars.count(c.title())}/{len(cars)} = {pc:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"P({c.title()}) = {cars.count(c.title())}/{lโ€ฆ with the values filled into { } on the screen
54
print(f"P(not {c.title()}) = 1 - {pc:.3f} = {1 - pc:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"P(not {c.title()}) = 1 - {pc:.3f} = {1 - pcโ€ฆ with the values filled into { } on the screen
55
if pc == 0:
๐Ÿ”€ Decision CHECKS whether pc is equal to 0. If True, the indented lines below run; otherwise they are skipped
56
print("This is an IMPOSSIBLE event in our data.")
๐Ÿ–ฅ๏ธ Output Displays the text "This is an IMPOSSIBLE event in ouโ€ฆ" on the screen
p_or() - lines 59โ€“61
LineCodeWhat it does
59
def p_or():
๐Ÿงฉ Function DEFINES a function p_or(). Python only remembers it here - its body runs later, each time p_or() is called.
60
a, b = input("Colour A: ").strip(), input("Colour B: ").strip()
โŒจ๏ธ Input Stores input("Colour A: ").strip(), input("Colour B: ").strip() into a, b respectively
61
print(f"P({a.title()} or {b.title()}) = {p(a):.3f} + {p(b):.3f} = {p(a) + p(b):.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"P({a.title()} or {b.title()}) = {p(a):.3f} โ€ฆ with the values filled into { } on the screen
simulate() - lines 64โ€“71
LineCodeWhat it does
64
def simulate():
๐Ÿงฉ Function DEFINES a function simulate(). Python only remembers it here - its body runs later, each time simulate() is called.
65
n = int(input("How many next cars to simulate? "))
โŒจ๏ธ Input Shows "How many next cars to simulate? ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable n
66
cols = unique(cars)
๐Ÿงฎ Store / Calculate Calls our own function unique(cars); the result is stored in variable cols
67
weights = [cars.count(c) for c in cols]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [cars.count(c) for c in cols] in variable weights
68
nxt = random.choices(cols, weights=weights, k=n)
๐Ÿงฎ Store / Calculate Calls random.choices(cols); the result is stored in variable nxt
69
print("Simulated:", ", ".join(nxt))
๐Ÿ–ฅ๏ธ Output Displays the text "Simulated:", then the value of ", ".join(nxt) on the screen
70
for c in cols:
๐Ÿ” Loop LOOP: takes each item of cols one-by-one into c and runs the indented block for it
71
print(f"  {c:<7} expected {p(c) * n:4.1f}  simulated {nxt.count(c)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {c:<7} expected {p(c) * n:4.1f} simulated โ€ฆ with the values filled into { } on the screen
evening() - lines 74โ€“80
LineCodeWhat it does
74
def evening():
๐Ÿงฉ Function DEFINES a function evening(). Python only remembers it here - its body runs later, each time evening() is called.
75
ev = to_list(input("Evening colours (comma separated):\n"))
โŒจ๏ธ Input Calls our own function to_list(input("Evening coloโ€ฆ); the result is stored in variable ev
76
print("\nEVENING SURVEY")
๐Ÿ–ฅ๏ธ Output Displays the text "EVENING SURVEY" on the screen
77
table(ev)
๐Ÿงฎ Store / Calculate Calls our own function table(ev)
78
print("\n{:<8}{:>10}{:>10}".format("Colour", "Morning", "Evening"))
๐Ÿ–ฅ๏ธ Output Displays the value of "\n{:<8}{:>10}{:>10}".format("Colour", "Morniโ€ฆ on the screen
79
for c in unique(cars + ev):
๐Ÿ” Loop LOOP: takes each item of unique(cars + ev) one-by-one into c and runs the indented block for it
80
print("{:<8}{:>10.2f}{:>10.2f}".format(c, cars.count(c) / len(cars), ev.count(c) / len(ev)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>10.2f}{:>10.2f}".format(c, cars.counโ€ฆ on the screen
Q1. What is probability?

Number of favourable outcomes / total outcomes, a value from 0 to 1.

Q2. What is the mode?

The value that occurs most often - here the most common car colour.

Q3. What is P(not A)?

1 - P(A), called the complement.

Q4. What is the addition rule?

For events that cannot happen together, P(A or B) = P(A) + P(B).

Q5. How is this linked to AI?

AI models (like Naive Bayes) learn probabilities from data and use them to predict.

04

Rule-Based Crop Advisor for Farmers (SDG 2)

PYTHONSDG 2 - Zero HungerRule-based AI modelnested if-elif-elselogical operatorslists
๐Ÿ“ 126 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 102 output lines๐Ÿ“„ 25+ page report

A rule-based AI model that suggests a suitable crop using the season, soil type and expected rainfall entered by a farmer, and explains the reason for each suggestion.

โœจ Features
  • Rule-based expert system that suggests a crop from season, soil and rainfall
  • Fertiliser (NPK) and irrigation advice for the recommended crop
  • Profit estimator: yield x MSP - cost for the chosen area (acres)
  • Records of all farmers advised in lists and a summary report
  • Crop calendar (sowing / harvesting months) lookup
  • Explains which rule fired (explainability)
โ˜ฐ Main menu
1Advise a FarmerSeason, soil, rainfall -> crop + reason
2Fertiliser & WaterNPK and irrigation tips
3Profit EstimatorArea x yield x MSP - cost
4Crop CalendarSowing / harvesting months
5Summary ReportAll farmers advised
6Show RulesPrints the rule base
0ExitEnds program
๐ŸŽฏ Objectives
  • Convert expert knowledge into if-elif rules (rule-based modelling)
  • Use logical operators and/or to combine conditions
  • Advise multiple farmers in a loop and summarise the advice
๐Ÿ“š Data dictionary
NameTypePurpose
CROPSlist of listscrop, sowing, harvest, yield q/acre, MSP Rs./q, cost Rs./acre, NPK, water
farmers / advicelistsNames and crops advised
advise()functionRule base returning crop and reason
Why it matters: Demonstrates the Rule-Based modelling approach from the AI Project Cycle and how domain knowledge becomes rules.
# =====================================================================
#   RULE-BASED CROP ADVISOR FOR FARMERS   (SDG 2 : Zero Hunger)
#   Concepts: nested if-elif (rule base), lists, functions, menu
# =====================================================================
#        crop,        sow,       harvest,   yield q/acre, MSP Rs/q, cost Rs/acre, NPK kg/acre,    water
CROPS = [["Rice", "Jun-Jul", "Oct-Nov", 22, 2369, 32000, "48:24:24", "Flooded fields; 1200+ mm"],
         ["Cotton", "May-Jun", "Oct-Dec", 9, 7710, 30000, "40:20:20", "Drip irrigation saves 40 % water"],
         ["Maize", "Jun-Jul", "Sep-Oct", 20, 2400, 22000, "48:24:16", "Irrigate at tasseling stage"],
         ["Bajra", "Jun-Jul", "Sep-Oct", 9, 2775, 12000, "24:12:0", "Rain-fed; 1-2 irrigations"],
         ["Wheat", "Nov", "Mar-Apr", 20, 2585, 25000, "50:25:12", "4-6 irrigations; first at 21 days"],
         ["Mustard", "Oct", "Feb-Mar", 8, 6200, 15000, "32:16:0", "2 irrigations"],
         ["Gram", "Oct-Nov", "Feb-Mar", 8, 5875, 14000, "8:20:0", "1-2 irrigations"],
         ["Watermelon", "Feb-Mar", "May-Jun", 80, 800, 30000, "40:24:24", "Light frequent irrigation"]]
farmers, advice = [], []


def find(crop):
    for c in CROPS:
        if c[0].lower() == crop.lower():
            return c
    return None


def advise(season, soil, rain):
    """The rule base: returns (crop, reason)."""
    if season == "kharif":
        if rain >= 1000 and soil in ("clay", "loamy"):
            return "Rice", "Rule K1: high rainfall + water-holding soil"
        elif soil == "black":
            return "Cotton", "Rule K2: black soil retains moisture"
        elif rain >= 500:
            return "Maize", "Rule K3: moderate rainfall"
        return "Bajra", "Rule K4: low rainfall, drought tolerant"
    elif season == "rabi":
        if soil == "loamy" and rain < 600:
            return "Wheat", "Rule R1: cool season + loamy soil"
        elif soil == "sandy":
            return "Mustard", "Rule R2: light soil, little water"
        return "Gram", "Rule R3: needs little irrigation"
    elif season == "zaid":
        return "Watermelon", "Rule Z1: short summer season crop"
    return None, "Unknown season"


def advise_farmer():
    name = input("Farmer name: ")
    season = input("Season (Kharif/Rabi/Zaid): ").strip().lower()
    soil = input("Soil type (clay/loamy/sandy/black): ").strip().lower()
    rain = float(input("Expected rainfall (mm): "))
    crop, why = advise(season, soil, rain)
    if crop is None:
        print("Sorry -", why, "- please enter Kharif, Rabi or Zaid.")
        return
    farmers.append(name); advice.append(crop)
    print(f"Recommended crop for {name}: {crop}")
    print("Reason (rule fired):", why)


def fert_water():
    c = find(input("Crop: "))
    if c:
        print(f"{c[0]}: NPK {c[6]} kg/acre (N:P:K) | Irrigation: {c[7]}")
        print("Tip: get a Soil Health Card test before applying fertiliser.")
    else:
        print("Crop not in database.")


def profit():
    c = find(input("Crop: "))
    area = float(input("Area (acres): "))
    if not c:
        print("Crop not in database."); return
    income = c[3] * c[4] * area
    cost = c[5] * area
    print(f"Expected yield : {c[3] * area} quintals")
    print(f"Income @ MSP   : Rs. {income:,.0f}")
    print(f"Cost           : Rs. {cost:,.0f}")
    print(f"Profit         : Rs. {income - cost:,.0f}  ({(income - cost) / cost * 100:.0f} % return)")


def calendar():
    c = find(input("Crop: "))
    print(f"{c[0]}: sow in {c[1]}, harvest in {c[2]}" if c else "Crop not in database.")


def summary():
    print("{:<4}{:<12}{}".format("No", "Farmer", "Crop"))
    for i in range(len(farmers)):
        print("{:<4}{:<12}{}".format(i + 1, farmers[i], advice[i]))
    for c in CROPS:
        if advice.count(c[0]):
            print(f"  {c[0]:<10}: {advice.count(c[0])} farmer(s)")
    print("Note: rule-based advice; verify with the local Krishi Vigyan Kendra.")


def rules():
    print("K1 Kharif + rain>=1000 + clay/loamy -> Rice | K2 Kharif + black -> Cotton")
    print("K3 Kharif + rain>=500 -> Maize | K4 Kharif otherwise -> Bajra")
    print("R1 Rabi + loamy + rain<600 -> Wheat | R2 Rabi + sandy -> Mustard | R3 Rabi otherwise -> Gram")
    print("Z1 Zaid -> Watermelon")


print("=" * 50)
print("   RULE-BASED CROP ADVISOR  (SDG 2)")
print("=" * 50)
while True:
    print("\n1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Jai Kisan!")
        break
    elif ch == "1":
        advise_farmer()
    elif ch == "2":
        fert_water()
    elif ch == "3":
        profit()
    elif ch == "4":
        calendar()
    elif ch == "5":
        summary()
    elif ch == "6":
        rules()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Advise? → No: run other option
  4. Read season, soil, rainfall
  5. Season = Kharif? → No: check Rabi / Zaid rules
  6. Apply rules to choose crop
  7. Show crop and reason
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Kharif, clay, 1200 mmRicePASS
2Kharif, black, 700 mmCottonPASS
3Rabi, loamy, 400 mmWheatPASS
4Rabi, sandyMustardPASS
5ZaidWatermelonPASS
6Season 'winter''Unknown season'PASS
7Profit Wheat 5 acresProfit shownPASS
8Calendar RiceJun-Jul / Oct-NovPASS
โš  Limitations
  • Few rules and crops
  • Prices and yields are approximate
  • No soil test values (pH, NPK)
  • Local conditions differ
๐Ÿš€ Future scope
  • Use machine learning on Kaggle crop dataset (Class XI KNN)
  • Weather API for rainfall
  • Hindi / regional language voice input
  • Link to e-NAM market prices

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: CROPS.
  2. 8 functions are defined (lines 17โ€“100) - Python stores them but does NOT run them yet.
  3. Main program starts at line 14: farmers, advice = [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
find(crop)17โ€“21Findfert_water(), profit(), calendar()
advise(season, soil, rain)24โ€“42The rule base: returns (crop, reason).advise_farmer()
advise_farmer()45โ€“56Advise farmermain program
fert_water()59โ€“65Fert watermain program
profit()68โ€“78Profitmain program
calendar()81โ€“83Calendarmain program
summary()86โ€“93Summarymain program
rules()96โ€“100Rulesmain program
โ‘ข Main program - line by line
LineCodeWhat it does
14
farmers, advice = [], []
๐Ÿงฎ Store / Calculate Stores [], [] into farmers, advice respectively
103
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
104
print("   RULE-BASED CROP ADVISOR  (SDG 2)")
๐Ÿ–ฅ๏ธ Output Displays the text "RULE-BASED CROP ADVISOR (SDG 2)" on the screen
105
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
106
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
107
print("\n1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Advise 2.Fertiliser & Water 3.Pโ€ฆ" on the screen
108
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
109
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
110
print("Jai Kisan!")
๐Ÿ–ฅ๏ธ Output Displays the text "Jai Kisan!" on the screen
111
break
๐Ÿ” Loop BREAK - leaves the loop immediately
112
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
113
advise_farmer()
๐Ÿงฎ Store / Calculate Calls our own function advise_farmer()
114
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
115
fert_water()
๐Ÿงฎ Store / Calculate Calls our own function fert_water()
116
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
117
profit()
๐Ÿงฎ Store / Calculate Calls our own function profit()
118
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
119
calendar()
๐Ÿงฎ Store / Calculate Calls our own function calendar()
120
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
121
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
122
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
123
rules()
๐Ÿงฎ Store / Calculate Calls our own function rules()
124
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
125
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: RULE-BASED CROP ADVISOR (SDG 2) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: advise_farmer()
  3. You type Ramesh at Farmer name:
  4. You type Kharif at Season (Kharif/Rabi/Zaid):
  5. You type clay at Soil type (clay/loamy/sandy/black):
  6. You type 1200 at Expected rainfall (mm):
    runs: advise()
    shows: Recommended crop for Ramesh: Rice (+2 more lines)
  7. You type 1 at Enter choice:
    runs: advise_farmer()
  8. You type Sita at Farmer name:
  9. You type Kharif at Season (Kharif/Rabi/Zaid):
  10. You type black at Soil type (clay/loamy/sandy/black):
  11. You type 700 at Expected rainfall (mm):
    runs: advise()
    shows: Recommended crop for Sita: Cotton (+2 more lines)
  12. You type 1 at Enter choice:
    runs: advise_farmer()
  13. You type Gurpreet at Farmer name:
  14. You type Rabi at Season (Kharif/Rabi/Zaid):
  15. You type loamy at Soil type (clay/loamy/sandy/black):
  16. You type 400 at Expected rainfall (mm):
    runs: advise()
    shows: Recommended crop for Gurpreet: Wheat (+2 more lines)
  17. You type 1 at Enter choice:
    runs: advise_farmer()
  18. You type Bhola at Farmer name:
  19. You type Rabi at Season (Kharif/Rabi/Zaid):
  20. You type sandy at Soil type (clay/loamy/sandy/black):
  21. You type 300 at Expected rainfall (mm):
    runs: advise()
    shows: Recommended crop for Bhola: Mustard (+2 more lines)
  22. You type 1 at Enter choice:
    runs: advise_farmer()
  23. You type Anil at Farmer name:
  24. You type Zaid at Season (Kharif/Rabi/Zaid):
  25. You type sandy at Soil type (clay/loamy/sandy/black):
  26. You type 100 at Expected rainfall (mm):
    runs: advise()
    shows: Recommended crop for Anil: Watermelon (+2 more lines)
  27. You type 1 at Enter choice:
    runs: advise_farmer()
  28. You type Test at Farmer name:
  29. You type winter at Season (Kharif/Rabi/Zaid):
  30. You type clay at Soil type (clay/loamy/sandy/black):
  31. You type 500 at Expected rainfall (mm):
    runs: advise()
    shows: Sorry - Unknown season - please enter Kharif, Rabi or Zaid. (+1 more lines)
  32. You type 2 at Enter choice:
    runs: fert_water()
  33. You type Wheat at Crop:
    runs: find()
    shows: Wheat: NPK 50:25:12 kg/acre (N:P:K) | Irrigation: 4-6 irrigations; first at 21 days (+2 more lines)
  34. You type 3 at Enter choice:
    runs: profit()
  35. You type Wheat at Crop:
    runs: find()
  36. You type 5 at Area (acres):
    shows: Expected yield : 100.0 quintals (+4 more lines)
  37. You type 4 at Enter choice:
    runs: calendar()
  38. You type Rice at Crop:
    runs: find()
    shows: Rice: sow in Jun-Jul, harvest in Oct-Nov (+1 more lines)
  39. You type 5 at Enter choice:
    runs: summary()
    shows: No Farmer Crop (+12 more lines)
  40. You type 6 at Enter choice:
    runs: rules()
    shows: K1 Kharif + rain>=1000 + clay/loamy -> Rice | K2 Kharif + black -> Cotton (+4 more lines)
โ‘ค Inside each function - line by line
find() - lines 17โ€“21
LineCodeWhat it does
17
def find(crop):
๐Ÿงฉ Function DEFINES a function find(crop). Python only remembers it here - its body runs later, each time find() is called.
18
for c in CROPS:
๐Ÿ” Loop LOOP: takes each item of CROPS one-by-one into c and runs the indented block for it
19
if c[0].lower() == crop.lower():
๐Ÿ”€ Decision CHECKS whether c[0].lower() is equal to crop.lower(). If True, the indented lines below run; otherwise they are skipped
20
return c
๐Ÿงฉ Function Sends back (returns) the value of c to the line that called the function
21
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
advise() - lines 24โ€“42
LineCodeWhat it does
24
def advise(season, soil, rain):
๐Ÿงฉ Function DEFINES a function advise(season, soil, rain). Python only remembers it here - its body runs later, each time advise() is called.
26
if season == "kharif":
๐Ÿ”€ Decision CHECKS whether season is equal to "kharif". If True, the indented lines below run; otherwise Python jumps to the elif/else part
27
if rain >= 1000 and soil in ("clay", "loamy"):
๐Ÿ”€ Decision CHECKS whether (rain is greater than or equal to 1000 AND soil is present in ("clay", "loamy")). If True, the indented lines below run; otherwise Python jumps to the elif/else part
28
return "Rice", "Rule K1: high rainfall + water-holding soil"
๐Ÿงฉ Function Sends back (returns) the tuple "Rice", "Rule K1: high rainfall + water-holdiโ€ฆ to the line that called the function
29
elif soil == "black":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether soil is equal to "black"
30
return "Cotton", "Rule K2: black soil retains moisture"
๐Ÿงฉ Function Sends back (returns) the tuple "Cotton", "Rule K2: black soil retains moistuโ€ฆ to the line that called the function
31
elif rain >= 500:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether rain is greater than or equal to 500
32
return "Maize", "Rule K3: moderate rainfall"
๐Ÿงฉ Function Sends back (returns) the tuple "Maize", "Rule K3: moderate rainfall" to the line that called the function
33
return "Bajra", "Rule K4: low rainfall, drought tolerant"
๐Ÿงฉ Function Sends back (returns) the tuple "Bajra", "Rule K4: low rainfall, drought toleโ€ฆ to the line that called the function
34
elif season == "rabi":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether season is equal to "rabi"
35
if soil == "loamy" and rain < 600:
๐Ÿ”€ Decision CHECKS whether (soil is equal to "loamy" AND rain is less than 600). If True, the indented lines below run; otherwise Python jumps to the elif/else part
36
return "Wheat", "Rule R1: cool season + loamy soil"
๐Ÿงฉ Function Sends back (returns) the tuple "Wheat", "Rule R1: cool season + loamy soil" to the line that called the function
37
elif soil == "sandy":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether soil is equal to "sandy"
38
return "Mustard", "Rule R2: light soil, little water"
๐Ÿงฉ Function Sends back (returns) the tuple "Mustard", "Rule R2: light soil, little water" to the line that called the function
39
return "Gram", "Rule R3: needs little irrigation"
๐Ÿงฉ Function Sends back (returns) the tuple "Gram", "Rule R3: needs little irrigation" to the line that called the function
40
elif season == "zaid":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether season is equal to "zaid"
41
return "Watermelon", "Rule Z1: short summer season crop"
๐Ÿงฉ Function Sends back (returns) the tuple "Watermelon", "Rule Z1: short summer season cโ€ฆ to the line that called the function
42
return None, "Unknown season"
๐Ÿงฉ Function Sends back (returns) the tuple None, "Unknown season" to the line that called the function
advise_farmer() - lines 45โ€“56
LineCodeWhat it does
45
def advise_farmer():
๐Ÿงฉ Function DEFINES a function advise_farmer(). Python only remembers it here - its body runs later, each time advise_farmer() is called.
46
name = input("Farmer name: ")
โŒจ๏ธ Input Shows the message "Farmer name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
47
season = input("Season (Kharif/Rabi/Zaid): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable season
48
soil = input("Soil type (clay/loamy/sandy/black): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable soil
49
rain = float(input("Expected rainfall (mm): "))
โŒจ๏ธ Input Shows "Expected rainfall (mm): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable rain
50
crop, why = advise(season, soil, rain)
๐Ÿงฎ Store / Calculate Calls our own function advise(season, soil, rain) - the rule base: returns (crop, reason); the result is stored in variables crop, why
51
if crop is None:
๐Ÿ”€ Decision CHECKS whether crop is None. If True, the indented lines below run; otherwise they are skipped
52
print("Sorry -", why, "- please enter Kharif, Rabi or Zaid.")
๐Ÿ–ฅ๏ธ Output Displays the text "Sorry -", then the value of why, then the text "- please enter Kharif, Rabi or Zaโ€ฆ" on the screen
53
return
๐Ÿงฉ Function Ends the function and goes back to the caller
54
farmers.append(name); advice.append(crop)
๐Ÿงฎ Store / Calculate Adds name at the end of list farmers
54
farmers.append(name); advice.append(crop)
๐Ÿงฎ Store / Calculate Adds crop at the end of list advice
55
print(f"Recommended crop for {name}: {crop}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Recommended crop for {name}: {crop}" with the values filled into { } on the screen
56
print("Reason (rule fired):", why)
๐Ÿ–ฅ๏ธ Output Displays the text "Reason (rule fired):", then the value of why on the screen
fert_water() - lines 59โ€“65
LineCodeWhat it does
59
def fert_water():
๐Ÿงฉ Function DEFINES a function fert_water(). Python only remembers it here - its body runs later, each time fert_water() is called.
60
c = find(input("Crop: "))
โŒจ๏ธ Input Calls our own function find(input("Crop: ")); the result is stored in variable c
61
if c:
๐Ÿ”€ Decision CHECKS whether c is True (not empty / not zero). If True, the indented lines below run; otherwise Python jumps to the elif/else part
62
print(f"{c[0]}: NPK {c[6]} kg/acre (N:P:K) | Irrigation: {c[7]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c[0]}: NPK {c[6]} kg/acre (N:P:K) | Irrigaโ€ฆ with the values filled into { } on the screen
63
print("Tip: get a Soil Health Card test before applying fertiliser.")
๐Ÿ–ฅ๏ธ Output Displays the text "Tip: get a Soil Health Card test โ€ฆ" on the screen
64
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
65
print("Crop not in database.")
๐Ÿ–ฅ๏ธ Output Displays the text "Crop not in database." on the screen
profit() - lines 68โ€“78
LineCodeWhat it does
68
def profit():
๐Ÿงฉ Function DEFINES a function profit(). Python only remembers it here - its body runs later, each time profit() is called.
69
c = find(input("Crop: "))
โŒจ๏ธ Input Calls our own function find(input("Crop: ")); the result is stored in variable c
70
area = float(input("Area (acres): "))
โŒจ๏ธ Input Shows "Area (acres): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable area
71
if not c:
๐Ÿ”€ Decision CHECKS whether c is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
72
print("Crop not in database."); return
๐Ÿ–ฅ๏ธ Output Displays the text "Crop not in database." on the screen
72
print("Crop not in database."); return
๐Ÿ–ฅ๏ธ Output Ends the function and goes back to the caller
73
income = c[3] * c[4] * area
๐Ÿงฎ Store / Calculate Stores the value of c[3] * c[4] * area (calculated using ร—) in variable income
74
cost = c[5] * area
๐Ÿงฎ Store / Calculate Stores the value of c[5] * area (calculated using ร—) in variable cost
75
print(f"Expected yield : {c[3] * area} quintals")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Expected yield : {c[3] * area} quintals" with the values filled into { } on the screen
76
print(f"Income @ MSP   : Rs. {income:,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Income @ MSP : Rs. {income:,.0f}" with the values filled into { } on the screen
77
print(f"Cost           : Rs. {cost:,.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Cost : Rs. {cost:,.0f}" with the values filled into { } on the screen
78
print(f"Profit         : Rs. {income - cost:,.0f}  ({(income - cost) / cost * 100:.0f} % return)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Profit : Rs. {income - cost:,.0f} ({(incomeโ€ฆ with the values filled into { } on the screen
calendar() - lines 81โ€“83
LineCodeWhat it does
81
def calendar():
๐Ÿงฉ Function DEFINES a function calendar(). Python only remembers it here - its body runs later, each time calendar() is called.
82
c = find(input("Crop: "))
โŒจ๏ธ Input Calls our own function find(input("Crop: ")); the result is stored in variable c
83
print(f"{c[0]}: sow in {c[1]}, harvest in {c[2]}" if c else "Crop not in database.")
๐Ÿ–ฅ๏ธ Output Displays the value of f"{c[0]}: sow in {c[1]}, harvest in {c[2]}" iโ€ฆ on the screen
summary() - lines 86โ€“93
LineCodeWhat it does
86
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
87
print("{:<4}{:<12}{}".format("No", "Farmer", "Crop"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<12}{}".format("No", "Farmer", "Crop") on the screen
88
for i in range(len(farmers)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(farmers) - 1; for each number, i takes that value and the indented block runs once
89
print("{:<4}{:<12}{}".format(i + 1, farmers[i], advice[i]))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<12}{}".format(i + 1, farmers[i], advโ€ฆ on the screen
90
for c in CROPS:
๐Ÿ” Loop LOOP: takes each item of CROPS one-by-one into c and runs the indented block for it
91
if advice.count(c[0]):
๐Ÿ”€ Decision CHECKS whether advice.count(c[0]) is True. If True, the indented lines below run; otherwise they are skipped
92
print(f"  {c[0]:<10}: {advice.count(c[0])} farmer(s)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {c[0]:<10}: {advice.count(c[0])} farmer(s)" with the values filled into { } on the screen
93
print("Note: rule-based advice; verify with the local Krishi Vigyan Kendra.")
๐Ÿ–ฅ๏ธ Output Displays the text "Note: rule-based advice; verify wโ€ฆ" on the screen
rules() - lines 96โ€“100
LineCodeWhat it does
96
def rules():
๐Ÿงฉ Function DEFINES a function rules(). Python only remembers it here - its body runs later, each time rules() is called.
97
print("K1 Kharif + rain>=1000 + clay/loamy -> Rice | K2 Kharif + black -> Cotton")
๐Ÿ–ฅ๏ธ Output Displays the text "K1 Kharif + rain>=1000 + clay/loaโ€ฆ" on the screen
98
print("K3 Kharif + rain>=500 -> Maize | K4 Kharif otherwise -> Bajra")
๐Ÿ–ฅ๏ธ Output Displays the text "K3 Kharif + rain>=500 -> Maize | โ€ฆ" on the screen
99
print("R1 Rabi + loamy + rain<600 -> Wheat | R2 Rabi + sandy -> Mustard | R3 Rabi otherwise -> Gram")
๐Ÿ–ฅ๏ธ Output Displays the text "R1 Rabi + loamy + rain<600 -> Wheโ€ฆ" on the screen
100
print("Z1 Zaid -> Watermelon")
๐Ÿ–ฅ๏ธ Output Displays the text "Z1 Zaid -> Watermelon" on the screen
Q1. What is a rule-based system?

A program where experts' knowledge is written as IF-THEN rules; it does not learn from data.

Q2. What are its advantages?

Easy to explain the decision, works with little data, quick to build.

Q3. Limitation of rule-based AI?

Cannot handle new situations not covered by rules; rules must be updated manually.

Q4. What is MSP?

Minimum Support Price - price at which government buys crops from farmers.

Q5. Which SDG?

SDG 2 - Zero Hunger, by improving farm productivity and income.

05

Personalised Learning Quiz - AI Project Cycle (SDG 4)

PYTHONSDG 4 - Quality Educationlists of questions/answersfor loopstring methodsscoringif-elif
๐Ÿ“ 123 lines of codeโ˜ฐ 6 menu options๐Ÿ–ฅ๏ธ 174 output lines๐Ÿ“„ 25+ page report

Implements the CBSE activity 'AI model for Personalised Education': a quiz on AI basics checks the student's answers, calculates topic-wise scores and recommends the next learning level and the weakest topic to revise.

โœจ Features
  • Question bank of 12 questions on AI domains, project cycle, modeling and evaluation (lists)
  • Topic-wise score tracking and personalised level recommendation (Beginner / Intermediate / Advanced)
  • Practice mode on a chosen topic only
  • Hint option before answering
  • Leaderboard of all students in the session (sorted)
  • Weak-topic analysis for the whole class
โ˜ฐ Main menu
1Full QuizAll 12 questions with topic report
2Practice a TopicQuestions of one topic
3LeaderboardSorted by score
4Class Weak TopicsTopic-wise class accuracy
5Question Bank StatsQuestions per topic
0ExitEnds program
๐ŸŽฏ Objectives
  • Store questions, answers and topics in parallel lists
  • Evaluate answers and compute topic-wise performance
  • Recommend a personalised learning path using rules
๐Ÿ“š Data dictionary
NameTypePurpose
questions / answers / topics / hintslistsParallel lists of the question bank
names, scoreslistsStudents and their scores
t_right, t_totallistsClass-wide topic counters
Why it matters: Shows every stage of the AI project cycle in miniature - data (answers), model (rules), evaluation (score) and deployment (recommendation).
# =====================================================================
#   PERSONALISED LEARNING QUIZ - AI PROJECT CYCLE   (SDG 4)
#   Concepts: parallel lists, functions, loops, min/max with key, sort
# =====================================================================
questions = ["Face unlock in phones belongs to which AI domain (cv/nlp/data)?",
             "Google Translate belongs to which AI domain?",
             "Netflix recommendations belong to which AI domain?",
             "Name the FIRST stage of the AI Project Cycle.",
             "Collecting data from surveys and sensors is called ____ ____.",
             "A model where the developer writes all rules is called ____ based.",
             "Rock-paper-scissors move prediction comes under which domain?",
             "Predicted YES and actually YES is called a ____ ____.",
             "Predicted NO but actually YES is called a ____ ____.",
             "Training the AI model is done in which stage?",
             "(TP + TN) / Total is called ____.",
             "Making the model available to users is called ____."]
answers = ["cv", "nlp", "data", "problem scoping", "data acquisition", "rule", "data", "true positive", "false negative", "modelling", "accuracy", "deployment"]
topics = ["Domains", "Domains", "Domains", "Project Cycle", "Project Cycle", "Modelling", "Domains", "Evaluation", "Evaluation", "Project Cycle", "Evaluation", "Project Cycle"]
hints = ["It sees images", "It understands language", "It learns from numbers", "Starts with 'problem'", "Starts with 'data'", "Opposite of learning based",
         "Uses past move data", "Both true", "Wrongly said no", "Starts with 'mod'", "Starts with 'acc'", "Starts with 'dep'"]
TOPICS = ["Domains", "Project Cycle", "Modelling", "Evaluation"]
names, scores = [], []
t_right, t_total = [0, 0, 0, 0], [0, 0, 0, 0]


def ask(i):
    """Asks question i; returns True if correct. 'h' shows a hint."""
    while True:
        ans = input("Your answer (h = hint): ").strip().lower()
        if ans == "h":
            print("  Hint:", hints[i])
        else:
            break
    t = TOPICS.index(topics[i])
    t_total[t] += 1
    if answers[i] in ans:
        t_right[t] += 1
        print("  Correct!")
        return True
    print("  Oops! Correct answer:", answers[i])
    return False


def full_quiz():
    name = input("Enter your name: ")
    right, tot = [0, 0, 0, 0], [0, 0, 0, 0]
    score = 0
    for i in range(len(questions)):
        print(f"\nQ{i + 1}. [{topics[i]}] {questions[i]}")
        t = TOPICS.index(topics[i])
        tot[t] += 1
        if ask(i):
            score += 1; right[t] += 1
    pct = score / len(questions) * 100
    print("\n----- REPORT CARD:", name, "-----")
    for t in range(4):
        print(f"{TOPICS[t]:<14}: {right[t]}/{tot[t]}  " + "*" * right[t])
    print("Score:", score, "/", len(questions), "=", round(pct, 1), "%")
    weak = min(range(4), key=lambda t: right[t] / tot[t])
    if pct >= 80:
        print("Level: ADVANCED - try Python projects next.")
    elif pct >= 50:
        print("Level: INTERMEDIATE - revise", TOPICS[weak])
    else:
        print("Level: BEGINNER - watch the videos on", TOPICS[weak])
    names.append(name); scores.append(score)


def practice():
    tp = input("Topic (Domains/Project Cycle/Modelling/Evaluation): ").strip().title()
    idx = [i for i in range(len(topics)) if topics[i] == tp]
    if not idx:
        print("No such topic."); return
    s = 0
    for i in idx:
        print("\n" + questions[i])
        if ask(i):
            s += 1
    print(f"Practice score in {tp}: {s}/{len(idx)}")


def leaderboard():
    pairs = sorted(zip(scores, names), reverse=True)
    for r, (s, n) in enumerate(pairs, 1):
        print(f"{r}. {n:<10} {s}/{len(questions)}")


def class_weak():
    for t in range(4):
        if t_total[t]:
            print(f"{TOPICS[t]:<14} class accuracy {t_right[t] / t_total[t] * 100:5.1f} %")
    weak = min([t for t in range(4) if t_total[t]], key=lambda t: t_right[t] / t_total[t])
    print("Teacher should re-teach:", TOPICS[weak])


def bank():
    for tp in TOPICS:
        print(f"{tp:<14}: {topics.count(tp)} questions")
    print("Total:", len(questions))


print("=" * 50)
print("   PERSONALISED AI LEARNING QUIZ  (SDG 4)")
print("=" * 50)
while True:
    print("\n1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Keep learning!")
        break
    elif ch == "1":
        full_quiz()
    elif ch == "2":
        practice()
    elif ch == "3":
        leaderboard()
    elif ch == "4":
        class_weak()
    elif ch == "5":
        bank()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Full Quiz? → No: run other option
  4. Read name
  5. Ask question; 'h' shows hint
  6. Answer correct? → No: show correct answer
  7. Update topic scores
  8. Report card and recommendation
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1All correctADVANCED levelPASS
27/12 correctINTERMEDIATE + weak topic to revisePASS
3Type 'h'Hint shown and asked againPASS
4Practice 'Evaluation'Only evaluation questionsPASS
5Practice 'xyz''No such topic'PASS
6LeaderboardSorted listPASS
7Class weak topicsAccuracy per topicPASS
โš  Limitations
  • Fixed question bank
  • Exact keyword matching
  • No timer
  • Session data not saved
๐Ÿš€ Future scope
  • Adaptive difficulty (harder questions after correct answers)
  • Store results in CSV
  • Voice-based quiz
  • Chatbot tutor

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: questions, answers, topics, hints, TOPICS.
  2. 6 functions are defined (lines 26โ€“99) - Python stores them but does NOT run them yet.
  3. Main program starts at line 22: names, scores = [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
ask(i)26โ€“41Asks question i; returns True if correct. 'h' shows a hint.full_quiz(), practice()
full_quiz()44โ€“66Full quizmain program
practice()69โ€“79Practicemain program
leaderboard()82โ€“85Leaderboardmain program
class_weak()88โ€“93Class weakmain program
bank()96โ€“99Bankmain program
โ‘ข Main program - line by line
LineCodeWhat it does
22
names, scores = [], []
๐Ÿงฎ Store / Calculate Stores [], [] into names, scores respectively
23
t_right, t_total = [0, 0, 0, 0], [0, 0, 0, 0]
๐Ÿงฎ Store / Calculate Stores [0, 0, 0, 0], [0, 0, 0, 0] into t_right, t_total respectively
102
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
103
print("   PERSONALISED AI LEARNING QUIZ  (SDG 4)")
๐Ÿ–ฅ๏ธ Output Displays the text "PERSONALISED AI LEARNING QUIZ (SDโ€ฆ" on the screen
104
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
105
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
106
print("\n1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Full Quiz 2.Practice Topic 3.Leโ€ฆ" on the screen
107
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
108
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
109
print("Keep learning!")
๐Ÿ–ฅ๏ธ Output Displays the text "Keep learning!" on the screen
110
break
๐Ÿ” Loop BREAK - leaves the loop immediately
111
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
112
full_quiz()
๐Ÿงฎ Store / Calculate Calls our own function full_quiz()
113
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
114
practice()
๐Ÿงฎ Store / Calculate Calls our own function practice()
115
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
116
leaderboard()
๐Ÿงฎ Store / Calculate Calls our own function leaderboard()
117
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
118
class_weak()
๐Ÿงฎ Store / Calculate Calls our own function class_weak()
119
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
120
bank()
๐Ÿงฎ Store / Calculate Calls our own function bank()
121
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
122
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: PERSONALISED AI LEARNING QUIZ (SDG 4) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: full_quiz()
  3. You type Meera at Enter your name:
    runs: ask()
    shows: Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)?
  4. You type cv at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  5. You type nlp at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  6. You type data at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  7. You type problem scoping at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  8. You type h at Your answer (h = hint):
    shows: Hint: Starts with 'data'
  9. You type data acquisition at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  10. You type rule at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  11. You type data at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  12. You type true positive at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  13. You type false negative at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  14. You type modelling at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  15. You type accuracy at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  16. You type deployment at Your answer (h = hint):
    shows: Correct! (+8 more lines)
  17. You type 1 at Enter choice:
    runs: full_quiz()
  18. You type Arjun at Enter your name:
    runs: ask()
    shows: Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)?
  19. You type cv at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  20. You type nlp at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  21. You type netflix at Your answer (h = hint):
    runs: ask()
    shows: Oops! Correct answer: data (+1 more lines)
  22. You type data acquisition at Your answer (h = hint):
    runs: ask()
    shows: Oops! Correct answer: problem scoping (+1 more lines)
  23. You type h at Your answer (h = hint):
    shows: Hint: Starts with 'data'
  24. You type data acquisition at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  25. You type rule at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  26. You type data at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  27. You type true negative at Your answer (h = hint):
    runs: ask()
    shows: Oops! Correct answer: true positive (+1 more lines)
  28. You type false negative at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  29. You type evaluation at Your answer (h = hint):
    runs: ask()
    shows: Oops! Correct answer: modelling (+1 more lines)
  30. You type precision at Your answer (h = hint):
    runs: ask()
    shows: Oops! Correct answer: accuracy (+1 more lines)
  31. You type deployment at Your answer (h = hint):
    shows: Correct! (+8 more lines)
  32. You type 2 at Enter choice:
    runs: practice()
  33. You type Evaluation at Topic (Domains/Project Cycle/Modelling/Evaluation):
    runs: ask()
    shows: Predicted YES and actually YES is called a ____ ____.
  34. You type true positive at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  35. You type false negative at Your answer (h = hint):
    runs: ask()
    shows: Correct! (+1 more lines)
  36. You type accuracy at Your answer (h = hint):
    shows: Correct! (+2 more lines)
  37. You type 2 at Enter choice:
    runs: practice()
  38. You type xyz at Topic (Domains/Project Cycle/Modelling/Evaluation):
    shows: No such topic. (+1 more lines)
  39. You type 3 at Enter choice:
    runs: leaderboard()
    shows: 1. Meera 12/12 (+2 more lines)
  40. You type 4 at Enter choice:
    runs: class_weak()
    shows: Domains class accuracy 87.5 % (+5 more lines)

โ€ฆ and 2 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
ask() - lines 26โ€“41
LineCodeWhat it does
26
def ask(i):
๐Ÿงฉ Function DEFINES a function ask(i). Python only remembers it here - its body runs later, each time ask() is called.
28
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
29
ans = input("Your answer (h = hint): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable ans
30
if ans == "h":
๐Ÿ”€ Decision CHECKS whether ans is equal to "h". If True, the indented lines below run; otherwise Python jumps to the elif/else part
31
print("  Hint:", hints[i])
๐Ÿ–ฅ๏ธ Output Displays the text "Hint:", then the value of hints[i] on the screen
32
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
33
break
๐Ÿ” Loop BREAK - leaves the loop immediately
34
t = TOPICS.index(topics[i])
๐Ÿงฎ Store / Calculate Gives the position of topics[i] in TOPICS; the result is stored in variable t
35
t_total[t] += 1
๐Ÿงฎ Store / Calculate Adds 1 to t_total[t] (same as t_total[t] = t_total[t] + 1)
36
if answers[i] in ans:
๐Ÿ”€ Decision CHECKS whether answers[i] is present in ans. If True, the indented lines below run; otherwise they are skipped
37
t_right[t] += 1
๐Ÿงฎ Store / Calculate Adds 1 to t_right[t] (same as t_right[t] = t_right[t] + 1)
38
print("  Correct!")
๐Ÿ–ฅ๏ธ Output Displays the text "Correct!" on the screen
39
return True
๐Ÿงฉ Function Sends back (returns) True to the line that called the function
40
print("  Oops! Correct answer:", answers[i])
๐Ÿ–ฅ๏ธ Output Displays the text "Oops! Correct answer:", then the value of answers[i] on the screen
41
return False
๐Ÿงฉ Function Sends back (returns) False to the line that called the function
full_quiz() - lines 44โ€“66
LineCodeWhat it does
44
def full_quiz():
๐Ÿงฉ Function DEFINES a function full_quiz(). Python only remembers it here - its body runs later, each time full_quiz() is called.
45
name = input("Enter your name: ")
โŒจ๏ธ Input Shows the message "Enter your name: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
46
right, tot = [0, 0, 0, 0], [0, 0, 0, 0]
๐Ÿงฎ Store / Calculate Stores [0, 0, 0, 0], [0, 0, 0, 0] into right, tot respectively
47
score = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable score
48
for i in range(len(questions)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(questions) - 1; for each number, i takes that value and the indented block runs once
49
print(f"\nQ{i + 1}. [{topics[i]}] {questions[i]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"\nQ{i + 1}. [{topics[i]}] {questions[i]}" with the values filled into { } on the screen
50
t = TOPICS.index(topics[i])
๐Ÿงฎ Store / Calculate Gives the position of topics[i] in TOPICS; the result is stored in variable t
51
tot[t] += 1
๐Ÿงฎ Store / Calculate Adds 1 to tot[t] (same as tot[t] = tot[t] + 1)
52
if ask(i):
๐Ÿ”€ Decision CHECKS whether ask(i) is True. If True, the indented lines below run; otherwise they are skipped
53
score += 1; right[t] += 1
๐Ÿงฎ Store / Calculate Adds 1 to score (same as score = score + 1)
53
score += 1; right[t] += 1
๐Ÿงฎ Store / Calculate Adds 1 to right[t] (same as right[t] = right[t] + 1)
54
pct = score / len(questions) * 100
๐Ÿงฎ Store / Calculate Stores the value of score / len(questions) * 100 (calculated using ร—) in variable pct
55
print("\n----- REPORT CARD:", name, "-----")
๐Ÿ–ฅ๏ธ Output Displays the text "----- REPORT CARD:", then the value of name, then the text "-----" on the screen
56
for t in range(4):
๐Ÿ” Loop LOOP: gives the numbers 0 to 3 (4 numbers); for each number, t takes that value and the indented block runs once
57
print(f"{TOPICS[t]:<14}: {right[t]}/{tot[t]}  " + "*" * right[t])
๐Ÿ–ฅ๏ธ Output Displays the value of f"{TOPICS[t]:<14}: {right[t]}/{tot[t]} " + "*โ€ฆ on the screen
58
print("Score:", score, "/", len(questions), "=", round(pct, 1), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Score:", then the value of score, then the text "/", then the value of len(questions), then the text "=", then the value of round(pct, 1), then the text "%" on the screen
59
weak = min(range(4), key=lambda t: right[t] / tot[t])
๐Ÿงฎ Store / Calculate Finds the smallest value among range(4); the result is stored in variable weak
60
if pct >= 80:
๐Ÿ”€ Decision CHECKS whether pct is greater than or equal to 80. If True, the indented lines below run; otherwise Python jumps to the elif/else part
61
print("Level: ADVANCED - try Python projects next.")
๐Ÿ–ฅ๏ธ Output Displays the text "Level: ADVANCED - try Python projโ€ฆ" on the screen
62
elif pct >= 50:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether pct is greater than or equal to 50
63
print("Level: INTERMEDIATE - revise", TOPICS[weak])
๐Ÿ–ฅ๏ธ Output Displays the text "Level: INTERMEDIATE - revise", then the value of TOPICS[weak] on the screen
64
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
65
print("Level: BEGINNER - watch the videos on", TOPICS[weak])
๐Ÿ–ฅ๏ธ Output Displays the text "Level: BEGINNER - watch the videoโ€ฆ", then the value of TOPICS[weak] on the screen
66
names.append(name); scores.append(score)
๐Ÿงฎ Store / Calculate Adds name at the end of list names
66
names.append(name); scores.append(score)
๐Ÿงฎ Store / Calculate Adds score at the end of list scores
practice() - lines 69โ€“79
LineCodeWhat it does
69
def practice():
๐Ÿงฉ Function DEFINES a function practice(). Python only remembers it here - its body runs later, each time practice() is called.
70
tp = input("Topic (Domains/Project Cycle/Modelling/Evaluation): ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable tp
71
idx = [i for i in range(len(topics)) if topics[i] == tp]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [i for i in range(len(topics)) if topics[i] =โ€ฆ in variable idx
72
if not idx:
๐Ÿ”€ Decision CHECKS whether idx is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
73
print("No such topic."); return
๐Ÿ–ฅ๏ธ Output Displays the text "No such topic." on the screen
73
print("No such topic."); return
๐Ÿ–ฅ๏ธ Output Ends the function and goes back to the caller
74
s = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable s
75
for i in idx:
๐Ÿ” Loop LOOP: takes each item of idx one-by-one into i and runs the indented block for it
76
print("\n" + questions[i])
๐Ÿ–ฅ๏ธ Output Displays the value of "\n" + questions[i] on the screen
77
if ask(i):
๐Ÿ”€ Decision CHECKS whether ask(i) is True. If True, the indented lines below run; otherwise they are skipped
78
s += 1
๐Ÿงฎ Store / Calculate Adds 1 to s (same as s = s + 1)
79
print(f"Practice score in {tp}: {s}/{len(idx)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Practice score in {tp}: {s}/{len(idx)}" with the values filled into { } on the screen
leaderboard() - lines 82โ€“85
LineCodeWhat it does
82
def leaderboard():
๐Ÿงฉ Function DEFINES a function leaderboard(). Python only remembers it here - its body runs later, each time leaderboard() is called.
83
pairs = sorted(zip(scores, names), reverse=True)
๐Ÿงฎ Store / Calculate Makes a new sorted list from zip(scores, names); the result is stored in variable pairs
84
for r, (s, n) in enumerate(pairs, 1):
๐Ÿ” Loop LOOP over pairs with position: in each round r, (s, n) get (position, item)
85
print(f"{r}. {n:<10} {s}/{len(questions)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{r}. {n:<10} {s}/{len(questions)}" with the values filled into { } on the screen
class_weak() - lines 88โ€“93
LineCodeWhat it does
88
def class_weak():
๐Ÿงฉ Function DEFINES a function class_weak(). Python only remembers it here - its body runs later, each time class_weak() is called.
89
for t in range(4):
๐Ÿ” Loop LOOP: gives the numbers 0 to 3 (4 numbers); for each number, t takes that value and the indented block runs once
90
if t_total[t]:
๐Ÿ”€ Decision CHECKS whether t_total[t] is True. If True, the indented lines below run; otherwise they are skipped
91
print(f"{TOPICS[t]:<14} class accuracy {t_right[t] / t_total[t] * 100:5.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{TOPICS[t]:<14} class accuracy {t_right[t] โ€ฆ with the values filled into { } on the screen
92
weak = min([t for t in range(4) if t_total[t]], key=lambda t: t_right[t] / t_total[t])
๐Ÿงฎ Store / Calculate Finds the smallest value among [t for t in range(4) if t_total[t]]; the result is stored in variable weak
93
print("Teacher should re-teach:", TOPICS[weak])
๐Ÿ–ฅ๏ธ Output Displays the text "Teacher should re-teach:", then the value of TOPICS[weak] on the screen
bank() - lines 96โ€“99
LineCodeWhat it does
96
def bank():
๐Ÿงฉ Function DEFINES a function bank(). Python only remembers it here - its body runs later, each time bank() is called.
97
for tp in TOPICS:
๐Ÿ” Loop LOOP: takes each item of TOPICS one-by-one into tp and runs the indented block for it
98
print(f"{tp:<14}: {topics.count(tp)} questions")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{tp:<14}: {topics.count(tp)} questions" with the values filled into { } on the screen
99
print("Total:", len(questions))
๐Ÿ–ฅ๏ธ Output Displays the text "Total:", then the value of len(questions) on the screen
Q1. What is personalised learning?

Teaching that adapts to each student's level and weak areas - here the quiz recommends a level and topic.

Q2. Name the stages of the AI project cycle.

Problem Scoping, Data Acquisition, Data Exploration, Modelling, Evaluation (and Deployment).

Q3. What is a false negative?

The model predicts NO but the actual answer is YES.

Q4. How is the weak topic found?

The topic with the lowest right/total ratio using min() with a key.

Q5. Which SDG?

SDG 4 - Quality Education.

06

Preventable Blindness Screening - Model Evaluator (SDG 3)

PYTHONSDG 3 - Good Health and Well-beingparallel listszip()confusion matrix (TPFPTN
๐Ÿ“ 123 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 78 output lines๐Ÿ“„ 25+ page report

Inspired by the CBSE case study 'Preventable Blindness': compares an AI screening model's predictions with doctors' diagnoses for 20 patients, builds the confusion matrix and calculates accuracy, explaining why false negatives are dangerous.

โœจ Features
  • Actual and predicted results of an AI eye-screening model for 20 patients (lists)
  • Confusion matrix TP, FP, TN, FN counted with a loop
  • Accuracy, Precision, Recall and F1 score with explanation
  • Compare two models (Model A vs Model B) and choose the safer one (fewer FN)
  • Threshold experiment: probability scores converted to YES/NO at different thresholds
  • Patient-wise report showing which patients were missed
โ˜ฐ Main menu
1Show DataActual vs predicted for each patient
2Confusion MatrixTP, FP, TN, FN table
3MetricsAccuracy, precision, recall, F1
4Missed PatientsList of FN and FP cases
5Compare ModelsModel A vs Model B
6Threshold ExperimentEffect of threshold on FN / FP
7Ethics NoteWhy FN is dangerous in healthcare
0ExitEnds program
๐ŸŽฏ Objectives
  • Understand TP, FP, TN and FN with a healthcare example
  • Build a confusion matrix using lists and a loop
  • Calculate accuracy and judge whether the model is safe to deploy
๐Ÿ“š Data dictionary
NameTypePurpose
actuallist1 = disease, 0 = healthy (20 patients)
model_a / model_blistsPredictions of two models
scoreslist of floatModel probability of disease
matrix()functionReturns TP, FP, TN, FN
Why it matters: Makes the Evaluation stage of the AI project cycle concrete using a real healthcare scenario.
# =====================================================================
#   PREVENTABLE BLINDNESS SCREENING - MODEL EVALUATOR   (SDG 3)
#   Concepts: lists, zip, loops, functions, confusion matrix, metrics
# =====================================================================
# 1 = has diabetic retinopathy, 0 = healthy  (20 patients P01..P20)
actual  = [1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1]
model_a = [1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1]
model_b = [1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1]
scores  = [.91, .12, .84, .42, .08, .63, .77, .35, .88, .21, .95, .15, .58, .81, .05, .38, .72, .27, .18, .93]
patients = ["P%02d" % i for i in range(1, 21)]


def matrix(act, pred):
    TP = FP = TN = FN = 0
    for a, p in zip(act, pred):
        if a == 1 and p == 1:
            TP += 1
        elif a == 0 and p == 1:
            FP += 1
        elif a == 0 and p == 0:
            TN += 1
        else:
            FN += 1
    return TP, FP, TN, FN


def metrics(TP, FP, TN, FN):
    acc = (TP + TN) / (TP + FP + TN + FN)
    pre = TP / (TP + FP) if TP + FP else 0
    rec = TP / (TP + FN) if TP + FN else 0
    f1 = 2 * pre * rec / (pre + rec) if pre + rec else 0
    return acc, pre, rec, f1


def show_data():
    print("{:<6}{:>8}{:>9}{:>9}".format("Patient", "Actual", "Model A", "Score"))
    for i in range(20):
        mark = "" if actual[i] == model_a[i] else "  <- wrong"
        print("{:<6}{:>8}{:>9}{:>9.2f}{}".format(patients[i], actual[i], model_a[i], scores[i], mark))


def show_matrix():
    TP, FP, TN, FN = matrix(actual, model_a)
    print("                    Reality: Disease   Reality: Healthy")
    print("Predicted Disease        TP =", TP, "          FP =", FP)
    print("Predicted Healthy        FN =", FN, "          TN =", TN)


def show_metrics():
    TP, FP, TN, FN = matrix(actual, model_a)
    acc, pre, rec, f1 = metrics(TP, FP, TN, FN)
    print(f"Accuracy  = (TP+TN)/Total = {TP + TN}/20 = {acc * 100:.1f} %")
    print(f"Precision = TP/(TP+FP)   = {TP}/{TP + FP} = {pre:.2f}")
    print(f"Recall    = TP/(TP+FN)   = {TP}/{TP + FN} = {rec:.2f}")
    print(f"F1 score  = 2PR/(P+R)    = {f1:.2f}")


def missed():
    for i in range(20):
        if actual[i] == 1 and model_a[i] == 0:
            print(patients[i], "- FALSE NEGATIVE: disease missed! (score", scores[i], ")")
        elif actual[i] == 0 and model_a[i] == 1:
            print(patients[i], "- false positive: extra check-up needed")


def compare():
    print("{:<8}{:>4}{:>4}{:>4}{:>4}{:>9}{:>8}".format("Model", "TP", "FP", "TN", "FN", "Accuracy", "Recall"))
    best, best_fn = "", 99
    for name, pred in (("Model A", model_a), ("Model B", model_b)):
        TP, FP, TN, FN = matrix(actual, pred)
        acc, pre, rec, f1 = metrics(TP, FP, TN, FN)
        print("{:<8}{:>4}{:>4}{:>4}{:>4}{:>8.0f}%{:>8.2f}".format(name, TP, FP, TN, FN, acc * 100, rec))
        if FN < best_fn:
            best, best_fn = name, FN
    print("Safer choice for screening:", best, "(fewest missed patients)")


def threshold():
    try:
        t = float(input("Threshold (0-1): "))
    except ValueError:
        print("Invalid value."); return
    pred = [1 if s >= t else 0 for s in scores]
    TP, FP, TN, FN = matrix(actual, pred)
    print(f"Threshold {t}: TP {TP}  FP {FP}  TN {TN}  FN {FN}")
    for th in (0.3, 0.5, 0.7):
        r = matrix(actual, [1 if s >= th else 0 for s in scores])
        print(f"  at {th}: FN = {r[3]}, FP = {r[1]}")
    print("Lower threshold -> fewer missed patients but more false alarms.")


def ethics():
    print("In medical screening a FALSE NEGATIVE means a sick patient is told 'healthy'.")
    print("He may not visit a doctor and can lose eyesight. So we prefer HIGH RECALL,")
    print("and AI should only ASSIST doctors, who re-check every 'healthy' result.")


print("=" * 55)
print("   AI SCREENING MODEL EVALUATOR  (SDG 3)")
print("=" * 55)
while True:
    print("\n1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        show_data()
    elif ch == "2":
        show_matrix()
    elif ch == "3":
        show_metrics()
    elif ch == "4":
        missed()
    elif ch == "5":
        compare()
    elif ch == "6":
        threshold()
    elif ch == "7":
        ethics()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Loop over actual and predicted pairs
  4. actual = 1 and predicted = 1? → No: check FP / TN / FN
  5. Count TP, FP, TN, FN
  6. Compute metrics
  7. Show matrix / metrics
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Confusion matrix Model ATP 8, FP 2, TN 8, FN 2PASS
2Accuracy80 %PASS
3Recall0.8PASS
4Missed patientsP04 and P16PASS
5CompareModel B has fewer FNPASS
6Threshold 0.3FN drops, FP risesPASS
7Threshold 'abc'Invalid valuePASS
โš  Limitations
  • Small sample of 20 patients
  • Predictions given as data (no image model here)
  • Single disease only
  • Thresholds fixed in list
๐Ÿš€ Future scope
  • Train a real CNN on retina images (Class X CV)
  • Use larger public datasets
  • Doctor feedback loop
  • Mobile screening camp app

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: actual, model_a, model_b, scores, patients.
  2. 9 functions are defined (lines 13โ€“95) - Python stores them but does NOT run them yet.
  3. Main program starts at line 98: print("=" * 55) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
matrix(act, pred)13โ€“24Matrixshow_matrix(), show_metrics(), compare(), threshold()
metrics(TP, FP, TN, FN)27โ€“32Metricsshow_metrics(), compare()
show_data()35โ€“39Show datamain program
show_matrix()42โ€“46Show matrixmain program
show_metrics()49โ€“55Show metricsmain program
missed()58โ€“63Missedmain program
compare()66โ€“75Comparemain program
threshold()78โ€“89Thresholdmain program
ethics()92โ€“95Ethicsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
98
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
99
print("   AI SCREENING MODEL EVALUATOR  (SDG 3)")
๐Ÿ–ฅ๏ธ Output Displays the text "AI SCREENING MODEL EVALUATOR (SDGโ€ฆ" on the screen
100
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
101
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
102
print("\n1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Matrix 3.Metrics 4.Misseโ€ฆ" on the screen
103
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
104
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
105
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
106
break
๐Ÿ” Loop BREAK - leaves the loop immediately
107
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
108
show_data()
๐Ÿงฎ Store / Calculate Calls our own function show_data()
109
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
110
show_matrix()
๐Ÿงฎ Store / Calculate Calls our own function show_matrix()
111
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
112
show_metrics()
๐Ÿงฎ Store / Calculate Calls our own function show_metrics()
113
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
114
missed()
๐Ÿงฎ Store / Calculate Calls our own function missed()
115
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
116
compare()
๐Ÿงฎ Store / Calculate Calls our own function compare()
117
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
118
threshold()
๐Ÿงฎ Store / Calculate Calls our own function threshold()
119
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
120
ethics()
๐Ÿงฎ Store / Calculate Calls our own function ethics()
121
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
122
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: AI SCREENING MODEL EVALUATOR (SDG 3) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show_data()
    shows: Patient Actual Model A Score (+21 more lines)
  3. You type 2 at Enter choice:
    runs: show_matrix() โ†’ matrix()
    shows: Reality: Disease Reality: Healthy (+3 more lines)
  4. You type 3 at Enter choice:
    runs: show_metrics() โ†’ matrix() โ†’ metrics()
    shows: Accuracy = (TP+TN)/Total = 16/20 = 80.0 % (+4 more lines)
  5. You type 4 at Enter choice:
    runs: missed()
    shows: P04 - FALSE NEGATIVE: disease missed! (score 0.42 ) (+4 more lines)
  6. You type 5 at Enter choice:
    runs: compare() โ†’ matrix() โ†’ metrics() โ†’ matrix() โ†’ metrics()
    shows: Model TP FP TN FN Accuracy Recall (+4 more lines)
  7. You type 6 at Enter choice:
    runs: threshold()
  8. You type 0.3 at Threshold (0-1):
    runs: matrix() ร—4
    shows: Threshold 0.3: TP 10 FP 3 TN 7 FN 0 (+5 more lines)
  9. You type 6 at Enter choice:
    runs: threshold()
  10. You type abc at Threshold (0-1):
    shows: Invalid value. (+1 more lines)
  11. You type 7 at Enter choice:
    runs: ethics()
    shows: In medical screening a FALSE NEGATIVE means a sick patient is told 'healthy'. (+3 more lines)
  12. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
matrix() - lines 13โ€“24
LineCodeWhat it does
13
def matrix(act, pred):
๐Ÿงฉ Function DEFINES a function matrix(act, pred). Python only remembers it here - its body runs later, each time matrix() is called.
14
TP = FP = TN = FN = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable TP
15
for a, p in zip(act, pred):
๐Ÿ” Loop LOOP that walks through act, pred together; a, p get one item from each
16
if a == 1 and p == 1:
๐Ÿ”€ Decision CHECKS whether (a is equal to 1 AND p is equal to 1). If True, the indented lines below run; otherwise Python jumps to the elif/else part
17
TP += 1
๐Ÿงฎ Store / Calculate Adds 1 to TP (same as TP = TP + 1)
18
elif a == 0 and p == 1:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (a is equal to 0 AND p is equal to 1)
19
FP += 1
๐Ÿงฎ Store / Calculate Adds 1 to FP (same as FP = FP + 1)
20
elif a == 0 and p == 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (a is equal to 0 AND p is equal to 0)
21
TN += 1
๐Ÿงฎ Store / Calculate Adds 1 to TN (same as TN = TN + 1)
22
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
23
FN += 1
๐Ÿงฎ Store / Calculate Adds 1 to FN (same as FN = FN + 1)
24
return TP, FP, TN, FN
๐Ÿงฉ Function Sends back (returns) the tuple TP, FP, TN, FN to the line that called the function
metrics() - lines 27โ€“32
LineCodeWhat it does
27
def metrics(TP, FP, TN, FN):
๐Ÿงฉ Function DEFINES a function metrics(TP, FP, TN, FN). Python only remembers it here - its body runs later, each time metrics() is called.
28
acc = (TP + TN) / (TP + FP + TN + FN)
๐Ÿงฎ Store / Calculate Stores the value of (TP + TN) / (TP + FP + TN + FN) (calculated using รท) in variable acc
29
pre = TP / (TP + FP) if TP + FP else 0
๐Ÿงฎ Store / Calculate Stores either TP / (TP + FP) or 0 depending on TP + FP in variable pre
30
rec = TP / (TP + FN) if TP + FN else 0
๐Ÿงฎ Store / Calculate Stores either TP / (TP + FN) or 0 depending on TP + FN in variable rec
31
f1 = 2 * pre * rec / (pre + rec) if pre + rec else 0
๐Ÿงฎ Store / Calculate Stores either 2 * pre * rec / (pre + rec) or 0 depending on pre + rec in variable f1
32
return acc, pre, rec, f1
๐Ÿงฉ Function Sends back (returns) the tuple acc, pre, rec, f1 to the line that called the function
show_data() - lines 35โ€“39
LineCodeWhat it does
35
def show_data():
๐Ÿงฉ Function DEFINES a function show_data(). Python only remembers it here - its body runs later, each time show_data() is called.
36
print("{:<6}{:>8}{:>9}{:>9}".format("Patient", "Actual", "Model A", "Score"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<6}{:>8}{:>9}{:>9}".format("Patient", "Actโ€ฆ on the screen
37
for i in range(20):
๐Ÿ” Loop LOOP: gives the numbers 0 to 19 (20 numbers); for each number, i takes that value and the indented block runs once
38
mark = "" if actual[i] == model_a[i] else "  <- wrong"
๐Ÿงฎ Store / Calculate Stores either "" or " <- wrong" depending on actual[i] == model_a[i] in variable mark
39
print("{:<6}{:>8}{:>9}{:>9.2f}{}".format(patients[i], actual[i], model_a[i], scores[i], mark))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<6}{:>8}{:>9}{:>9.2f}{}".format(patients[iโ€ฆ on the screen
show_matrix() - lines 42โ€“46
LineCodeWhat it does
42
def show_matrix():
๐Ÿงฉ Function DEFINES a function show_matrix(). Python only remembers it here - its body runs later, each time show_matrix() is called.
43
TP, FP, TN, FN = matrix(actual, model_a)
๐Ÿงฎ Store / Calculate Calls our own function matrix(actual, model_a); the result is stored in variables TP, FP, TN, FN
44
print("                    Reality: Disease   Reality: Healthy")
๐Ÿ–ฅ๏ธ Output Displays the text "Reality: Disease Reality: Healthy" on the screen
45
print("Predicted Disease        TP =", TP, "          FP =", FP)
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted Disease TP =", then the value of TP, then the text "FP =", then the value of FP on the screen
46
print("Predicted Healthy        FN =", FN, "          TN =", TN)
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted Healthy FN =", then the value of FN, then the text "TN =", then the value of TN on the screen
show_metrics() - lines 49โ€“55
LineCodeWhat it does
49
def show_metrics():
๐Ÿงฉ Function DEFINES a function show_metrics(). Python only remembers it here - its body runs later, each time show_metrics() is called.
50
TP, FP, TN, FN = matrix(actual, model_a)
๐Ÿงฎ Store / Calculate Calls our own function matrix(actual, model_a); the result is stored in variables TP, FP, TN, FN
51
acc, pre, rec, f1 = metrics(TP, FP, TN, FN)
๐Ÿงฎ Store / Calculate Calls our own function metrics(TP, FP, TN, FN); the result is stored in variables acc, pre, rec, f1
52
print(f"Accuracy  = (TP+TN)/Total = {TP + TN}/20 = {acc * 100:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Accuracy = (TP+TN)/Total = {TP + TN}/20 = {โ€ฆ with the values filled into { } on the screen
53
print(f"Precision = TP/(TP+FP)   = {TP}/{TP + FP} = {pre:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Precision = TP/(TP+FP) = {TP}/{TP + FP} = {โ€ฆ with the values filled into { } on the screen
54
print(f"Recall    = TP/(TP+FN)   = {TP}/{TP + FN} = {rec:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Recall = TP/(TP+FN) = {TP}/{TP + FN} = {recโ€ฆ with the values filled into { } on the screen
55
print(f"F1 score  = 2PR/(P+R)    = {f1:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"F1 score = 2PR/(P+R) = {f1:.2f}" with the values filled into { } on the screen
missed() - lines 58โ€“63
LineCodeWhat it does
58
def missed():
๐Ÿงฉ Function DEFINES a function missed(). Python only remembers it here - its body runs later, each time missed() is called.
59
for i in range(20):
๐Ÿ” Loop LOOP: gives the numbers 0 to 19 (20 numbers); for each number, i takes that value and the indented block runs once
60
if actual[i] == 1 and model_a[i] == 0:
๐Ÿ”€ Decision CHECKS whether (actual[i] is equal to 1 AND model_a[i] is equal to 0). If True, the indented lines below run; otherwise Python jumps to the elif/else part
61
print(patients[i], "- FALSE NEGATIVE: disease missed! (score", scores[i], ")")
๐Ÿ–ฅ๏ธ Output Displays the value of patients[i], then the text "- FALSE NEGATIVE: disease missed!โ€ฆ", then the value of scores[i], then the text ")" on the screen
62
elif actual[i] == 0 and model_a[i] == 1:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (actual[i] is equal to 0 AND model_a[i] is equal to 1)
63
print(patients[i], "- false positive: extra check-up needed")
๐Ÿ–ฅ๏ธ Output Displays the value of patients[i], then the text "- false positive: extra check-up โ€ฆ" on the screen
compare() - lines 66โ€“75
LineCodeWhat it does
66
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
67
print("{:<8}{:>4}{:>4}{:>4}{:>4}{:>9}{:>8}".format("Model", "TP", "FP", "TN", "FN", "Accuracy", "Recall"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>4}{:>4}{:>4}{:>4}{:>9}{:>8}".format(โ€ฆ on the screen
68
best, best_fn = "", 99
๐Ÿงฎ Store / Calculate Stores "", 99 into best, best_fn respectively
69
for name, pred in (("Model A", model_a), ("Model B", model_b)):
๐Ÿ” Loop LOOP: takes each item of (("Model A", model_a), ("Model B", model_b)) one-by-one into name, pred and runs the indented block for it
70
TP, FP, TN, FN = matrix(actual, pred)
๐Ÿงฎ Store / Calculate Calls our own function matrix(actual, pred); the result is stored in variables TP, FP, TN, FN
71
acc, pre, rec, f1 = metrics(TP, FP, TN, FN)
๐Ÿงฎ Store / Calculate Calls our own function metrics(TP, FP, TN, FN); the result is stored in variables acc, pre, rec, f1
72
print("{:<8}{:>4}{:>4}{:>4}{:>4}{:>8.0f}%{:>8.2f}".format(name, TP, FP, TN, FN, acc * 100, rec))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>4}{:>4}{:>4}{:>4}{:>8.0f}%{:>8.2f}".โ€ฆ on the screen
73
if FN < best_fn:
๐Ÿ”€ Decision CHECKS whether FN is less than best_fn. If True, the indented lines below run; otherwise they are skipped
74
best, best_fn = name, FN
๐Ÿงฎ Store / Calculate Stores name, FN into best, best_fn respectively
75
print("Safer choice for screening:", best, "(fewest missed patients)")
๐Ÿ–ฅ๏ธ Output Displays the text "Safer choice for screening:", then the value of best, then the text "(fewest missed patients)" on the screen
threshold() - lines 78โ€“89
LineCodeWhat it does
78
def threshold():
๐Ÿงฉ Function DEFINES a function threshold(). Python only remembers it here - its body runs later, each time threshold() is called.
79
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
80
t = float(input("Threshold (0-1): "))
โŒจ๏ธ Input Shows "Threshold (0-1): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable t
81
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
82
print("Invalid value."); return
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid value." on the screen
82
print("Invalid value."); return
๐Ÿ–ฅ๏ธ Output Ends the function and goes back to the caller
83
pred = [1 if s >= t else 0 for s in scores]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [1 if s >= t else 0 for s in scores] in variable pred
84
TP, FP, TN, FN = matrix(actual, pred)
๐Ÿงฎ Store / Calculate Calls our own function matrix(actual, pred); the result is stored in variables TP, FP, TN, FN
85
print(f"Threshold {t}: TP {TP}  FP {FP}  TN {TN}  FN {FN}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Threshold {t}: TP {TP} FP {FP} TN {TN} FN {โ€ฆ with the values filled into { } on the screen
86
for th in (0.3, 0.5, 0.7):
๐Ÿ” Loop LOOP: takes each item of (0.3, 0.5, 0.7) one-by-one into th and runs the indented block for it
87
r = matrix(actual, [1 if s >= th else 0 for s in scores])
๐Ÿงฎ Store / Calculate Calls our own function matrix(actual, [1 if s >= th else โ€ฆ); the result is stored in variable r
88
print(f"  at {th}: FN = {r[3]}, FP = {r[1]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" at {th}: FN = {r[3]}, FP = {r[1]}" with the values filled into { } on the screen
89
print("Lower threshold -> fewer missed patients but more false alarms.")
๐Ÿ–ฅ๏ธ Output Displays the text "Lower threshold -> fewer missed pโ€ฆ" on the screen
ethics() - lines 92โ€“95
LineCodeWhat it does
92
def ethics():
๐Ÿงฉ Function DEFINES a function ethics(). Python only remembers it here - its body runs later, each time ethics() is called.
93
print("In medical screening a FALSE NEGATIVE means a sick patient is told 'healthy'.")
๐Ÿ–ฅ๏ธ Output Displays the text "In medical screening a FALSE NEGAโ€ฆ" on the screen
94
print("He may not visit a doctor and can lose eyesight. So we prefer HIGH RECALL,")
๐Ÿ–ฅ๏ธ Output Displays the text "He may not visit a doctor and canโ€ฆ" on the screen
95
print("and AI should only ASSIST doctors, who re-check every 'healthy' result.")
๐Ÿ–ฅ๏ธ Output Displays the text "and AI should only ASSIST doctorsโ€ฆ" on the screen
Q1. What is a confusion matrix?

A 2x2 table comparing predictions with reality: TP, FP, FN, TN.

Q2. Why is recall important here?

Recall = TP/(TP+FN); low recall means sick patients are missed, which can cause blindness.

Q3. What is precision?

TP/(TP+FP) - of all patients the model called sick, how many were really sick.

Q4. What happens if the threshold is lowered?

More patients are called 'disease' - FN falls but FP rises.

Q5. Which SDG?

SDG 3 - Good Health and Well-being.

07

Top 10 Songs Data Explorer

PYTHONSDG 4 - Quality Education (data literacy)listssorting with zip()string formattingtext bar chartaverage
๐Ÿ“ 95 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 88 output lines๐Ÿ“„ 25+ page report

Based on the CBSE 'Top 10 Song Prediction' activity: stores song names, weekly streams and likes, ranks the songs, draws a text bar chart, finds songs above average and predicts the next week's top song using a simple trend rule.

โœจ Features
  • Streams of 10 songs for last week and this week (lists)
  • Ranking with sorted() and a text bar chart
  • Growth % for every song and fastest-growing song
  • Genre-wise totals and average
  • Search a song and compare two weeks
  • Prediction of next week's No. 1 using a simple growth rule; add new song entry
โ˜ฐ Main menu
1This Week's ChartRanked table with bars
2Growth ReportGrowth % and movers
3Above AverageSongs above mean streams
4Genre SummaryTotals by genre
5Search SongDetails of one song
6Predict Next WeekGrowth-based prediction
7Add New SongAppends to lists
0ExitEnds program
๐ŸŽฏ Objectives
  • Identify data features that affect song popularity
  • Rank and visualise data using lists and a text bar chart
  • Make a simple prediction from the growth trend
๐Ÿ“š Data dictionary
NameTypePurpose
songs, genrelistsSong names and genre
last_week, this_weeklistsMillion streams
growthlistGrowth % calculated
Why it matters: Develops data-feature thinking - which features (streams, likes, growth) can predict popularity.
# =====================================================================
#   TOP 10 SONGS DATA EXPLORER
#   Concepts: lists, zip, sorted, functions, list comprehension, menu
# =====================================================================
songs = ["Song A", "Song B", "Song C", "Song D", "Song E", "Song F", "Song G", "Song H", "Song I", "Song J"]
genre = ["Pop", "Folk", "Pop", "Indie", "Rap", "Folk", "Indie", "Pop", "Rap", "Pop"]
last_week = [12.0, 9.5, 15.2, 7.8, 11.0, 6.5, 8.9, 10.2, 5.0, 13.1]   # million streams
this_week = [13.1, 12.4, 14.8, 7.9, 11.6, 9.1, 8.2, 11.9, 7.0, 13.5]


def growth(i):
    return round((this_week[i] - last_week[i]) / last_week[i] * 100, 1)


def chart():
    ranked = sorted(zip(this_week, songs, genre), reverse=True)
    print("{:<5}{:<8}{:<7}{:>9}{:>9}  Chart".format("Rank", "Song", "Genre", "Streams", "Growth"))
    for r, (s, name, g) in enumerate(ranked, start=1):
        print("{:<5}{:<8}{:<7}{:>8}M{:>8}%  {}".format(r, name, g, s, growth(songs.index(name)), "|" * int(s)))


def growth_report():
    gr = [growth(i) for i in range(len(songs))]
    for i in range(len(songs)):
        arrow = "UP  " if gr[i] > 0 else "DOWN"
        print(f"{songs[i]:<8} {last_week[i]:>5} -> {this_week[i]:>5}  {arrow} {gr[i]:>6}%")
    print("Fastest growing:", songs[gr.index(max(gr))], "(+" + str(max(gr)) + "%)")
    print("Biggest fall   :", songs[gr.index(min(gr))], "(" + str(min(gr)) + "%)")


def above():
    avg = sum(this_week) / len(this_week)
    print("Average streams:", round(avg, 2), "million")
    print("Above average  :", [songs[i] for i in range(len(songs)) if this_week[i] > avg])


def genres():
    seen = []
    for g in genre:
        if g not in seen:
            seen.append(g)
    print("{:<7}{:>6}{:>10}{:>9}".format("Genre", "Songs", "Streams", "Average"))
    for g in seen:
        vals = [this_week[i] for i in range(len(songs)) if genre[i] == g]
        print("{:<7}{:>6}{:>10.1f}{:>9.2f}".format(g, len(vals), sum(vals), sum(vals) / len(vals)))


def search():
    s = input("Song name: ").strip()
    if s in songs:
        i = songs.index(s)
        print(f"{s} ({genre[i]}): last week {last_week[i]}M, this week {this_week[i]}M, growth {growth(i)}%")
    else:
        print("Song not found.")


def predict():
    pred = [this_week[i] * (1 + growth(i) / 100) for i in range(len(songs))]
    order = sorted(zip(pred, songs), reverse=True)[:3]
    for r, (p, s) in enumerate(order, 1):
        print(f"Predicted No.{r}: {s} with about {p:.1f} M streams")


def add():
    songs.append(input("Song name: ")); genre.append(input("Genre: "))
    last_week.append(float(input("Last week streams (M): "))); this_week.append(float(input("This week streams (M): ")))
    print("Added. Songs in chart data:", len(songs))


print("=" * 50)
print("   TOP SONGS DATA EXPLORER")
print("=" * 50)
while True:
    print("\n1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Keep listening!")
        break
    elif ch == "1":
        chart()
    elif ch == "2":
        growth_report()
    elif ch == "3":
        above()
    elif ch == "4":
        genres()
    elif ch == "5":
        search()
    elif ch == "6":
        predict()
    elif ch == "7":
        add()
    else:
        print("Invalid choice")

        
  1. Start
  2. Calculate growth list
  3. Show menu and read choice
  4. Choice valid? → No: 'Invalid choice'
  5. Sort / filter / predict
  6. Show result
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1ChartSong C No. 1PASS
2GrowthSong F +40 %PASS
3Above averageList of songsPASS
4Genre summaryPop, Folk, Indie, RapPASS
5Search 'Song E'DetailsPASS
6Search 'Song Z'Not foundPASS
7PredictNext No. 1PASS
8Add songList grows to 11PASS
โš  Limitations
  • Simple linear growth rule
  • Two weeks of data only
  • Song names are placeholders
  • No real streaming API
๐Ÿš€ Future scope
  • Fetch real chart data
  • Use regression over many weeks
  • Matplotlib charts
  • Recommend songs to users (Data Science domain)

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: songs, genre, last_week, this_week.
  2. 8 functions are defined (lines 11โ€“67) - Python stores them but does NOT run them yet.
  3. Main program starts at line 70: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
growth(i)11โ€“12Growthchart(), growth_report(), search(), predict()
chart()15โ€“19Chartmain program
growth_report()22โ€“28Growth reportmain program
above()31โ€“34Abovemain program
genres()37โ€“45Genresmain program
search()48โ€“54Searchmain program
predict()57โ€“61Predictmain program
add()64โ€“67Addmain program
โ‘ข Main program - line by line
LineCodeWhat it does
70
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
71
print("   TOP SONGS DATA EXPLORER")
๐Ÿ–ฅ๏ธ Output Displays the text "TOP SONGS DATA EXPLORER" on the screen
72
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
73
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
74
print("\n1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Chart 2.Growth 3.Above Avg 4.Geโ€ฆ" on the screen
75
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
76
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
77
print("Keep listening!")
๐Ÿ–ฅ๏ธ Output Displays the text "Keep listening!" on the screen
78
break
๐Ÿ” Loop BREAK - leaves the loop immediately
79
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
80
chart()
๐Ÿงฎ Store / Calculate Calls our own function chart()
81
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
82
growth_report()
๐Ÿงฎ Store / Calculate Calls our own function growth_report()
83
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
84
above()
๐Ÿงฎ Store / Calculate Calls our own function above()
85
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
86
genres()
๐Ÿงฎ Store / Calculate Calls our own function genres()
87
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
88
search()
๐Ÿงฎ Store / Calculate Calls our own function search()
89
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
90
predict()
๐Ÿงฎ Store / Calculate Calls our own function predict()
91
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
92
add()
๐Ÿงฎ Store / Calculate Calls our own function add()
93
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
94
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: TOP SONGS DATA EXPLORER (+1 more lines)
  2. You type 1 at Enter choice:
    runs: chart() โ†’ growth() ร—10
    shows: Rank Song Genre Streams Growth Chart (+11 more lines)
  3. You type 2 at Enter choice:
    runs: growth_report() โ†’ growth() ร—10
    shows: Song A 12.0 -> 13.1 UP 9.2% (+12 more lines)
  4. You type 3 at Enter choice:
    runs: above()
    shows: Average streams: 10.95 million (+2 more lines)
  5. You type 4 at Enter choice:
    runs: genres()
    shows: Genre Songs Streams Average (+5 more lines)
  6. You type 5 at Enter choice:
    runs: search()
  7. You type Song E at Song name:
    runs: growth()
    shows: Song E (Rap): last week 11.0M, this week 11.6M, growth 5.5% (+1 more lines)
  8. You type 5 at Enter choice:
    runs: search()
  9. You type Song Z at Song name:
    shows: Song not found. (+1 more lines)
  10. You type 6 at Enter choice:
    runs: predict() โ†’ growth() ร—10
    shows: Predicted No.1: Song B with about 16.2 M streams (+3 more lines)
  11. You type 7 at Enter choice:
    runs: add()
  12. You type Song K at Song name:
  13. You type Indie at Genre:
  14. You type 4.2 at Last week streams (M):
  15. You type 8.8 at This week streams (M):
    shows: Added. Songs in chart data: 11 (+1 more lines)
  16. You type 1 at Enter choice:
    runs: chart() โ†’ growth() ร—11
    shows: Rank Song Genre Streams Growth Chart (+12 more lines)
  17. You type 0 at Enter choice:
    shows: Keep listening!
โ‘ค Inside each function - line by line
growth() - lines 11โ€“12
LineCodeWhat it does
11
def growth(i):
๐Ÿงฉ Function DEFINES a function growth(i). Python only remembers it here - its body runs later, each time growth() is called.
12
return round((this_week[i] - last_week[i]) / last_week[i] * 100, 1)
๐Ÿงฉ Function Sends back (returns) the result of: rounds (this_week[i] - last_week[i]) / last_week[i] โ€ฆ to 1 decimal places to the line that called the function
chart() - lines 15โ€“19
LineCodeWhat it does
15
def chart():
๐Ÿงฉ Function DEFINES a function chart(). Python only remembers it here - its body runs later, each time chart() is called.
16
ranked = sorted(zip(this_week, songs, genre), reverse=True)
๐Ÿงฎ Store / Calculate Makes a new sorted list from zip(this_week, songs, genre); the result is stored in variable ranked
17
print("{:<5}{:<8}{:<7}{:>9}{:>9}  Chart".format("Rank", "Song", "Genre", "Streams", "Growth"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<5}{:<8}{:<7}{:>9}{:>9} Chart".format("Ranโ€ฆ on the screen
18
for r, (s, name, g) in enumerate(ranked, start=1):
๐Ÿ” Loop LOOP over ranked with position: in each round r, (s, name, g) get (position, item)
19
print("{:<5}{:<8}{:<7}{:>8}M{:>8}%  {}".format(r, name, g, s, growth(songs.index(name)), "|" * int(s)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<5}{:<8}{:<7}{:>8}M{:>8}% {}".format(r, naโ€ฆ on the screen
growth_report() - lines 22โ€“28
LineCodeWhat it does
22
def growth_report():
๐Ÿงฉ Function DEFINES a function growth_report(). Python only remembers it here - its body runs later, each time growth_report() is called.
23
gr = [growth(i) for i in range(len(songs))]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [growth(i) for i in range(len(songs))] in variable gr
24
for i in range(len(songs)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(songs) - 1; for each number, i takes that value and the indented block runs once
25
arrow = "UP  " if gr[i] > 0 else "DOWN"
๐Ÿงฎ Store / Calculate Stores either "UP " or "DOWN" depending on gr[i] > 0 in variable arrow
26
print(f"{songs[i]:<8} {last_week[i]:>5} -> {this_week[i]:>5}  {arrow} {gr[i]:>6}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{songs[i]:<8} {last_week[i]:>5} -> {this_weโ€ฆ with the values filled into { } on the screen
27
print("Fastest growing:", songs[gr.index(max(gr))], "(+" + str(max(gr)) + "%)")
๐Ÿ–ฅ๏ธ Output Displays the text "Fastest growing:", then the value of songs[gr.index(max(gr))], then the value of "(+" + str(max(gr)) + "%)" on the screen
28
print("Biggest fall   :", songs[gr.index(min(gr))], "(" + str(min(gr)) + "%)")
๐Ÿ–ฅ๏ธ Output Displays the text "Biggest fall :", then the value of songs[gr.index(min(gr))], then the value of "(" + str(min(gr)) + "%)" on the screen
above() - lines 31โ€“34
LineCodeWhat it does
31
def above():
๐Ÿงฉ Function DEFINES a function above(). Python only remembers it here - its body runs later, each time above() is called.
32
avg = sum(this_week) / len(this_week)
๐Ÿงฎ Store / Calculate Stores the value of sum(this_week) / len(this_week) (calculated using รท) in variable avg
33
print("Average streams:", round(avg, 2), "million")
๐Ÿ–ฅ๏ธ Output Displays the text "Average streams:", then the value of round(avg, 2), then the text "million" on the screen
34
print("Above average  :", [songs[i] for i in range(len(songs)) if this_week[i] > avg])
๐Ÿ–ฅ๏ธ Output Displays the text "Above average :", then the value of [songs[i] for i in range(len(songs)) if this_โ€ฆ on the screen
genres() - lines 37โ€“45
LineCodeWhat it does
37
def genres():
๐Ÿงฉ Function DEFINES a function genres(). Python only remembers it here - its body runs later, each time genres() is called.
38
seen = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable seen
39
for g in genre:
๐Ÿ” Loop LOOP: takes each item of genre one-by-one into g and runs the indented block for it
40
if g not in seen:
๐Ÿ”€ Decision CHECKS whether g is not present in seen. If True, the indented lines below run; otherwise they are skipped
41
seen.append(g)
๐Ÿงฎ Store / Calculate Adds g at the end of list seen
42
print("{:<7}{:>6}{:>10}{:>9}".format("Genre", "Songs", "Streams", "Average"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<7}{:>6}{:>10}{:>9}".format("Genre", "Songโ€ฆ on the screen
43
for g in seen:
๐Ÿ” Loop LOOP: takes each item of seen one-by-one into g and runs the indented block for it
44
vals = [this_week[i] for i in range(len(songs)) if genre[i] == g]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [this_week[i] for i in range(len(songs)) if gโ€ฆ in variable vals
45
print("{:<7}{:>6}{:>10.1f}{:>9.2f}".format(g, len(vals), sum(vals), sum(vals) / len(vals)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<7}{:>6}{:>10.1f}{:>9.2f}".format(g, len(vโ€ฆ on the screen
search() - lines 48โ€“54
LineCodeWhat it does
48
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
49
s = input("Song name: ").strip()
โŒจ๏ธ Input Shows "Song name: ", reads the typed text, removes extra spaces (strip) and stores it in variable s
50
if s in songs:
๐Ÿ”€ Decision CHECKS whether s is present in songs. If True, the indented lines below run; otherwise Python jumps to the elif/else part
51
i = songs.index(s)
๐Ÿงฎ Store / Calculate Gives the position of s in songs; the result is stored in variable i
52
print(f"{s} ({genre[i]}): last week {last_week[i]}M, this week {this_week[i]}M, growth {growth(i)}%")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{s} ({genre[i]}): last week {last_week[i]}Mโ€ฆ with the values filled into { } on the screen
53
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
54
print("Song not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Song not found." on the screen
predict() - lines 57โ€“61
LineCodeWhat it does
57
def predict():
๐Ÿงฉ Function DEFINES a function predict(). Python only remembers it here - its body runs later, each time predict() is called.
58
pred = [this_week[i] * (1 + growth(i) / 100) for i in range(len(songs))]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [this_week[i] * (1 + growth(i) / 100) for i iโ€ฆ in variable pred
59
order = sorted(zip(pred, songs), reverse=True)[:3]
๐Ÿงฎ Store / Calculate Stores a slice sorted(zip(pred, songs), reverse=True)[:3] (part of sorted(zip(pred, songs), reverse=True)) in variable order
60
for r, (p, s) in enumerate(order, 1):
๐Ÿ” Loop LOOP over order with position: in each round r, (p, s) get (position, item)
61
print(f"Predicted No.{r}: {s} with about {p:.1f} M streams")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Predicted No.{r}: {s} with about {p:.1f} M โ€ฆ with the values filled into { } on the screen
add() - lines 64โ€“67
LineCodeWhat it does
64
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
65
songs.append(input("Song name: ")); genre.append(input("Genre: "))
โŒจ๏ธ Input Adds input("Song name: ") at the end of list songs
65
songs.append(input("Song name: ")); genre.append(input("Genre: "))
โŒจ๏ธ Input Adds input("Genre: ") at the end of list genre
66
last_week.append(float(input("Last week streams (M): "))); this_week.append(float(input("This week streams (M): ")))
โŒจ๏ธ Input Adds float(input("Last week streams (M): ")) at the end of list last_week
66
last_week.append(float(input("Last week streams (M): "))); this_week.append(float(input("This week streams (M): ")))
โŒจ๏ธ Input Adds float(input("This week streams (M): ")) at the end of list this_week
67
print("Added. Songs in chart data:", len(songs))
๐Ÿ–ฅ๏ธ Output Displays the text "Added. Songs in chart data:", then the value of len(songs) on the screen
Q1. How is growth % calculated?

(this week - last week) / last week x 100.

Q2. How are songs ranked?

sorted(zip(this_week, songs), reverse=True) sorts by streams in descending order.

Q3. What is zip()?

It pairs items of several lists position-wise.

Q4. Which AI domain does this belong to?

Data Science - learning patterns from numbers.

Q5. Is the prediction always correct?

No - it assumes growth continues; real models use more data and features.

08

Family Health & BMI Advisor (SDG 3)

PYTHONSDG 3 - Good Health and Well-beingwhile looplistsfunctions-free arithmeticif-elif categoriescounting
๐Ÿ“ 103 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 99 output lines๐Ÿ“„ 25+ page report

Calculates the Body Mass Index (BMI) of each family member from height and weight, classifies it into categories, counts members in each category and gives general healthy-lifestyle tips.

โœจ Features
  • BMI of every family member from height and weight
  • Category (Underweight / Normal / Overweight / Obese) with healthy weight range for the height
  • Daily calorie need estimate (Mifflin-St Jeor) with activity level
  • Water intake suggestion (35 ml per kg)
  • Family summary: category counts and average BMI
  • Personal tips based on category
โ˜ฐ Main menu
1Add MemberName, age, gender, height, weight, activity
2BMI TableBMI and category for all
3Healthy Weight RangeFor each member's height
4Calorie & Water NeedsPer member estimate
5Family SummaryCounts and average
6Personal TipsTips by category
0ExitEnds program
๐ŸŽฏ Objectives
  • Calculate BMI using arithmetic expressions
  • Classify values into categories with if-elif rules
  • Summarise categories with counters and give advice
๐Ÿ“š Data dictionary
NameTypePurpose
names, ages, genders, hts, wts, actslistsMember details
bmi()functionweight / (height in m)^2
category()functionBMI class
FACTORlistActivity multipliers 1.2 / 1.55 / 1.75
Why it matters: Uses data to promote healthy habits and shows classification using threshold rules.
# =====================================================================
#   FAMILY HEALTH & BMI ADVISOR   (SDG 3 : Good Health and Well-being)
#   Concepts: lists, functions, if-elif ladder, loops, menu
# =====================================================================
names, ages, genders, hts, wts, acts = [], [], [], [], [], []
FACTOR = [1.2, 1.55, 1.75]          # 1 sedentary, 2 moderate, 3 active
TIPS = {"Underweight": "Eat protein-rich food (dal, paneer, eggs), add healthy snacks, do strength exercise.",
        "Normal": "Great! Keep 60 min activity, balanced meals and 8 hours sleep.",
        "Overweight": "Walk 45 min daily, avoid sugary drinks and fried snacks, eat more salad.",
        "Obese": "Consult a doctor, plan diet with a nutritionist, start with light daily walks."}


def bmi(i):
    return round(wts[i] / (hts[i] / 100) ** 2, 1)


def category(b):
    if b < 18.5:
        return "Underweight"
    elif b < 25:
        return "Normal"
    elif b < 30:
        return "Overweight"
    return "Obese"


def add():
    name = input("Name        : ")
    age = int(input("Age         : "))
    g = input("Gender M/F  : ").upper()
    h = float(input("Height (cm) : "))
    w = float(input("Weight (kg) : "))
    if h <= 50 or w <= 0:
        print("Invalid height / weight. Member not added.")
        return
    a = int(input("Activity 1-Sedentary 2-Moderate 3-Active: "))
    names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
    print(f"{name} added. BMI = {bmi(len(names) - 1)}")


def table():
    print("{:<8}{:>5}{:>8}{:>8}{:>7}  {}".format("Name", "Age", "Ht(cm)", "Wt(kg)", "BMI", "Category"))
    print("-" * 50)
    for i in range(len(names)):
        print("{:<8}{:>5}{:>8.0f}{:>8.0f}{:>7}  {}".format(names[i], ages[i], hts[i], wts[i], bmi(i), category(bmi(i))))


def ranges():
    for i in range(len(names)):
        m = hts[i] / 100
        lo, hi = 18.5 * m * m, 24.9 * m * m
        diff = wts[i] - hi if wts[i] > hi else wts[i] - lo if wts[i] < lo else 0
        note = "in range" if diff == 0 else f"{abs(diff):.1f} kg {'above' if diff > 0 else 'below'}"
        print(f"{names[i]:<8} healthy weight {lo:.1f} - {hi:.1f} kg  ({note})")


def needs():
    for i in range(len(names)):
        base = 10 * wts[i] + 6.25 * hts[i] - 5 * ages[i] + (5 if genders[i] == "M" else -161)
        cal = base * FACTOR[acts[i] - 1]
        print(f"{names[i]:<8} calories ~{cal:.0f} kcal/day | water ~{wts[i] * 0.035:.1f} L/day")


def summary():
    cats = [category(bmi(i)) for i in range(len(names))]
    for c in ["Underweight", "Normal", "Overweight", "Obese"]:
        print(f"{c:<12}: {cats.count(c)}  " + "*" * cats.count(c))
    print("Family average BMI:", round(sum(bmi(i) for i in range(len(names))) / len(names), 1))


def tips():
    for i in range(len(names)):
        c = category(bmi(i))
        print(f"{names[i]} ({c}): {TIPS[c]}")
    print("Note: general tips only - consult a doctor for medical advice.")


print("=" * 50)
print("   FAMILY HEALTH & BMI ADVISOR  (SDG 3)")
print("=" * 50)
while True:
    print("\n1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Stay healthy!")
        break
    elif ch == "1":
        add()
    elif len(names) == 0:
        print("Add members first.")
    elif ch == "2":
        table()
    elif ch == "3":
        ranges()
    elif ch == "4":
        needs()
    elif ch == "5":
        summary()
    elif ch == "6":
        tips()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Add? → No: check members exist
  4. Read member details
  5. BMI = weight / height^2
  6. BMI < 18.5? → No: check other categories
  7. Show table / tips
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Papa 170 cm 92 kgBMI 31.8 ObesePASS
2Mummy 160/6625.8 OverweightPASS
3Riya 150/4017.8 UnderweightPASS
4Height 0'Invalid height'PASS
5Healthy range 170 cm53.5-72.0 kgPASS
6CaloriesEstimate per memberPASS
7SummaryCounts and averagePASS
โš  Limitations
  • BMI does not separate muscle and fat
  • Adult cut-offs used for teenagers (approximation)
  • Not medical advice
  • Formula-based estimates
๐Ÿš€ Future scope
  • Age-wise BMI percentiles for children
  • Track weight every month in a file
  • Diet plan chatbot
  • Fitness band data import

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: FACTOR, TIPS.
  2. 8 functions are defined (lines 13โ€“75) - Python stores them but does NOT run them yet.
  3. Main program starts at line 5: names, ages, genders, hts, wts, acts = [], [], [], [], [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
bmi(i)13โ€“14Bmiadd(), table(), summary(), tips()
category(b)17โ€“24Categorytable(), summary(), tips()
add()27โ€“38Addmain program
table()41โ€“45Tablemain program
ranges()48โ€“54Rangesmain program
needs()57โ€“61Needsmain program
summary()64โ€“68Summarymain program
tips()71โ€“75Tipsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
5
names, ages, genders, hts, wts, acts = [], [], [], [], [], []
๐Ÿงฎ Store / Calculate Stores [], [], [], [], [], [] into names, ages, genders, hts, wts, acts respectively
6
FACTOR = [1.2, 1.55, 1.75]          # 1 sedentary, 2 moderate, 3 active
๐Ÿงฎ Store / Calculate Stores a list [1.2, 1.55, 1.75] in variable FACTOR
7
TIPS = {"Underweight": "Eat protein-rich food (dal, paneer, eggs), add healthy snacks, do strength exercise.",
        "Normal": "Great! Keep 60 min activityโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Underweight": "Eat protein-rich food (dal, โ€ฆ in variable TIPS
78
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
79
print("   FAMILY HEALTH & BMI ADVISOR  (SDG 3)")
๐Ÿ–ฅ๏ธ Output Displays the text "FAMILY HEALTH & BMI ADVISOR (SDG โ€ฆ" on the screen
80
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
81
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
82
print("\n1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Add Member 2.BMI Table 3.Healthโ€ฆ" on the screen
83
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
84
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
85
print("Stay healthy!")
๐Ÿ–ฅ๏ธ Output Displays the text "Stay healthy!" on the screen
86
break
๐Ÿ” Loop BREAK - leaves the loop immediately
87
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
88
add()
๐Ÿงฎ Store / Calculate Calls our own function add()
89
elif len(names) == 0:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether len(names) is equal to 0
90
print("Add members first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Add members first." on the screen
91
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
92
table()
๐Ÿงฎ Store / Calculate Calls our own function table()
93
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
94
ranges()
๐Ÿงฎ Store / Calculate Calls our own function ranges()
95
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
96
needs()
๐Ÿงฎ Store / Calculate Calls our own function needs()
97
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
98
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
99
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
100
tips()
๐Ÿงฎ Store / Calculate Calls our own function tips()
101
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
102
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: FAMILY HEALTH & BMI ADVISOR (SDG 3) (+1 more lines)
  2. You type 2 at Enter choice:
    shows: Add members first. (+1 more lines)
  3. You type 1 at Enter choice:
    runs: add()
  4. You type Papa at Name :
  5. You type 45 at Age :
  6. You type M at Gender M/F :
  7. You type 170 at Height (cm) :
  8. You type 92 at Weight (kg) :
  9. You type 1 at Activity 1-Sedentary 2-Moderate 3-Active:
    runs: bmi()
    shows: Papa added. BMI = 31.8 (+1 more lines)
  10. You type 1 at Enter choice:
    runs: add()
  11. You type Mummy at Name :
  12. You type 42 at Age :
  13. You type F at Gender M/F :
  14. You type 160 at Height (cm) :
  15. You type 66 at Weight (kg) :
  16. You type 2 at Activity 1-Sedentary 2-Moderate 3-Active:
    runs: bmi()
    shows: Mummy added. BMI = 25.8 (+1 more lines)
  17. You type 1 at Enter choice:
    runs: add()
  18. You type Riya at Name :
  19. You type 15 at Age :
  20. You type F at Gender M/F :
  21. You type 150 at Height (cm) :
  22. You type 40 at Weight (kg) :
  23. You type 3 at Activity 1-Sedentary 2-Moderate 3-Active:
    runs: bmi()
    shows: Riya added. BMI = 17.8 (+1 more lines)
  24. You type 1 at Enter choice:
    runs: add()
  25. You type Kabir at Name :
  26. You type 17 at Age :
  27. You type M at Gender M/F :
  28. You type 165 at Height (cm) :
  29. You type 60 at Weight (kg) :
  30. You type 3 at Activity 1-Sedentary 2-Moderate 3-Active:
    runs: bmi()
    shows: Kabir added. BMI = 22.0 (+1 more lines)
  31. You type 1 at Enter choice:
    runs: add()
  32. You type Test at Name :
  33. You type 20 at Age :
  34. You type M at Gender M/F :
  35. You type 0 at Height (cm) :
  36. You type 50 at Weight (kg) :
    shows: Invalid height / weight. Member not added. (+1 more lines)
  37. You type 2 at Enter choice:
    runs: table() โ†’ bmi() ร—2 โ†’ category() โ†’ bmi() ร—2 โ†’ category() โ†’ bmi() ร—2 โ†’ category() โ†’ bmi() ร—2
    shows: Name Age Ht(cm) Wt(kg) BMI Category (+5 more lines)
  38. You type 3 at Enter choice:
    runs: ranges()
    shows: Papa healthy weight 53.5 - 72.0 kg (20.0 kg above) (+4 more lines)
  39. You type 4 at Enter choice:
    runs: needs()
    shows: Papa calories ~2115 kcal/day | water ~3.2 L/day (+4 more lines)
  40. You type 5 at Enter choice:
    runs: summary() โ†’ bmi() โ†’ category() โ†’ bmi() โ†’ category() โ†’ bmi() โ†’ category() โ†’ bmi()
    shows: Underweight : 1 * (+5 more lines)

โ€ฆ and 2 more inputs in the same way, till the program ends.

โ‘ค Inside each function - line by line
bmi() - lines 13โ€“14
LineCodeWhat it does
13
def bmi(i):
๐Ÿงฉ Function DEFINES a function bmi(i). Python only remembers it here - its body runs later, each time bmi() is called.
14
return round(wts[i] / (hts[i] / 100) ** 2, 1)
๐Ÿงฉ Function Sends back (returns) the result of: rounds wts[i] / (hts[i] / 100) ** 2 to 1 decimal places to the line that called the function
category() - lines 17โ€“24
LineCodeWhat it does
17
def category(b):
๐Ÿงฉ Function DEFINES a function category(b). Python only remembers it here - its body runs later, each time category() is called.
18
if b < 18.5:
๐Ÿ”€ Decision CHECKS whether b is less than 18.5. If True, the indented lines below run; otherwise Python jumps to the elif/else part
19
return "Underweight"
๐Ÿงฉ Function Sends back (returns) the text "Underweight" to the line that called the function
20
elif b < 25:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether b is less than 25
21
return "Normal"
๐Ÿงฉ Function Sends back (returns) the text "Normal" to the line that called the function
22
elif b < 30:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether b is less than 30
23
return "Overweight"
๐Ÿงฉ Function Sends back (returns) the text "Overweight" to the line that called the function
24
return "Obese"
๐Ÿงฉ Function Sends back (returns) the text "Obese" to the line that called the function
add() - lines 27โ€“38
LineCodeWhat it does
27
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
28
name = input("Name        : ")
โŒจ๏ธ Input Shows the message "Name : " and waits; whatever the user types comes back as TEXT (string); it is stored in variable name
29
age = int(input("Age         : "))
โŒจ๏ธ Input Shows "Age : ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable age
30
g = input("Gender M/F  : ").upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable g
31
h = float(input("Height (cm) : "))
โŒจ๏ธ Input Shows "Height (cm) : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable h
32
w = float(input("Weight (kg) : "))
โŒจ๏ธ Input Shows "Weight (kg) : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable w
33
if h <= 50 or w <= 0:
๐Ÿ”€ Decision CHECKS whether (h is less than or equal to 50 OR w is less than or equal to 0). If True, the indented lines below run; otherwise they are skipped
34
print("Invalid height / weight. Member not added.")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid height / weight. Member nโ€ฆ" on the screen
35
return
๐Ÿงฉ Function Ends the function and goes back to the caller
36
a = int(input("Activity 1-Sedentary 2-Moderate 3-Active: "))
โŒจ๏ธ Input Shows "Activity 1-Sedentary 2-Moderate 3-Active: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable a
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds name at the end of list names
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds age at the end of list ages
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds g at the end of list genders
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds h at the end of list hts
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds w at the end of list wts
37
names.append(name); ages.append(age); genders.append(g); hts.append(h); wts.append(w); acts.append(a)
๐Ÿงฎ Store / Calculate Adds a at the end of list acts
38
print(f"{name} added. BMI = {bmi(len(names) - 1)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name} added. BMI = {bmi(len(names) - 1)}" with the values filled into { } on the screen
table() - lines 41โ€“45
LineCodeWhat it does
41
def table():
๐Ÿงฉ Function DEFINES a function table(). Python only remembers it here - its body runs later, each time table() is called.
42
print("{:<8}{:>5}{:>8}{:>8}{:>7}  {}".format("Name", "Age", "Ht(cm)", "Wt(kg)", "BMI", "Category"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>5}{:>8}{:>8}{:>7} {}".format("Name",โ€ฆ on the screen
43
print("-" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "-" signs on the screen
44
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
45
print("{:<8}{:>5}{:>8.0f}{:>8.0f}{:>7}  {}".format(names[i], ages[i], hts[i], wts[i], bmi(i), category(bmi(i))))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:>5}{:>8.0f}{:>8.0f}{:>7} {}".format(nโ€ฆ on the screen
ranges() - lines 48โ€“54
LineCodeWhat it does
48
def ranges():
๐Ÿงฉ Function DEFINES a function ranges(). Python only remembers it here - its body runs later, each time ranges() is called.
49
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
50
m = hts[i] / 100
๐Ÿงฎ Store / Calculate Stores the value of hts[i] / 100 (calculated using รท) in variable m
51
lo, hi = 18.5 * m * m, 24.9 * m * m
๐Ÿงฎ Store / Calculate Stores 18.5 * m * m, 24.9 * m * m into lo, hi respectively
52
diff = wts[i] - hi if wts[i] > hi else wts[i] - lo if wts[i] < lo else 0
๐Ÿงฎ Store / Calculate Stores either wts[i] - hi or wts[i] - lo if wts[i] < lo else 0 depending on wts[i] > hi in variable diff
53
note = "in range" if diff == 0 else f"{abs(diff):.1f} kg {'above' if diff > 0 else 'below'}"
๐Ÿงฎ Store / Calculate Stores either "in range" or f"{abs(diff):.1f} kg {'above' if diff > 0 elsโ€ฆ depending on diff == 0 in variable note
54
print(f"{names[i]:<8} healthy weight {lo:.1f} - {hi:.1f} kg  ({note})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{names[i]:<8} healthy weight {lo:.1f} - {hiโ€ฆ with the values filled into { } on the screen
needs() - lines 57โ€“61
LineCodeWhat it does
57
def needs():
๐Ÿงฉ Function DEFINES a function needs(). Python only remembers it here - its body runs later, each time needs() is called.
58
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
59
base = 10 * wts[i] + 6.25 * hts[i] - 5 * ages[i] + (5 if genders[i] == "M" else -161)
๐Ÿงฎ Store / Calculate Stores the value of 10 * wts[i] + 6.25 * hts[i] - 5 * ages[i] + (โ€ฆ (calculated using +) in variable base
60
cal = base * FACTOR[acts[i] - 1]
๐Ÿงฎ Store / Calculate Stores the value of base * FACTOR[acts[i] - 1] (calculated using ร—) in variable cal
61
print(f"{names[i]:<8} calories ~{cal:.0f} kcal/day | water ~{wts[i] * 0.035:.1f} L/day")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{names[i]:<8} calories ~{cal:.0f} kcal/day โ€ฆ with the values filled into { } on the screen
summary() - lines 64โ€“68
LineCodeWhat it does
64
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
65
cats = [category(bmi(i)) for i in range(len(names))]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [category(bmi(i)) for i in range(len(names))] in variable cats
66
for c in ["Underweight", "Normal", "Overweight", "Obese"]:
๐Ÿ” Loop LOOP: takes each item of ["Underweight", "Normal", "Overweight", "Obesโ€ฆ one-by-one into c and runs the indented block for it
67
print(f"{c:<12}: {cats.count(c)}  " + "*" * cats.count(c))
๐Ÿ–ฅ๏ธ Output Displays the value of f"{c:<12}: {cats.count(c)} " + "*" * cats.couโ€ฆ on the screen
68
print("Family average BMI:", round(sum(bmi(i) for i in range(len(names))) / len(names), 1))
๐Ÿ–ฅ๏ธ Output Displays the text "Family average BMI:", then the value of round(sum(bmi(i) for i in range(len(names))) โ€ฆ on the screen
tips() - lines 71โ€“75
LineCodeWhat it does
71
def tips():
๐Ÿงฉ Function DEFINES a function tips(). Python only remembers it here - its body runs later, each time tips() is called.
72
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
73
c = category(bmi(i))
๐Ÿงฎ Store / Calculate Calls our own function category(bmi(i)); the result is stored in variable c
74
print(f"{names[i]} ({c}): {TIPS[c]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{names[i]} ({c}): {TIPS[c]}" with the values filled into { } on the screen
75
print("Note: general tips only - consult a doctor for medical advice.")
๐Ÿ–ฅ๏ธ Output Displays the text "Note: general tips only - consultโ€ฆ" on the screen
Q1. What is BMI?

Body Mass Index = weight (kg) / height (m) squared.

Q2. Healthy BMI range?

18.5 to 24.9 for adults.

Q3. How is the healthy weight range found?

18.5 x h^2 to 24.9 x h^2, where h is height in metres.

Q4. Why is this not medical advice?

BMI is only a screening tool; a doctor considers many other factors.

Q5. Which SDG?

SDG 3 - Good Health and Well-being.

09

Smart Waste Segregation Guide (SDG 12)

PYTHONSDG 12 - Responsible Consumption and Productionkeyword listsmembership operator 'in'for looprule-based classificationcounters
๐Ÿ“ 106 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 92 output lines๐Ÿ“„ 25+ page report

A rule-based classifier that sorts waste items typed by the user into Wet (green bin), Dry (blue bin), E-waste and Hazardous categories using keyword lists, and reports the share of each category.

โœจ Features
  • Rule-based classifier that sorts waste items into Wet, Dry, E-waste, Hazardous
  • Keyword lists for each category; hazardous / e-waste rules checked first (rule order)
  • Teach-the-AI option: add a new keyword when an item is Unknown
  • Daily segregation log with counts and percentages
  • Composting estimate: compost produced from wet waste
  • Accuracy test against a labelled sample set
โ˜ฐ Main menu
1Classify ItemsComma-separated items -> bin
2Teach New KeywordAdds a keyword to a category
3SummaryCounts and % of today's items
4Compost EstimateWet waste kg -> compost
5Test AccuracyLabelled sample set
6Show RulesKeyword lists
0ExitEnds program
๐ŸŽฏ Objectives
  • Represent knowledge as keyword lists
  • Classify items using membership tests
  • Count and report category-wise percentages
๐Ÿ“š Data dictionary
NameTypePurpose
wet, dry, ewaste, hazardlistsKeywords for each category
log_items, log_catslistsItems classified today
classify()functionReturns category and bin
SAMPLElist of pairsItems with correct labels for testing
Why it matters: Shows how a simple text-based rule model can support Swachh Bharat and responsible waste management.
# =====================================================================
#   SMART WASTE SEGREGATION GUIDE   (SDG 12)
#   Concepts: lists, any(), functions, rule order, menu, accuracy
# =====================================================================
wet = ["peel", "food", "tea", "vegetable", "fruit", "egg", "leaves", "flower"]
dry = ["plastic", "paper", "newspaper", "bottle", "cardboard", "packet", "can", "glass"]
ewaste = ["charger", "mobile", "battery", "cable", "bulb", "earphone", "remote"]
hazard = ["thermometer", "medicine", "syringe", "paint", "pesticide"]
BINS = {"Wet": "Green bin (compost)", "Dry": "Blue bin (recycle)", "E-waste": "E-waste collection centre",
        "Hazardous": "Red bin / special disposal", "Unknown": "Ask teacher / teach a new rule"}
SAMPLE = [("apple core fruit", "Wet"), ("milk packet", "Dry"), ("tv remote", "E-waste"), ("expired medicine", "Hazardous"),
          ("flower garland", "Wet"), ("cold drink can", "Dry"), ("usb cable", "E-waste"), ("paint tin", "Hazardous"),
          ("cooked food", "Wet"), ("rubber slipper", "Dry")]
log_items, log_cats = [], []


def classify(item):
    if any(k in item for k in hazard):
        return "Hazardous"
    if any(k in item for k in ewaste):
        return "E-waste"
    if any(k in item for k in wet):
        return "Wet"
    if any(k in item for k in dry):
        return "Dry"
    return "Unknown"


def classify_items():
    items = input("Enter waste items (comma separated):\n").split(",")
    for item in items:
        item = item.strip().lower()
        cat = classify(item)
        log_items.append(item); log_cats.append(cat)
        print(f"{item:<20} -> {cat:<10} : {BINS[cat]}")


def teach():
    word = input("New keyword: ").strip().lower()
    cat = input("Category (wet/dry/ewaste/hazard): ").strip().lower()
    lists = {"wet": wet, "dry": dry, "ewaste": ewaste, "hazard": hazard}
    if cat in lists:
        lists[cat].append(word)
        print(f"Rule learnt: '{word}' -> {cat}")
    else:
        print("Unknown category.")


def summary():
    total = len(log_cats)
    print("Items classified today:", total)
    for c in BINS:
        n = log_cats.count(c)
        print(f"{c:<10}: {n:>2}  ({n / total * 100:4.0f} %)  " + "#" * n)


def compost():
    w = log_cats.count("Wet") * 0.5
    print(f"Wet items today: {log_cats.count('Wet')} (~{w:.1f} kg at 0.5 kg each)")
    print(f"Compost after 45 days: ~{w * 0.3:.1f} kg  |  in a month (x30): ~{w * 0.3 * 30:.0f} kg")


def test_accuracy():
    right = 0
    for item, label in SAMPLE:
        got = classify(item)
        ok = got == label
        right += ok
        print(f"{item:<18} expected {label:<10} got {got:<10} {'OK' if ok else 'WRONG'}")
    print(f"Accuracy = {right}/{len(SAMPLE)} = {right / len(SAMPLE) * 100:.0f} %")


def rules():
    print("Hazardous :", hazard)
    print("E-waste   :", ewaste)
    print("Wet       :", wet)
    print("Dry       :", dry)
    print("Order of checking: Hazardous -> E-waste -> Wet -> Dry")


print("=" * 55)
print("   SMART WASTE SEGREGATION GUIDE  (SDG 12)")
print("=" * 55)
while True:
    print("\n1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Segregate at source!")
        break
    elif ch == "1":
        classify_items()
    elif ch == "2":
        teach()
    elif ch in ("3", "4") and not log_cats:
        print("Classify some items first.")
    elif ch == "3":
        summary()
    elif ch == "4":
        compost()
    elif ch == "5":
        test_accuracy()
    elif ch == "6":
        rules()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Classify? → No: run other option
  4. Read items
  5. Hazard keyword? → No: check e-waste, wet, dry
  6. Assign category and bin
  7. Show bin; count
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1banana peelWet - Green binPASS
2plastic bottleDry - Blue binPASS
3used batteryE-wastePASS
4broken thermometerHazardousPASS
5mystery objectUnknownPASS
6Teach 'diaper' -> hazardNext time classified HazardousPASS
7Accuracy test9/10, then 10/10 after teaching slipper -> dryPASS
8Compost 5 kgAbout 1.5 kg compostPASS
โš  Limitations
  • Keyword matching only - no images
  • Spelling must match keywords
  • Mixed items (e.g. tetra pack) are hard
  • Rules must be updated manually
๐Ÿš€ Future scope
  • Camera-based waste classifier (CNN)
  • Smart bin with sensors
  • Hindi keyword support
  • Reward points for correct segregation

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: wet, dry, ewaste, hazard, BINS, SAMPLE.
  2. 7 functions are defined (lines 17โ€“78) - Python stores them but does NOT run them yet.
  3. Main program starts at line 14: log_items, log_cats = [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
classify(item)17โ€“26Classifyclassify_items(), test_accuracy()
classify_items()29โ€“35Classify itemsmain program
teach()38โ€“46Teachmain program
summary()49โ€“54Summarymain program
compost()57โ€“60Compostmain program
test_accuracy()63โ€“70Test accuracymain program
rules()73โ€“78Rulesmain program
โ‘ข Main program - line by line
LineCodeWhat it does
14
log_items, log_cats = [], []
๐Ÿงฎ Store / Calculate Stores [], [] into log_items, log_cats respectively
81
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
82
print("   SMART WASTE SEGREGATION GUIDE  (SDG 12)")
๐Ÿ–ฅ๏ธ Output Displays the text "SMART WASTE SEGREGATION GUIDE (SDโ€ฆ" on the screen
83
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
84
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
85
print("\n1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Classify 2.Teach Keyword 3.Summโ€ฆ" on the screen
86
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
87
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
88
print("Segregate at source!")
๐Ÿ–ฅ๏ธ Output Displays the text "Segregate at source!" on the screen
89
break
๐Ÿ” Loop BREAK - leaves the loop immediately
90
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
91
classify_items()
๐Ÿงฎ Store / Calculate Calls our own function classify_items()
92
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
93
teach()
๐Ÿงฎ Store / Calculate Calls our own function teach()
94
elif ch in ("3", "4") and not log_cats:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (ch is present in ("3", "4") AND log_cats is False (or empty / zero))
95
print("Classify some items first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Classify some items first." on the screen
96
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
97
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
98
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
99
compost()
๐Ÿงฎ Store / Calculate Calls our own function compost()
100
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
101
test_accuracy()
๐Ÿงฎ Store / Calculate Calls our own function test_accuracy()
102
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
103
rules()
๐Ÿงฎ Store / Calculate Calls our own function rules()
104
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
105
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: SMART WASTE SEGREGATION GUIDE (SDG 12) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: classify_items()
  3. You type banana peel, plastic bottle, old mobile charger, newspaper, tea leaves, used battery, chips packet, broken thermometer, vegetable peels, mystery object, diaper at Enter waste items (comma separated):
    runs: classify() ร—11
    shows: banana peel -> Wet : Green bin (compost) (+11 more lines)
  4. You type 2 at Enter choice:
    runs: teach()
  5. You type diaper at New keyword:
  6. You type hazard at Category (wet/dry/ewaste/hazard):
    shows: Rule learnt: 'diaper' -> hazard (+1 more lines)
  7. You type 1 at Enter choice:
    runs: classify_items()
  8. You type diaper, egg shells at Enter waste items (comma separated):
    runs: classify() ร—2
    shows: diaper -> Hazardous : Red bin / special disposal (+2 more lines)
  9. You type 3 at Enter choice:
    runs: summary()
    shows: Items classified today: 13 (+6 more lines)
  10. You type 4 at Enter choice:
    runs: compost()
    shows: Wet items today: 4 (~2.0 kg at 0.5 kg each) (+2 more lines)
  11. You type 5 at Enter choice:
    runs: test_accuracy() โ†’ classify() ร—10
    shows: apple core fruit expected Wet got Wet OK (+11 more lines)
  12. You type 2 at Enter choice:
    runs: teach()
  13. You type slipper at New keyword:
  14. You type dry at Category (wet/dry/ewaste/hazard):
    shows: Rule learnt: 'slipper' -> dry (+1 more lines)
  15. You type 5 at Enter choice:
    runs: test_accuracy() โ†’ classify() ร—10
    shows: apple core fruit expected Wet got Wet OK (+11 more lines)
  16. You type 6 at Enter choice:
    runs: rules()
    shows: Hazardous : ['thermometer', 'medicine', 'syringe', 'paint', 'pesticide', 'diaper'] (+5 more lines)
  17. You type 0 at Enter choice:
    shows: Segregate at source!
โ‘ค Inside each function - line by line
classify() - lines 17โ€“26
LineCodeWhat it does
17
def classify(item):
๐Ÿงฉ Function DEFINES a function classify(item). Python only remembers it here - its body runs later, each time classify() is called.
18
if any(k in item for k in hazard):
๐Ÿ”€ Decision CHECKS whether any(k in item for k in hazard) is True. If True, the indented lines below run; otherwise they are skipped
19
return "Hazardous"
๐Ÿงฉ Function Sends back (returns) the text "Hazardous" to the line that called the function
20
if any(k in item for k in ewaste):
๐Ÿ”€ Decision CHECKS whether any(k in item for k in ewaste) is True. If True, the indented lines below run; otherwise they are skipped
21
return "E-waste"
๐Ÿงฉ Function Sends back (returns) the text "E-waste" to the line that called the function
22
if any(k in item for k in wet):
๐Ÿ”€ Decision CHECKS whether any(k in item for k in wet) is True. If True, the indented lines below run; otherwise they are skipped
23
return "Wet"
๐Ÿงฉ Function Sends back (returns) the text "Wet" to the line that called the function
24
if any(k in item for k in dry):
๐Ÿ”€ Decision CHECKS whether any(k in item for k in dry) is True. If True, the indented lines below run; otherwise they are skipped
25
return "Dry"
๐Ÿงฉ Function Sends back (returns) the text "Dry" to the line that called the function
26
return "Unknown"
๐Ÿงฉ Function Sends back (returns) the text "Unknown" to the line that called the function
classify_items() - lines 29โ€“35
LineCodeWhat it does
29
def classify_items():
๐Ÿงฉ Function DEFINES a function classify_items(). Python only remembers it here - its body runs later, each time classify_items() is called.
30
items = input("Enter waste items (comma separated):\n").split(",")
โŒจ๏ธ Input Breaks input("Enter waste items (comma separated):\nโ€ฆ into a list of words wherever "," occurs; the result is stored in variable items
31
for item in items:
๐Ÿ” Loop LOOP: takes each item of items one-by-one into item and runs the indented block for it
32
item = item.strip().lower()
๐Ÿงฎ Store / Calculate Changes item.strip() to small letters; the result is stored in variable item
33
cat = classify(item)
๐Ÿงฎ Store / Calculate Calls our own function classify(item); the result is stored in variable cat
34
log_items.append(item); log_cats.append(cat)
๐Ÿงฎ Store / Calculate Adds item at the end of list log_items
34
log_items.append(item); log_cats.append(cat)
๐Ÿงฎ Store / Calculate Adds cat at the end of list log_cats
35
print(f"{item:<20} -> {cat:<10} : {BINS[cat]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{item:<20} -> {cat:<10} : {BINS[cat]}" with the values filled into { } on the screen
teach() - lines 38โ€“46
LineCodeWhat it does
38
def teach():
๐Ÿงฉ Function DEFINES a function teach(). Python only remembers it here - its body runs later, each time teach() is called.
39
word = input("New keyword: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable word
40
cat = input("Category (wet/dry/ewaste/hazard): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable cat
41
lists = {"wet": wet, "dry": dry, "ewaste": ewaste, "hazard": hazard}
๐Ÿงฎ Store / Calculate Stores a dictionary {"wet": wet, "dry": dry, "ewaste": ewaste, "hโ€ฆ in variable lists
42
if cat in lists:
๐Ÿ”€ Decision CHECKS whether cat is present in lists. If True, the indented lines below run; otherwise Python jumps to the elif/else part
43
lists[cat].append(word)
๐Ÿงฎ Store / Calculate Adds word at the end of list lists[cat]
44
print(f"Rule learnt: '{word}' -> {cat}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Rule learnt: '{word}' -> {cat}" with the values filled into { } on the screen
45
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
46
print("Unknown category.")
๐Ÿ–ฅ๏ธ Output Displays the text "Unknown category." on the screen
summary() - lines 49โ€“54
LineCodeWhat it does
49
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
50
total = len(log_cats)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in log_cats; the result is stored in variable total
51
print("Items classified today:", total)
๐Ÿ–ฅ๏ธ Output Displays the text "Items classified today:", then the value of total on the screen
52
for c in BINS:
๐Ÿ” Loop LOOP: takes each item of BINS one-by-one into c and runs the indented block for it
53
n = log_cats.count(c)
๐Ÿงฎ Store / Calculate Counts how many times c occurs in log_cats; the result is stored in variable n
54
print(f"{c:<10}: {n:>2}  ({n / total * 100:4.0f} %)  " + "#" * n)
๐Ÿ–ฅ๏ธ Output Displays the value of f"{c:<10}: {n:>2} ({n / total * 100:4.0f} %) โ€ฆ on the screen
compost() - lines 57โ€“60
LineCodeWhat it does
57
def compost():
๐Ÿงฉ Function DEFINES a function compost(). Python only remembers it here - its body runs later, each time compost() is called.
58
w = log_cats.count("Wet") * 0.5
๐Ÿงฎ Store / Calculate Stores the value of log_cats.count("Wet") * 0.5 (calculated using ร—) in variable w
59
print(f"Wet items today: {log_cats.count('Wet')} (~{w:.1f} kg at 0.5 kg each)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Wet items today: {log_cats.count('Wet')} (~โ€ฆ with the values filled into { } on the screen
60
print(f"Compost after 45 days: ~{w * 0.3:.1f} kg  |  in a month (x30): ~{w * 0.3 * 30:.0f} kg")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Compost after 45 days: ~{w * 0.3:.1f} kg | โ€ฆ with the values filled into { } on the screen
test_accuracy() - lines 63โ€“70
LineCodeWhat it does
63
def test_accuracy():
๐Ÿงฉ Function DEFINES a function test_accuracy(). Python only remembers it here - its body runs later, each time test_accuracy() is called.
64
right = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable right
65
for item, label in SAMPLE:
๐Ÿ” Loop LOOP: takes each item of SAMPLE one-by-one into item, label and runs the indented block for it
66
got = classify(item)
๐Ÿงฎ Store / Calculate Calls our own function classify(item); the result is stored in variable got
67
ok = got == label
๐Ÿงฎ Store / Calculate Stores True/False for got is equal to label in variable ok
68
right += ok
๐Ÿงฎ Store / Calculate Adds ok to right (same as right = right + ok)
69
print(f"{item:<18} expected {label:<10} got {got:<10} {'OK' if ok else 'WRONG'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{item:<18} expected {label:<10} got {got:<1โ€ฆ with the values filled into { } on the screen
70
print(f"Accuracy = {right}/{len(SAMPLE)} = {right / len(SAMPLE) * 100:.0f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Accuracy = {right}/{len(SAMPLE)} = {right /โ€ฆ with the values filled into { } on the screen
rules() - lines 73โ€“78
LineCodeWhat it does
73
def rules():
๐Ÿงฉ Function DEFINES a function rules(). Python only remembers it here - its body runs later, each time rules() is called.
74
print("Hazardous :", hazard)
๐Ÿ–ฅ๏ธ Output Displays the text "Hazardous :", then the value of hazard on the screen
75
print("E-waste   :", ewaste)
๐Ÿ–ฅ๏ธ Output Displays the text "E-waste :", then the value of ewaste on the screen
76
print("Wet       :", wet)
๐Ÿ–ฅ๏ธ Output Displays the text "Wet :", then the value of wet on the screen
77
print("Dry       :", dry)
๐Ÿ–ฅ๏ธ Output Displays the text "Dry :", then the value of dry on the screen
78
print("Order of checking: Hazardous -> E-waste -> Wet -> Dry")
๐Ÿ–ฅ๏ธ Output Displays the text "Order of checking: Hazardous -> Eโ€ฆ" on the screen
Q1. Why are hazardous rules checked first?

Some items may match two lists; checking the dangerous categories first avoids putting them in the wrong bin.

Q2. What is the 'teach' option?

It lets the user add a new keyword - a simple way of improving the rule base (not real learning).

Q3. What is any()?

Returns True if at least one condition in the sequence is True.

Q4. How is accuracy tested?

Classify items whose correct answer is known and count how many match.

Q5. Which SDG?

SDG 12 - Responsible Consumption and Production.

10

Class Attendance Analyser and Predictor (SDG 4)

PYTHONSDG 4 - Quality Educationnested listsfor loopspercentageprobabilityif conditions
๐Ÿ“ 102 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 90 output lines๐Ÿ“„ 25+ page report

Analyses one week of attendance for a group of students (P/A), calculates each student's attendance percentage, lists students below 75 %, finds the day with the lowest attendance and estimates the probability that a student is present.

โœจ Features
  • Weekly attendance strings (P/A) of 8 students for 6 days
  • Student-wise percentage and status (Regular / Needs support)
  • Day-wise presents and lowest attendance day
  • Probability of a student being present and expected attendance for a class of 40
  • Mark attendance for a new day and update records
  • Early-warning list: students with 2+ absences or consecutive absences
โ˜ฐ Main menu
1Weekly ReportPercentage and status
2Day-wise AnalysisPresents per day with bars
3Probability & PredictionExpected attendance tomorrow
4Mark Today's AttendanceAdds a new day
5Early Warning2+ absences or AA pattern
6Student SearchHistory of one student
0ExitEnds program
๐ŸŽฏ Objectives
  • Store and process tabular data using lists of strings
  • Compute percentages and identify students at risk (< 75 %)
  • Estimate probability from past data
๐Ÿ“š Data dictionary
NameTypePurpose
nameslist8 student names
attlist of strOne string per student, 'P'/'A' per day
dayslistDay names
probfloatTotal presents / (students x days)
Why it matters: Shows how schools can use simple data analysis to identify students who need support.
# =====================================================================
#   CLASS ATTENDANCE ANALYSER AND PREDICTOR   (SDG 4)
#   Concepts: strings, count(), lists, nested loops, functions, menu
# =====================================================================
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
names = ["Anu", "Bilal", "Chetna", "Dev", "Esha", "Farhan", "Gita", "Harry"]
att = ["PPPPPP", "PAPAPP", "PPPPAP", "AAPPPA", "PPPPPP", "PPAPPP", "PPPPPA", "PAAPPP"]


def report():
    print("{:<8}{:<10}{:>7}  Status".format("Name", "Record", "%"))
    for i in range(len(names)):
        pct = att[i].count("P") / len(days) * 100
        status = "Regular" if pct >= 75 else "Needs support"
        print("{:<8}{:<10}{:>6.1f}%  {}".format(names[i], att[i], pct, status))
    total = sum(s.count("P") for s in att)
    print(f"Class attendance: {total}/{len(names) * len(days)} = {total / (len(names) * len(days)) * 100:.1f} %")


def day_wise():
    counts = []
    for d in range(len(days)):
        c = 0
        for s in att:
            if s[d] == "P":
                c += 1
        counts.append(c)
        print(f"{days[d]}: {c}/{len(names)}  " + "#" * c)
    print("Lowest attendance day :", days[counts.index(min(counts))])
    print("Highest attendance day:", days[counts.index(max(counts))])


def probability():
    total = sum(s.count("P") for s in att)
    prob = total / (len(names) * len(days))
    print("P(student present on a day) =", round(prob, 3))
    print("P(student absent)           =", round(1 - prob, 3))
    print("Expected present tomorrow (class of 40):", round(prob * 40))
    for i in range(len(names)):
        print(f"  P({names[i]} present tomorrow) = {att[i].count('P') / len(days):.2f}")


def mark():
    day = "D" + str(len(days) + 1)
    print("Marking attendance for", day)
    for i in range(len(names)):
        while True:
            v = input(f"  {names[i]} (P/A): ").strip().upper()
            if v in ("P", "A"):
                break
            print("  Enter P or A only.")
        att[i] = att[i] + v
    days.append(day)
    print("Attendance saved. Days recorded:", len(days))


def warning():
    found = False
    for i in range(len(names)):
        a = att[i].count("A")
        if a >= 2 or "AA" in att[i]:
            reason = "consecutive absences" if "AA" in att[i] else f"{a} absences"
            print(f"WARNING: {names[i]:<7} {att[i]}  -> {reason}; inform class teacher / parents")
            found = True
    if not found:
        print("No student at risk.")


def search():
    n = input("Student name: ").strip().title()
    if n in names:
        s = att[names.index(n)]
        print(n, ":", " ".join(f"{days[d]}-{s[d]}" for d in range(len(s))))
        print(f"Present {s.count('P')} / {len(s)} = {s.count('P') / len(s) * 100:.1f} %")
    else:
        print("Student not found.")


print("=" * 50)
print("   CLASS ATTENDANCE ANALYSER  (SDG 4)")
print("=" * 50)
while True:
    print("\n1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        report()
    elif ch == "2":
        day_wise()
    elif ch == "3":
        probability()
    elif ch == "4":
        mark()
    elif ch == "5":
        warning()
    elif ch == "6":
        search()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Choice is Mark? → No: run report
  4. Read P/A for each student
  5. Input is P or A? → No: ask again
  6. Append to strings
  7. Show report / warning
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Weekly reportDev 50 % Needs supportPASS
2Day-wiseLowest day shownPASS
3Probability0.792PASS
4Mark day with 'X'Asked againPASS
5Mark day7 days nowPASS
6Early warningStudents with AAPASS
7Search 'Esha'100 %PASS
8Search 'Zara'Not foundPASS
โš  Limitations
  • Small class sample
  • Prediction ignores day-of-week effects
  • No reasons for absence
  • Data not saved to file
๐Ÿš€ Future scope
  • Face-recognition attendance (CV)
  • Save to CSV and use pandas
  • SMS to parents
  • Predict dropout risk (Class XII project)

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Global variables / constants are created: days, names, att.
  2. 6 functions are defined (lines 10โ€“76) - Python stores them but does NOT run them yet.
  3. Main program starts at line 79: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
report()10โ€“17Reportmain program
day_wise()20โ€“30Day wisemain program
probability()33โ€“40Probabilitymain program
mark()43โ€“54Markmain program
warning()57โ€“66Warningmain program
search()69โ€“76Searchmain program
โ‘ข Main program - line by line
LineCodeWhat it does
79
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
80
print("   CLASS ATTENDANCE ANALYSER  (SDG 4)")
๐Ÿ–ฅ๏ธ Output Displays the text "CLASS ATTENDANCE ANALYSER (SDG 4)" on the screen
81
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
82
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
83
print("\n1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Report 2.Day-wise 3.Probabilityโ€ฆ" on the screen
84
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
85
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
86
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
87
break
๐Ÿ” Loop BREAK - leaves the loop immediately
88
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
89
report()
๐Ÿงฎ Store / Calculate Calls our own function report()
90
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
91
day_wise()
๐Ÿงฎ Store / Calculate Calls our own function day_wise()
92
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
93
probability()
๐Ÿงฎ Store / Calculate Calls our own function probability()
94
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
95
mark()
๐Ÿงฎ Store / Calculate Calls our own function mark()
96
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
97
warning()
๐Ÿงฎ Store / Calculate Calls our own function warning()
98
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
99
search()
๐Ÿงฎ Store / Calculate Calls our own function search()
100
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
101
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CLASS ATTENDANCE ANALYSER (SDG 4) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: report()
    shows: Name Record % Status (+10 more lines)
  3. You type 2 at Enter choice:
    runs: day_wise()
    shows: Mon: 7/8 ####### (+8 more lines)
  4. You type 3 at Enter choice:
    runs: probability()
    shows: P(student present on a day) = 0.792 (+11 more lines)
  5. You type 4 at Enter choice:
    runs: mark()
    shows: Marking attendance for D7
  6. You type P at Anu (P/A):
  7. You type P at Bilal (P/A):
  8. You type P at Chetna (P/A):
  9. You type A at Dev (P/A):
  10. You type X at Esha (P/A):
    shows: Enter P or A only.
  11. You type P at Esha (P/A):
  12. You type P at Farhan (P/A):
  13. You type P at Gita (P/A):
  14. You type P at Harry (P/A):
    shows: Attendance saved. Days recorded: 7 (+1 more lines)
  15. You type 1 at Enter choice:
    runs: report()
    shows: Name Record % Status (+10 more lines)
  16. You type 5 at Enter choice:
    runs: warning()
    shows: WARNING: Bilal PAPAPPP -> 2 absences; inform class teacher / parents (+3 more lines)
  17. You type 6 at Enter choice:
    runs: search()
  18. You type Esha at Student name:
    shows: Esha : Mon-P Tue-P Wed-P Thu-P Fri-P Sat-P D7-P (+2 more lines)
  19. You type 6 at Enter choice:
    runs: search()
  20. You type Zara at Student name:
    shows: Student not found. (+1 more lines)
  21. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
report() - lines 10โ€“17
LineCodeWhat it does
10
def report():
๐Ÿงฉ Function DEFINES a function report(). Python only remembers it here - its body runs later, each time report() is called.
11
print("{:<8}{:<10}{:>7}  Status".format("Name", "Record", "%"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:<10}{:>7} Status".format("Name", "Recโ€ฆ on the screen
12
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
13
pct = att[i].count("P") / len(days) * 100
๐Ÿงฎ Store / Calculate Stores the value of att[i].count("P") / len(days) * 100 (calculated using ร—) in variable pct
14
status = "Regular" if pct >= 75 else "Needs support"
๐Ÿงฎ Store / Calculate Stores either "Regular" or "Needs support" depending on pct >= 75 in variable status
15
print("{:<8}{:<10}{:>6.1f}%  {}".format(names[i], att[i], pct, status))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<8}{:<10}{:>6.1f}% {}".format(names[i], atโ€ฆ on the screen
16
total = sum(s.count("P") for s in att)
๐Ÿงฎ Store / Calculate Adds up all the values in (s.count("P") for s in att); the result is stored in variable total
17
print(f"Class attendance: {total}/{len(names) * len(days)} = {total / (len(names) * len(days)) * 100:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Class attendance: {total}/{len(names) * lenโ€ฆ with the values filled into { } on the screen
day_wise() - lines 20โ€“30
LineCodeWhat it does
20
def day_wise():
๐Ÿงฉ Function DEFINES a function day_wise(). Python only remembers it here - its body runs later, each time day_wise() is called.
21
counts = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable counts
22
for d in range(len(days)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(days) - 1; for each number, d takes that value and the indented block runs once
23
c = 0
๐Ÿงฎ Store / Calculate Stores the number 0 in variable c
24
for s in att:
๐Ÿ” Loop LOOP: takes each item of att one-by-one into s and runs the indented block for it
25
if s[d] == "P":
๐Ÿ”€ Decision CHECKS whether s[d] is equal to "P". If True, the indented lines below run; otherwise they are skipped
26
c += 1
๐Ÿงฎ Store / Calculate Adds 1 to c (same as c = c + 1)
27
counts.append(c)
๐Ÿงฎ Store / Calculate Adds c at the end of list counts
28
print(f"{days[d]}: {c}/{len(names)}  " + "#" * c)
๐Ÿ–ฅ๏ธ Output Displays the value of f"{days[d]}: {c}/{len(names)} " + "#" * c on the screen
29
print("Lowest attendance day :", days[counts.index(min(counts))])
๐Ÿ–ฅ๏ธ Output Displays the text "Lowest attendance day :", then the value of days[counts.index(min(counts))] on the screen
30
print("Highest attendance day:", days[counts.index(max(counts))])
๐Ÿ–ฅ๏ธ Output Displays the text "Highest attendance day:", then the value of days[counts.index(max(counts))] on the screen
probability() - lines 33โ€“40
LineCodeWhat it does
33
def probability():
๐Ÿงฉ Function DEFINES a function probability(). Python only remembers it here - its body runs later, each time probability() is called.
34
total = sum(s.count("P") for s in att)
๐Ÿงฎ Store / Calculate Adds up all the values in (s.count("P") for s in att); the result is stored in variable total
35
prob = total / (len(names) * len(days))
๐Ÿงฎ Store / Calculate Stores the value of total / (len(names) * len(days)) (calculated using รท) in variable prob
36
print("P(student present on a day) =", round(prob, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "P(student present on a day) =", then the value of round(prob, 3) on the screen
37
print("P(student absent)           =", round(1 - prob, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "P(student absent) =", then the value of round(1 - prob, 3) on the screen
38
print("Expected present tomorrow (class of 40):", round(prob * 40))
๐Ÿ–ฅ๏ธ Output Displays the text "Expected present tomorrow (class โ€ฆ", then the value of round(prob * 40) on the screen
39
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
40
print(f"  P({names[i]} present tomorrow) = {att[i].count('P') / len(days):.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" P({names[i]} present tomorrow) = {att[i].cโ€ฆ with the values filled into { } on the screen
mark() - lines 43โ€“54
LineCodeWhat it does
43
def mark():
๐Ÿงฉ Function DEFINES a function mark(). Python only remembers it here - its body runs later, each time mark() is called.
44
day = "D" + str(len(days) + 1)
๐Ÿงฎ Store / Calculate Stores the value of "D" + str(len(days) + 1) (calculated using +) in variable day
45
print("Marking attendance for", day)
๐Ÿ–ฅ๏ธ Output Displays the text "Marking attendance for", then the value of day on the screen
46
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
47
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
48
v = input(f"  {names[i]} (P/A): ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable v
49
if v in ("P", "A"):
๐Ÿ”€ Decision CHECKS whether v is present in ("P", "A"). If True, the indented lines below run; otherwise they are skipped
50
break
๐Ÿ” Loop BREAK - leaves the loop immediately
51
print("  Enter P or A only.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter P or A only." on the screen
52
att[i] = att[i] + v
๐Ÿงฎ Store / Calculate Puts the value of att[i] + v (calculated using +) into att[i] (item i of att)
53
days.append(day)
๐Ÿงฎ Store / Calculate Adds day at the end of list days
54
print("Attendance saved. Days recorded:", len(days))
๐Ÿ–ฅ๏ธ Output Displays the text "Attendance saved. Days recorded:", then the value of len(days) on the screen
warning() - lines 57โ€“66
LineCodeWhat it does
57
def warning():
๐Ÿงฉ Function DEFINES a function warning(). Python only remembers it here - its body runs later, each time warning() is called.
58
found = False
๐Ÿงฎ Store / Calculate Stores False in variable found
59
for i in range(len(names)):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to len(names) - 1; for each number, i takes that value and the indented block runs once
60
a = att[i].count("A")
๐Ÿงฎ Store / Calculate Counts how many times "A" occurs in att[i]; the result is stored in variable a
61
if a >= 2 or "AA" in att[i]:
๐Ÿ”€ Decision CHECKS whether (a is greater than or equal to 2 OR "AA" is present in att[i]). If True, the indented lines below run; otherwise they are skipped
62
reason = "consecutive absences" if "AA" in att[i] else f"{a} absences"
๐Ÿงฎ Store / Calculate Stores either "consecutive absences" or f"{a} absences" depending on "AA" in att[i] in variable reason
63
print(f"WARNING: {names[i]:<7} {att[i]}  -> {reason}; inform class teacher / parents")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"WARNING: {names[i]:<7} {att[i]} -> {reason}โ€ฆ with the values filled into { } on the screen
64
found = True
๐Ÿงฎ Store / Calculate Stores True in variable found
65
if not found:
๐Ÿ”€ Decision CHECKS whether found is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
66
print("No student at risk.")
๐Ÿ–ฅ๏ธ Output Displays the text "No student at risk." on the screen
search() - lines 69โ€“76
LineCodeWhat it does
69
def search():
๐Ÿงฉ Function DEFINES a function search(). Python only remembers it here - its body runs later, each time search() is called.
70
n = input("Student name: ").strip().title()
โŒจ๏ธ Input Reads the typed text, changes its case with .title() and stores it in variable n
71
if n in names:
๐Ÿ”€ Decision CHECKS whether n is present in names. If True, the indented lines below run; otherwise Python jumps to the elif/else part
72
s = att[names.index(n)]
๐Ÿงฎ Store / Calculate Stores the item att[names.index(n)] in variable s
73
print(n, ":", " ".join(f"{days[d]}-{s[d]}" for d in range(len(s))))
๐Ÿ–ฅ๏ธ Output Displays the value of n, then the text ":", then the value of " ".join(f"{days[d]}-{s[d]}" for d in range(lโ€ฆ on the screen
74
print(f"Present {s.count('P')} / {len(s)} = {s.count('P') / len(s) * 100:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Present {s.count('P')} / {len(s)} = {s.counโ€ฆ with the values filled into { } on the screen
75
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
76
print("Student not found.")
๐Ÿ–ฅ๏ธ Output Displays the text "Student not found." on the screen
Q1. How is the percentage found?

count('P') / number of days x 100.

Q2. How is the probability of presence found?

Total presents / (number of students x number of days).

Q3. How are consecutive absences detected?

By checking if 'AA' is in the student's attendance string.

Q4. What is an early-warning system?

A system that flags students at risk early so teachers can help.

Q5. Which SDG?

SDG 4 - Quality Education.

๐Ÿง  Class X Artificial Intelligence (417) โ€” 10 AI Projects (incl. 3 CBSE sample projects) 10 projects

01

Palmer Penguin Species Predictor (Statistical Data)

PYTHON + PANDASSDG 14 - Life Below Water / SDG 15 - Life on LandPandas read_csvgroupby meanfeature scalingNumPy distancetrain-test split
๐Ÿ“ 130 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 96 output lines๐Ÿ“„ 25+ page report

CBSE sample project 1: uses the real Palmer Penguins dataset (333 penguins) to predict the species - Adelie, Chinstrap or Gentoo - from bill length, bill depth and flipper length using a nearest-centroid model built with NumPy, and evaluates it on unseen test data.

โœจ Features
  • Palmer Penguins dataset (333 rows) loaded from penguins.csv
  • Data exploration: species count, island-wise count and mean measurements
  • Nearest-centroid model on z-score scaled features with 80:20 train-test split
  • Evaluation: accuracy, confusion matrix and per-species precision / recall
  • Experiment: accuracy with 1, 2 and 3 features
  • Deployment: predict species of a new penguin with distance to each centroid
โ˜ฐ Main menu
1Explore DataShape, counts and averages
2Train ModelSplit, scale, compute centroids
3EvaluateAccuracy and confusion matrix
4Per-class ReportPrecision and recall per species
5Feature ExperimentAccuracy with different feature sets
6Predict New PenguinInput measurements
7ChartsScatter, box plot, accuracy bar
0ExitEnds program
๐ŸŽฏ Objectives
  • Explore a real dataset with Pandas (shape, species count, group means)
  • Build a nearest-centroid classifier using NumPy and evaluate it with a train-test split
  • Visualise how bill length and bill depth separate the species
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFramePenguins data (species, island, bill, flipper, mass)
featureslistColumns used by the model
mu, sdSeriesMean and std of training data for scaling
centroidsDataFrameMean scaled point of each species
Why it matters: Covers the full AI project cycle on a real scientific dataset - the same use case CBSE walks through in Orange Data Mining, now done in Python.
# =====================================================================
#   PALMER PENGUIN SPECIES PREDICTOR  (Statistical Data domain)
#   AI project cycle: explore -> train -> evaluate -> deploy
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("penguins.csv")
ALL = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm"]
model = {}


def explore():
    print("Dataset shape:", df.shape)
    print("\nSpecies count:\n" + df["species"].value_counts().to_string())
    print("\nSpecies on each island:\n", pd.crosstab(df["island"], df["species"]))
    print("\nAverage measurements:\n", df.groupby("species")[ALL + ["body_mass_g"]].mean().round(1))


def fit(features, seed=7):
    d = df.sample(frac=1, random_state=seed).reset_index(drop=True)
    cut = int(len(d) * 0.8)
    train, test = d[:cut], d[cut:]
    mu, sd = train[features].mean(), train[features].std()
    z = (train[features] - mu) / sd
    z["species"] = train["species"]
    return {"f": features, "mu": mu, "sd": sd, "cent": z.groupby("species")[features].mean(), "train": train, "test": test}


def predict(m, row):
    z = (np.array(row, dtype=float) - m["mu"].values) / m["sd"].values
    dist = np.sqrt(((m["cent"].values - z) ** 2).sum(axis=1))
    return m["cent"].index[np.argmin(dist)], dist


def train_model():
    model.clear()
    model.update(fit(ALL))
    print("Training rows:", len(model["train"]), "| Testing rows:", len(model["test"]))
    print("Learnt centroids (scaled):\n", model["cent"].round(3))


def preds(m):
    return [predict(m, r)[0] for r in m["test"][m["f"]].values]


def evaluate():
    p = preds(model)
    a = model["test"]["species"].values
    acc = (np.array(p) == a).mean() * 100
    print(f"Correct: {(np.array(p) == a).sum()} / {len(a)}  ->  Accuracy {acc:.2f} %")
    print(pd.crosstab(a, np.array(p), rownames=["Actual"], colnames=["Predicted"]))


def per_class():
    p, a = np.array(preds(model)), model["test"]["species"].values
    print(f"{'Species':<11}{'Precision':>10}{'Recall':>8}{'Support':>9}")
    for sp in sorted(set(a)):
        tp = ((p == sp) & (a == sp)).sum()
        pr = tp / max((p == sp).sum(), 1)
        rc = tp / (a == sp).sum()
        print(f"{sp:<11}{pr:>10.2f}{rc:>8.2f}{(a == sp).sum():>9}")


def experiment():
    sets = [["flipper_length_mm"], ["bill_length_mm", "bill_depth_mm"], ALL]
    res = []
    for f in sets:
        m = fit(f)
        acc = (np.array(preds(m)) == m["test"]["species"].values).mean() * 100
        res.append(acc)
        short = {"bill_length_mm": "bill length", "bill_depth_mm": "bill depth", "flipper_length_mm": "flipper"}
        print(f"{' + '.join(short[x] for x in f):<36} accuracy {acc:6.2f} %")
    print("Best feature set: option", res.index(max(res)) + 1, "- more useful features -> better model")
    return res


def new_penguin():
    row = [float(input("Bill length (mm)   : ")), float(input("Bill depth (mm)    : ")), float(input("Flipper length (mm): "))]
    sp, dist = predict(model, row)
    for name, d in zip(model["cent"].index, dist):
        print(f"  distance to {name:<10}: {d:.3f}")
    print("Predicted species:", sp)


def charts():
    colors = {"Adelie": "tab:orange", "Chinstrap": "tab:purple", "Gentoo": "tab:green"}
    for sp, g in df.groupby("species"):
        plt.scatter(g["bill_length_mm"], g["bill_depth_mm"], s=18, c=colors[sp], label=sp)
    plt.xlabel("Bill length (mm)"); plt.ylabel("Bill depth (mm)"); plt.title("Bill length vs bill depth"); plt.legend()
    plt.savefig("penguin_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
    df.boxplot(column="flipper_length_mm", by="species", grid=False)
    plt.suptitle(""); plt.title("Flipper length by species"); plt.ylabel("mm")
    plt.savefig("penguin_box.png", dpi=90, bbox_inches="tight"); plt.show()
    res = experiment()
    plt.bar(["Flipper only", "Bill (2)", "All 3"], res, color=["#90caf9", "#42a5f5", "#1565c0"])
    plt.ylim(0, 105); plt.ylabel("Accuracy %"); plt.title("Effect of features on accuracy")
    plt.savefig("penguin_accuracy.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: penguin_scatter.png, penguin_box.png, penguin_accuracy.png")


print("=" * 55)
print("   PALMER PENGUIN SPECIES PREDICTOR")
print("=" * 55)
while True:
    print("\n1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        explore()
    elif ch == "2":
        train_model()
    elif ch in "34567" and not model:
        print("Train the model first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        per_class()
    elif ch == "5":
        experiment()
    elif ch == "6":
        new_penguin()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Load penguins.csv
  3. Show menu and read choice
  4. Model trained? → No: train first (option 2)
  5. Scale input with training mean / std
  6. Find nearest centroid
  7. Show species and distances
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Explore333 rows, 3 speciesPASS
2Evaluate before training'Train the model first'PASS
3Train266 train / 67 testPASS
4EvaluateAccuracy 92.54 % (62/67)PASS
5Per-class reportPrecision / recallPASS
6Experiment76 % -> 87 % -> 93 % as features are addedPASS
7Predict 47.5, 15.0, 217GentooPASS
8Predict 39, 18.5, 185AdeliePASS
โš  Limitations
  • Simple distance model (no sklearn)
  • Body mass and island not used
  • Small dataset
  • Assumes clean data
๐Ÿš€ Future scope
  • Use KNN / decision tree in scikit-learn
  • Add body mass and sex
  • Web app for field researchers
  • Cross-validation

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 5): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: df, ALL, model.
  3. 10 functions are defined (lines 14โ€“100) - Python stores them but does NOT run them yet.
  4. Main program starts at line 103: print("=" * 55) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
explore()14โ€“18Exploremain program
fit(features, seed)21โ€“28Fittrain_model(), experiment()
predict(m, row)31โ€“34Predictpreds(), new_penguin()
train_model()37โ€“41Train modelmain program
preds(m)44โ€“45Predsevaluate(), per_class(), experiment()
evaluate()48โ€“53Evaluatemain program
per_class()56โ€“63Per classmain program
experiment()66โ€“76Experimentcharts(), main program
new_penguin()79โ€“84New penguinmain program
charts()87โ€“100Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
103
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
104
print("   PALMER PENGUIN SPECIES PREDICTOR")
๐Ÿ–ฅ๏ธ Output Displays the text "PALMER PENGUIN SPECIES PREDICTOR" on the screen
105
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
106
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
107
print("\n1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Explore 2.Train 3.Evaluate 4.Peโ€ฆ" on the screen
108
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
109
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
110
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
111
break
๐Ÿ” Loop BREAK - leaves the loop immediately
112
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
113
explore()
๐Ÿงฎ Store / Calculate Calls our own function explore()
114
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
115
train_model()
๐Ÿงฎ Store / Calculate Calls our own function train_model()
116
elif ch in "34567" and not model:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (ch is present in "34567" AND model is False (or empty / zero))
117
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
118
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
119
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
120
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
121
per_class()
๐Ÿงฎ Store / Calculate Calls our own function per_class()
122
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
123
experiment()
๐Ÿงฎ Store / Calculate Calls our own function experiment()
124
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
125
new_penguin()
๐Ÿงฎ Store / Calculate Calls our own function new_penguin()
126
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
127
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
128
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
129
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: PALMER PENGUIN SPECIES PREDICTOR (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: explore()
    shows: Dataset shape: (333, 8) (+18 more lines)
  4. You type 2 at Enter choice:
    runs: train_model() โ†’ fit()
    shows: Training rows: 266 | Testing rows: 67 (+7 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate() โ†’ preds() โ†’ predict() ร—67
    shows: Correct: 62 / 67 -> Accuracy 92.54 % (+6 more lines)
  6. You type 4 at Enter choice:
    runs: per_class() โ†’ preds() โ†’ predict() ร—67
    shows: Species Precision Recall Support (+4 more lines)
  7. You type 5 at Enter choice:
    runs: experiment() โ†’ fit() โ†’ preds() โ†’ predict() ร—67 โ†’ fit() โ†’ preds() โ†’ predict() ร—67 โ†’ fit()
    shows: flipper accuracy 76.12 % (+4 more lines)
  8. You type 6 at Enter choice:
    runs: new_penguin()
  9. You type 47.5 at Bill length (mm) :
  10. You type 15.0 at Bill depth (mm) :
  11. You type 217 at Flipper length (mm):
    runs: predict()
    shows: distance to Adelie : 3.027 (+4 more lines)
  12. You type 6 at Enter choice:
    runs: new_penguin()
  13. You type 39 at Bill length (mm) :
  14. You type 18.5 at Bill depth (mm) :
  15. You type 185 at Flipper length (mm):
    runs: predict()
    shows: distance to Adelie : 0.391 (+4 more lines)
  16. You type 7 at Enter choice:
    runs: charts() โ†’ experiment() โ†’ fit() โ†’ preds() โ†’ predict() ร—67 โ†’ fit() โ†’ preds() โ†’ predict() ร—67
    shows: [chart is drawn] (+8 more lines)
  17. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
explore() - lines 14โ€“18
LineCodeWhat it does
14
def explore():
๐Ÿงฉ Function DEFINES a function explore(). Python only remembers it here - its body runs later, each time explore() is called.
15
print("Dataset shape:", df.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Dataset shape:", then the value of df.shape on the screen
16
print("\nSpecies count:\n" + df["species"].value_counts().to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "\nSpecies count:\n" + df["species"].value_coโ€ฆ on the screen
17
print("\nSpecies on each island:\n", pd.crosstab(df["island"], df["species"]))
๐Ÿ–ฅ๏ธ Output Displays the text "Species on each island:", then the value of pd.crosstab(df["island"], df["species"]) on the screen
18
print("\nAverage measurements:\n", df.groupby("species")[ALL + ["body_mass_g"]].mean().round(1))
๐Ÿ–ฅ๏ธ Output Displays the text "Average measurements:", then the value of df.groupby("species")[ALL + ["body_mass_g"]].โ€ฆ on the screen
fit() - lines 21โ€“28
LineCodeWhat it does
21
def fit(features, seed=7):
๐Ÿงฉ Function DEFINES a function fit(features, seed). Python only remembers it here - its body runs later, each time fit() is called.
22
d = df.sample(frac=1, random_state=seed).reset_index(drop=True)
๐Ÿ“ฆ Library / Data Turns the index of df.sample(frac=1, random_state=seed) back into a column; the result is stored in variable d
23
cut = int(len(d) * 0.8)
๐Ÿงฎ Store / Calculate Converts len(d) * 0.8 into a whole number (int); the result is stored in variable cut
24
train, test = d[:cut], d[cut:]
๐Ÿงฎ Store / Calculate Stores d[:cut], d[cut:] into train, test respectively
25
mu, sd = train[features].mean(), train[features].std()
๐Ÿงฎ Store / Calculate Stores train[features].mean(), train[features].std() into mu, sd respectively
26
z = (train[features] - mu) / sd
๐Ÿงฎ Store / Calculate Stores the value of (train[features] - mu) / sd (calculated using รท) in variable z
27
z["species"] = train["species"]
๐Ÿงฎ Store / Calculate Puts the item train["species"] into z["species"] (item "species" of z)
28
return {"f": features, "mu": mu, "sd": sd, "cent": z.groupby("species")[features].mean(), "train": train, "test": test}
๐Ÿงฉ Function Sends back (returns) a dictionary {"f": features, "mu": mu, "sd": sd, "cent": zโ€ฆ to the line that called the function
predict() - lines 31โ€“34
LineCodeWhat it does
31
def predict(m, row):
๐Ÿงฉ Function DEFINES a function predict(m, row). Python only remembers it here - its body runs later, each time predict() is called.
32
z = (np.array(row, dtype=float) - m["mu"].values) / m["sd"].values
๐Ÿ“ฆ Library / Data Stores the value of (np.array(row, dtype=float) - m["mu"].values)โ€ฆ (calculated using รท) in variable z
33
dist = np.sqrt(((m["cent"].values - z) ** 2).sum(axis=1))
๐Ÿ“ฆ Library / Data Finds the square root of ((m["cent"].values - z) ** 2).sum(axis=1); the result is stored in variable dist
34
return m["cent"].index[np.argmin(dist)], dist
๐Ÿงฉ Function Sends back (returns) the tuple m["cent"].index[np.argmin(dist)], dist to the line that called the function
train_model() - lines 37โ€“41
LineCodeWhat it does
37
def train_model():
๐Ÿงฉ Function DEFINES a function train_model(). Python only remembers it here - its body runs later, each time train_model() is called.
38
model.clear()
๐Ÿงฎ Store / Calculate Removes all items from model
39
model.update(fit(ALL))
๐Ÿงฎ Store / Calculate Updates model with fit(ALL)
40
print("Training rows:", len(model["train"]), "| Testing rows:", len(model["test"]))
๐Ÿ–ฅ๏ธ Output Displays the text "Training rows:", then the value of len(model["train"]), then the text "| Testing rows:", then the value of len(model["test"]) on the screen
41
print("Learnt centroids (scaled):\n", model["cent"].round(3))
๐Ÿ–ฅ๏ธ Output Displays the text "Learnt centroids (scaled):", then the value of model["cent"].round(3) on the screen
preds() - lines 44โ€“45
LineCodeWhat it does
44
def preds(m):
๐Ÿงฉ Function DEFINES a function preds(m). Python only remembers it here - its body runs later, each time preds() is called.
45
return [predict(m, r)[0] for r in m["test"][m["f"]].values]
๐Ÿงฉ Function Sends back (returns) a new list made by a list comprehension [predict(m, r)[0] for r in m["test"][m["f"]].โ€ฆ to the line that called the function
evaluate() - lines 48โ€“53
LineCodeWhat it does
48
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
49
p = preds(model)
๐Ÿงฎ Store / Calculate Calls our own function preds(model); the result is stored in variable p
50
a = model["test"]["species"].values
๐Ÿงฎ Store / Calculate Stores model["test"]["species"].values in variable a
51
acc = (np.array(p) == a).mean() * 100
๐Ÿ“ฆ Library / Data Stores the value of (np.array(p) == a).mean() * 100 (calculated using ร—) in variable acc
52
print(f"Correct: {(np.array(p) == a).sum()} / {len(a)}  ->  Accuracy {acc:.2f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Correct: {(np.array(p) == a).sum()} / {len(โ€ฆ with the values filled into { } on the screen
53
print(pd.crosstab(a, np.array(p), rownames=["Actual"], colnames=["Predicted"]))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.crosstab(a, np.array(p), rownames=["Actualโ€ฆ on the screen
per_class() - lines 56โ€“63
LineCodeWhat it does
56
def per_class():
๐Ÿงฉ Function DEFINES a function per_class(). Python only remembers it here - its body runs later, each time per_class() is called.
57
p, a = np.array(preds(model)), model["test"]["species"].values
๐Ÿ“ฆ Library / Data Stores np.array(preds(model)), model["test"]["species"].values into p, a respectively
58
print(f"{'Species':<11}{'Precision':>10}{'Recall':>8}{'Support':>9}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Species':<11}{'Precision':>10}{'Recall':>โ€ฆ with the values filled into { } on the screen
59
for sp in sorted(set(a)):
๐Ÿ” Loop LOOP: takes each item of sorted(set(a)) one-by-one into sp and runs the indented block for it
60
tp = ((p == sp) & (a == sp)).sum()
๐Ÿงฎ Store / Calculate Adds up all values of (p == sp) & (a == sp); the result is stored in variable tp
61
pr = tp / max((p == sp).sum(), 1)
๐Ÿงฎ Store / Calculate Stores the value of tp / max((p == sp).sum(), 1) (calculated using รท) in variable pr
62
rc = tp / (a == sp).sum()
๐Ÿงฎ Store / Calculate Stores the value of tp / (a == sp).sum() (calculated using รท) in variable rc
63
print(f"{sp:<11}{pr:>10.2f}{rc:>8.2f}{(a == sp).sum():>9}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{sp:<11}{pr:>10.2f}{rc:>8.2f}{(a == sp).sumโ€ฆ with the values filled into { } on the screen
experiment() - lines 66โ€“76
LineCodeWhat it does
66
def experiment():
๐Ÿงฉ Function DEFINES a function experiment(). Python only remembers it here - its body runs later, each time experiment() is called.
67
sets = [["flipper_length_mm"], ["bill_length_mm", "bill_depth_mm"], ALL]
๐Ÿงฎ Store / Calculate Stores a list [["flipper_length_mm"], ["bill_length_mm", "bโ€ฆ in variable sets
68
res = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable res
69
for f in sets:
๐Ÿ” Loop LOOP: takes each item of sets one-by-one into f and runs the indented block for it
70
m = fit(f)
๐Ÿงฎ Store / Calculate Calls our own function fit(f); the result is stored in variable m
71
acc = (np.array(preds(m)) == m["test"]["species"].values).mean() * 100
๐Ÿ“ฆ Library / Data Stores the value of (np.array(preds(m)) == m["test"]["species"].vโ€ฆ (calculated using ร—) in variable acc
72
res.append(acc)
๐Ÿงฎ Store / Calculate Adds acc at the end of list res
73
short = {"bill_length_mm": "bill length", "bill_depth_mm": "bill depth", "flipper_length_mm": "flipper"}
๐Ÿงฎ Store / Calculate Stores a dictionary {"bill_length_mm": "bill length", "bill_depthโ€ฆ in variable short
74
print(f"{' + '.join(short[x] for x in f):<36} accuracy {acc:6.2f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{' + '.join(short[x] for x in f):<36} accurโ€ฆ with the values filled into { } on the screen
75
print("Best feature set: option", res.index(max(res)) + 1, "- more useful features -> better model")
๐Ÿ–ฅ๏ธ Output Displays the text "Best feature set: option", then the value of res.index(max(res)) + 1, then the text "- more useful features -> better โ€ฆ" on the screen
76
return res
๐Ÿงฉ Function Sends back (returns) the value of res to the line that called the function
new_penguin() - lines 79โ€“84
LineCodeWhat it does
79
def new_penguin():
๐Ÿงฉ Function DEFINES a function new_penguin(). Python only remembers it here - its body runs later, each time new_penguin() is called.
80
row = [float(input("Bill length (mm)   : ")), float(input("Bill depth (mm)    : ")), float(input("Flipper length (mm): "))]
โŒจ๏ธ Input Stores a list [float(input("Bill length (mm) : ")), float(iโ€ฆ in variable row
81
sp, dist = predict(model, row)
๐Ÿงฎ Store / Calculate Calls our own function predict(model, row); the result is stored in variables sp, dist
82
for name, d in zip(model["cent"].index, dist):
๐Ÿ” Loop LOOP that walks through model["cent"].index, dist together; name, d get one item from each
83
print(f"  distance to {name:<10}: {d:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" distance to {name:<10}: {d:.3f}" with the values filled into { } on the screen
84
print("Predicted species:", sp)
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted species:", then the value of sp on the screen
charts() - lines 87โ€“100
LineCodeWhat it does
87
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
88
colors = {"Adelie": "tab:orange", "Chinstrap": "tab:purple", "Gentoo": "tab:green"}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Adelie": "tab:orange", "Chinstrap": "tab:puโ€ฆ in variable colors
89
for sp, g in df.groupby("species"):
๐Ÿ” Loop LOOP: takes each item of df.groupby("species") one-by-one into sp, g and runs the indented block for it
90
plt.scatter(g["bill_length_mm"], g["bill_depth_mm"], s=18, c=colors[sp], label=sp)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of g["bill_length_mm"], g["bill_depth_mm"]
91
plt.xlabel("Bill length (mm)"); plt.ylabel("Bill depth (mm)"); plt.title("Bill length vs bill depth"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Bill length (mm)" as the label of the X-axis
91
plt.xlabel("Bill length (mm)"); plt.ylabel("Bill depth (mm)"); plt.title("Bill length vs bill depth"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Bill depth (mm)" as the label of the Y-axis
91
plt.xlabel("Bill length (mm)"); plt.ylabel("Bill depth (mm)"); plt.title("Bill length vs bill depth"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Bill length vs bill depth" as the title of the chart
91
plt.xlabel("Bill length (mm)"); plt.ylabel("Bill depth (mm)"); plt.title("Bill length vs bill depth"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
92
plt.savefig("penguin_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "penguin_scatter.png"
92
plt.savefig("penguin_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
93
df.boxplot(column="flipper_length_mm", by="species", grid=False)
๐Ÿ“ฆ Library / Data Draws a box plot of
94
plt.suptitle(""); plt.title("Flipper length by species"); plt.ylabel("mm")
๐Ÿ–ฅ๏ธ Output Sets the main title of the figure
94
plt.suptitle(""); plt.title("Flipper length by species"); plt.ylabel("mm")
๐Ÿ–ฅ๏ธ Output Writes "Flipper length by species" as the title of the chart
94
plt.suptitle(""); plt.title("Flipper length by species"); plt.ylabel("mm")
๐Ÿ–ฅ๏ธ Output Writes "mm" as the label of the Y-axis
95
plt.savefig("penguin_box.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "penguin_box.png"
95
plt.savefig("penguin_box.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
96
res = experiment()
๐Ÿงฎ Store / Calculate Calls our own function experiment(); the result is stored in variable res
97
plt.bar(["Flipper only", "Bill (2)", "All 3"], res, color=["#90caf9", "#42a5f5", "#1565c0"])
๐Ÿ–ฅ๏ธ Output Draws a bar chart of ["Flipper only", "Bill (2)", "All 3"], res
98
plt.ylim(0, 105); plt.ylabel("Accuracy %"); plt.title("Effect of features on accuracy")
๐Ÿ–ฅ๏ธ Output Sets the range of the Y-axis
98
plt.ylim(0, 105); plt.ylabel("Accuracy %"); plt.title("Effect of features on accuracy")
๐Ÿ–ฅ๏ธ Output Writes "Accuracy %" as the label of the Y-axis
98
plt.ylim(0, 105); plt.ylabel("Accuracy %"); plt.title("Effect of features on accuracy")
๐Ÿ–ฅ๏ธ Output Writes "Effect of features on accuracy" as the title of the chart
99
plt.savefig("penguin_accuracy.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "penguin_accuracy.png"
99
plt.savefig("penguin_accuracy.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
100
print("Charts saved: penguin_scatter.png, penguin_box.png, penguin_accuracy.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: penguin_scatter.pngโ€ฆ" on the screen
Q1. Which AI domain is this?

Statistical Data / Data Science - learning from numbers in a table.

Q2. Why is data split into training and testing?

The model learns from training data; testing data checks performance on unseen data.

Q3. Why scale features?

Flipper length (~200) is bigger than bill depth (~17); z-scores give each feature equal weight in distance.

Q4. What is a centroid?

The mean point of all training samples of a class.

Q5. What is a confusion matrix?

A table of actual vs predicted classes showing correct and wrong predictions.

02

Coral Bleaching Early Detector (Computer Vision)

PYTHON + OPENCVSDG 14 - Life Below WaterOpenCV imreadBGR to HSV conversionpixel masksNumPy percentagethreshold-based classification
๐Ÿ“ 119 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

CBSE sample project 2: analyses underwater reef photos and estimates the percentage of bleached (white, low-colour) coral pixels using the HSV colour space; reefs above a threshold are flagged for early action.

โœจ Features
  • Six reef photographs simulated and saved as images (OpenCV drawing)
  • Image converted BGR -> HSV; bleached (white) pixels found using low saturation + high brightness
  • Bleaching % per image and status (Healthy / Monitor / ALERT)
  • Adjustable thresholds to study their effect
  • Mask view showing which pixels were detected
  • Reef report with average and alert list
โ˜ฐ Main menu
1Generate / Load ImagesCreates reef images
2Analyse AllBleaching % for each image
3Change ThresholdsSaturation and brightness limits
4Alert ReportReefs needing attention
5Pixel InspectorHSV values at a point
6ChartsImage grid, bar chart, mask
0ExitEnds program
๐ŸŽฏ Objectives
  • Read images and convert colour spaces with OpenCV
  • Extract a feature - percentage of bleached pixels - using NumPy masks
  • Classify each reef photo as Healthy, Partly bleached or Severely bleached
๐Ÿ“š Data dictionary
NameTypePurpose
folderstrcoral_images directory
S_MAX, V_MINintThresholds for 'white' pixels
resultslist(name, image, %, status)
maskbool arrayTrue where pixel is bleached
Why it matters: Demonstrates how pixels, colour channels and simple image features can drive a real environmental early-warning system.
# =====================================================================
#   CORAL BLEACHING EARLY DETECTOR  (Computer Vision domain, SDG 14)
# =====================================================================
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt

folder = "coral_images"
S_MAX, V_MIN = 60, 170
results = []


def generate():
    os.makedirs(folder, exist_ok=True)
    rng = np.random.default_rng(3)
    for i, white in enumerate([0.03, 0.10, 0.22, 0.30, 0.48, 0.65]):
        img = np.zeros((120, 160, 3), np.uint8)
        img[:] = (150, 90, 20)                                  # blue water (BGR)
        for _ in range(60):
            x, y = rng.integers(10, 150), rng.integers(30, 115)
            bleached = rng.random() < white * 1.6
            col = (235, 240, 245) if bleached else tuple(int(c) for c in rng.choice(
                [(60, 80, 220), (40, 160, 240), (180, 60, 200), (70, 200, 120)]))
            cv2.circle(img, (int(x), int(y)), int(rng.integers(5, 13)), col, -1)
        cv2.imwrite(os.path.join(folder, "reef_%d.jpg" % (i + 1)), img)
    print(len(os.listdir(folder)), "reef images ready in", folder)


def bleach_mask(img):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    return (hsv[:, :, 1] < S_MAX) & (hsv[:, :, 2] > V_MIN)


def status(p):
    return "Severely bleached - ALERT" if p >= 40 else "Partly bleached - monitor" if p >= 15 else "Healthy"


def analyse():
    if not os.path.exists(folder):
        generate()
    results.clear()
    print(f"Thresholds: S < {S_MAX}, V > {V_MIN}")
    print("{:<12}{:>12}  {}".format("Image", "Bleached %", "Status"))
    for name in sorted(os.listdir(folder)):
        img = cv2.imread(os.path.join(folder, name))
        pct = bleach_mask(img).mean() * 100
        results.append((name, img, pct, status(pct)))
        print("{:<12}{:>11.1f}%  {}".format(name, pct, status(pct)))
    print("Average bleaching:", round(np.mean([r[2] for r in results]), 1), "%")


def thresholds():
    global S_MAX, V_MIN
    S_MAX = int(input("Max saturation for white (0-255): "))
    V_MIN = int(input("Min brightness for white (0-255): "))
    print("Thresholds updated - run Analyse again.")


def alerts():
    if not results:
        analyse()
    for name, img, pct, st in sorted(results, key=lambda r: -r[2]):
        if pct >= 15:
            print(f"{name}: {pct:.1f}% -> {st}")
    print("Healthy reefs:", [r[0] for r in results if r[2] < 15])


def inspector():
    img = cv2.imread(os.path.join(folder, "reef_%s.jpg" % input("Image number (1-6): ")))
    x, y = int(input("x (0-159): ")), int(input("y (0-119): "))
    b, g, r = img[y, x]
    h, s, v = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[y, x]
    print(f"BGR = ({b},{g},{r})  HSV = ({h},{s},{v})  -> {'WHITE (bleached)' if s < S_MAX and v > V_MIN else 'coloured / water'}")


def charts():
    if not results:
        analyse()
    fig, axes = plt.subplots(2, 3, figsize=(9, 5))
    for ax, (name, img, pct, st) in zip(axes.ravel(), results):
        ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax.set_title(f"{name}\n{pct:.0f}% - {st.split(' -')[0]}", fontsize=9); ax.axis("off")
    plt.suptitle("Coral bleaching analysis"); plt.tight_layout(); plt.savefig("coral_results.png", dpi=90); plt.show()
    pc = [r[2] for r in results]
    plt.bar([r[0][:-4] for r in results], pc, color=["red" if p >= 40 else "orange" if p >= 15 else "green" for p in pc])
    plt.axhline(40, ls="--", c="red"); plt.axhline(15, ls="--", c="orange")
    plt.ylabel("Bleached %"); plt.title("Bleaching level of each reef"); plt.savefig("coral_bars.png", dpi=90, bbox_inches="tight"); plt.show()
    img = results[-1][1]
    fig, ax = plt.subplots(1, 2, figsize=(8, 3))
    ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax[0].set_title("Original"); ax[0].axis("off")
    ax[1].imshow(bleach_mask(img), cmap="gray"); ax[1].set_title("Detected white pixels (mask)"); ax[1].axis("off")
    plt.tight_layout(); plt.savefig("coral_mask.png", dpi=90); plt.show()
    print("Charts saved: coral_results.png, coral_bars.png, coral_mask.png")


print("=" * 55)
print("   CORAL BLEACHING EARLY DETECTOR  (Computer Vision)")
print("=" * 55)
while True:
    print("\n1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Save our reefs!")
        break
    elif ch == "1":
        generate()
    elif ch == "2":
        analyse()
    elif ch == "3":
        thresholds()
    elif ch == "4":
        alerts()
    elif ch == "5":
        inspector()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Images exist? → No: generate images
  4. Read image, convert to HSV
  5. mask = (S < S_MAX) & (V > V_MIN)
  6. % = mask pixels / total
  7. % >= 40? → No: check >= 15
  8. Status and report
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Analyse before imagesImages generated firstPASS
2Analyse6 images with %PASS
3reef_6ALERTPASS
4reef_1HealthyPASS
5Thresholds 80/150More pixels detectedPASS
6Pixel (40,60)HSV valuesPASS
7Charts3 PNG filesPASS
โš  Limitations
  • Simulated images, not real underwater photos
  • Sand / foam may be counted as white
  • Lighting affects thresholds
  • No deep-learning model
๐Ÿš€ Future scope
  • Train a CNN on real reef image datasets
  • Underwater drone camera
  • Track the same reef over months
  • GPS map of alerts

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): os - file and folder operations, cv2 - OpenCV image processing, numpy - fast arrays and maths, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: folder, results.
  3. 8 functions are defined (lines 14โ€“93) - Python stores them but does NOT run them yet.
  4. Main program starts at line 10: S_MAX, V_MIN = 60, 170 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
generate()14โ€“27Generateanalyse(), main program
bleach_mask(img)30โ€“32Bleach maskanalyse(), charts()
status(p)35โ€“36Statusanalyse()
analyse()39โ€“50Analysealerts(), charts(), main program
thresholds()53โ€“57Thresholdsmain program
alerts()60โ€“66Alertsmain program
inspector()69โ€“74Inspectormain program
charts()77โ€“93Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
10
S_MAX, V_MIN = 60, 170
๐Ÿงฎ Store / Calculate Stores 60, 170 into S_MAX, V_MIN respectively
11
results = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable results
96
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
97
print("   CORAL BLEACHING EARLY DETECTOR  (Computer Vision)")
๐Ÿ–ฅ๏ธ Output Displays the text "CORAL BLEACHING EARLY DETECTOR (Cโ€ฆ" on the screen
98
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
99
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
100
print("\n1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Generate 2.Analyse 3.Thresholdsโ€ฆ" on the screen
101
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
102
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
103
print("Save our reefs!")
๐Ÿ–ฅ๏ธ Output Displays the text "Save our reefs!" on the screen
104
break
๐Ÿ” Loop BREAK - leaves the loop immediately
105
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
106
generate()
๐Ÿงฎ Store / Calculate Calls our own function generate()
107
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
108
analyse()
๐Ÿงฎ Store / Calculate Calls our own function analyse()
109
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
110
thresholds()
๐Ÿงฎ Store / Calculate Calls our own function thresholds()
111
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
112
alerts()
๐Ÿงฎ Store / Calculate Calls our own function alerts()
113
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
114
inspector()
๐Ÿงฎ Store / Calculate Calls our own function inspector()
115
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
116
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
117
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
118
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Inside each function - line by line
generate() - lines 14โ€“27
LineCodeWhat it does
14
def generate():
๐Ÿงฉ Function DEFINES a function generate(). Python only remembers it here - its body runs later, each time generate() is called.
15
os.makedirs(folder, exist_ok=True)
๐Ÿ“ File Creates folder folder
16
rng = np.random.default_rng(3)
๐Ÿ“ฆ Library / Data Creates a random number generator with seed 3; the result is stored in variable rng
17
for i, white in enumerate([0.03, 0.10, 0.22, 0.30, 0.48, 0.65]):
๐Ÿ” Loop LOOP over [0.03, 0.10, 0.22, 0.30, 0.48, 0.65] with position: in each round i, white get (position, item)
18
img = np.zeros((120, 160, 3), np.uint8)
๐Ÿ“ฆ Library / Data Makes a NumPy array filled with 0s; the result is stored in variable img
19
img[:] = (150, 90, 20)                                  # blue water (BGR)
๐Ÿงฎ Store / Calculate Puts the tuple (150, 90, 20) into img[:] (item : of img)
20
for _ in range(60):
๐Ÿ” Loop LOOP: gives the numbers 0 to 59 (60 numbers); for each number, _ takes that value and the indented block runs once
21
x, y = rng.integers(10, 150), rng.integers(30, 115)
๐Ÿงฎ Store / Calculate Stores rng.integers(10, 150), rng.integers(30, 115) into x, y respectively
22
bleached = rng.random() < white * 1.6
๐Ÿงฎ Store / Calculate Stores True/False for rng.random() is less than white * 1.6 in variable bleached
23
col = (235, 240, 245) if bleached else tuple(int(c) for c in rng.choice(
    [(60, 80, 220), (40, 160, 240), (180, 60, 200), (70, 200, 120)]))
๐Ÿงฎ Store / Calculate Stores either (235, 240, 245) or tuple(int(c) for c in rng.choice( [(60, 80, 2โ€ฆ depending on bleached in variable col
25
cv2.circle(img, (int(x), int(y)), int(rng.integers(5, 13)), col, -1)
๐Ÿ“ฆ Library / Data Calls cv2.circle(img, (int(x), int(y)), iโ€ฆ)
26
cv2.imwrite(os.path.join(folder, "reef_%d.jpg" % (i + 1)), img)
๐Ÿ“ File Saves the image to file os.path.join(folder, "reef_%d.jpg" % (i + 1))
27
print(len(os.listdir(folder)), "reef images ready in", folder)
๐Ÿ“ File Displays the value of len(os.listdir(folder)), then the text "reef images ready in", then the value of folder on the screen
bleach_mask() - lines 30โ€“32
LineCodeWhat it does
30
def bleach_mask(img):
๐Ÿงฉ Function DEFINES a function bleach_mask(img). Python only remembers it here - its body runs later, each time bleach_mask() is called.
31
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
๐Ÿ“ฆ Library / Data Converts the colour format of the image; the result is stored in variable hsv
32
return (hsv[:, :, 1] < S_MAX) & (hsv[:, :, 2] > V_MIN)
๐Ÿงฉ Function Sends back (returns) the value of (hsv[:, :, 1] < S_MAX) & (hsv[:, :, 2] > V_MIโ€ฆ (calculated using the operator) to the line that called the function
status() - lines 35โ€“36
LineCodeWhat it does
35
def status(p):
๐Ÿงฉ Function DEFINES a function status(p). Python only remembers it here - its body runs later, each time status() is called.
36
return "Severely bleached - ALERT" if p >= 40 else "Partly bleached - monitor" if p >= 15 else "Healthy"
๐Ÿงฉ Function Sends back (returns) either "Severely bleached - ALERT" or "Partly bleached - monitor" if p >= 15 else "โ€ฆ depending on p >= 40 to the line that called the function
analyse() - lines 39โ€“50
LineCodeWhat it does
39
def analyse():
๐Ÿงฉ Function DEFINES a function analyse(). Python only remembers it here - its body runs later, each time analyse() is called.
40
if not os.path.exists(folder):
๐Ÿ”€ Decision CHECKS whether NOT os.path.exists(folder) is True. If True, the indented lines below run; otherwise they are skipped
41
generate()
๐Ÿงฎ Store / Calculate Calls our own function generate()
42
results.clear()
๐Ÿงฎ Store / Calculate Removes all items from results
43
print(f"Thresholds: S < {S_MAX}, V > {V_MIN}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Thresholds: S < {S_MAX}, V > {V_MIN}" with the values filled into { } on the screen
44
print("{:<12}{:>12}  {}".format("Image", "Bleached %", "Status"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<12}{:>12} {}".format("Image", "Bleached %โ€ฆ on the screen
45
for name in sorted(os.listdir(folder)):
๐Ÿ” Loop LOOP: takes each item of sorted(os.listdir(folder)) one-by-one into name and runs the indented block for it
46
img = cv2.imread(os.path.join(folder, name))
๐Ÿ“ File Reads the image file os.path.join(folder, name) into a NumPy array of pixels; the result is stored in variable img
47
pct = bleach_mask(img).mean() * 100
๐Ÿงฎ Store / Calculate Stores the value of bleach_mask(img).mean() * 100 (calculated using ร—) in variable pct
48
results.append((name, img, pct, status(pct)))
๐Ÿงฎ Store / Calculate Adds (name, img, pct, status(pct)) at the end of list results
49
print("{:<12}{:>11.1f}%  {}".format(name, pct, status(pct)))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<12}{:>11.1f}% {}".format(name, pct, statuโ€ฆ on the screen
50
print("Average bleaching:", round(np.mean([r[2] for r in results]), 1), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Average bleaching:", then the value of round(np.mean([r[2] for r in results]), 1), then the text "%" on the screen
thresholds() - lines 53โ€“57
LineCodeWhat it does
53
def thresholds():
๐Ÿงฉ Function DEFINES a function thresholds(). Python only remembers it here - its body runs later, each time thresholds() is called.
54
global S_MAX, V_MIN
๐Ÿงฉ Function Tells Python that S_MAX, V_MIN means the GLOBAL variable (outside the function)
55
S_MAX = int(input("Max saturation for white (0-255): "))
โŒจ๏ธ Input Shows "Max saturation for white (0-255): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable S_MAX
56
V_MIN = int(input("Min brightness for white (0-255): "))
โŒจ๏ธ Input Shows "Min brightness for white (0-255): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable V_MIN
57
print("Thresholds updated - run Analyse again.")
๐Ÿ–ฅ๏ธ Output Displays the text "Thresholds updated - run Analyse โ€ฆ" on the screen
alerts() - lines 60โ€“66
LineCodeWhat it does
60
def alerts():
๐Ÿงฉ Function DEFINES a function alerts(). Python only remembers it here - its body runs later, each time alerts() is called.
61
if not results:
๐Ÿ”€ Decision CHECKS whether results is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
62
analyse()
๐Ÿงฎ Store / Calculate Calls our own function analyse()
63
for name, img, pct, st in sorted(results, key=lambda r: -r[2]):
๐Ÿ” Loop LOOP: takes each item of sorted(results, key=lambda r: -r[2]) one-by-one into name, img, pct, st and runs the indented block for it
64
if pct >= 15:
๐Ÿ”€ Decision CHECKS whether pct is greater than or equal to 15. If True, the indented lines below run; otherwise they are skipped
65
print(f"{name}: {pct:.1f}% -> {st}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name}: {pct:.1f}% -> {st}" with the values filled into { } on the screen
66
print("Healthy reefs:", [r[0] for r in results if r[2] < 15])
๐Ÿ–ฅ๏ธ Output Displays the text "Healthy reefs:", then the value of [r[0] for r in results if r[2] < 15] on the screen
inspector() - lines 69โ€“74
LineCodeWhat it does
69
def inspector():
๐Ÿงฉ Function DEFINES a function inspector(). Python only remembers it here - its body runs later, each time inspector() is called.
70
img = cv2.imread(os.path.join(folder, "reef_%s.jpg" % input("Image number (1-6): ")))
โŒจ๏ธ Input Reads the image file os.path.join(folder, "reef_%s.jpg" % input("Iโ€ฆ into a NumPy array of pixels; the result is stored in variable img
71
x, y = int(input("x (0-159): ")), int(input("y (0-119): "))
โŒจ๏ธ Input Stores int(input("x (0-159): ")), int(input("y (0-119): ")) into x, y respectively
72
b, g, r = img[y, x]
๐Ÿงฎ Store / Calculate Stores the item img[y, x] in variables b, g, r
73
h, s, v = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[y, x]
๐Ÿ“ฆ Library / Data Stores the item cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[y, x] in variables h, s, v
74
print(f"BGR = ({b},{g},{r})  HSV = ({h},{s},{v})  -> {'WHITE (bleached)' if s < S_MAX and v > V_MIN else 'coloured / water'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"BGR = ({b},{g},{r}) HSV = ({h},{s},{v}) -> โ€ฆ with the values filled into { } on the screen
charts() - lines 77โ€“93
LineCodeWhat it does
77
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
78
if not results:
๐Ÿ”€ Decision CHECKS whether results is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
79
analyse()
๐Ÿงฎ Store / Calculate Calls our own function analyse()
80
fig, axes = plt.subplots(2, 3, figsize=(9, 5))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, axes
81
for ax, (name, img, pct, st) in zip(axes.ravel(), results):
๐Ÿ” Loop LOOP that walks through axes.ravel(), results together; ax, (name, img, pct, st) get one item from each
82
ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax.set_title(f"{name}\n{pct:.0f}% - {st.split(' -')[0]}", fontsize=9); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
82
ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax.set_title(f"{name}\n{pct:.0f}% - {st.split(' -')[0]}", fontsize=9); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
82
ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax.set_title(f"{name}\n{pct:.0f}% - {st.split(' -')[0]}", fontsize=9); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
83
plt.suptitle("Coral bleaching analysis"); plt.tight_layout(); plt.savefig("coral_results.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the main title of the figure
83
plt.suptitle("Coral bleaching analysis"); plt.tight_layout(); plt.savefig("coral_results.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
83
plt.suptitle("Coral bleaching analysis"); plt.tight_layout(); plt.savefig("coral_results.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "coral_results.png"
83
plt.suptitle("Coral bleaching analysis"); plt.tight_layout(); plt.savefig("coral_results.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
84
pc = [r[2] for r in results]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [r[2] for r in results] in variable pc
85
plt.bar([r[0][:-4] for r in results], pc, color=["red" if p >= 40 else "orange" if p >= 15 else "green" for p in pc])
๐Ÿ–ฅ๏ธ Output Draws a bar chart of [r[0][:-4] for r in results], pc
86
plt.axhline(40, ls="--", c="red"); plt.axhline(15, ls="--", c="orange")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
86
plt.axhline(40, ls="--", c="red"); plt.axhline(15, ls="--", c="orange")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
87
plt.ylabel("Bleached %"); plt.title("Bleaching level of each reef"); plt.savefig("coral_bars.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Bleached %" as the label of the Y-axis
87
plt.ylabel("Bleached %"); plt.title("Bleaching level of each reef"); plt.savefig("coral_bars.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Bleaching level of each reef" as the title of the chart
87
plt.ylabel("Bleached %"); plt.title("Bleaching level of each reef"); plt.savefig("coral_bars.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "coral_bars.png"
87
plt.ylabel("Bleached %"); plt.title("Bleaching level of each reef"); plt.savefig("coral_bars.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
img = results[-1][1]
๐Ÿงฎ Store / Calculate Stores the item results[-1][1] in variable img
89
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax
90
ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax[0].set_title("Original"); ax[0].axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
90
ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax[0].set_title("Original"); ax[0].axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
90
ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); ax[0].set_title("Original"); ax[0].axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
91
ax[1].imshow(bleach_mask(img), cmap="gray"); ax[1].set_title("Detected white pixels (mask)"); ax[1].axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
91
ax[1].imshow(bleach_mask(img), cmap="gray"); ax[1].set_title("Detected white pixels (mask)"); ax[1].axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
91
ax[1].imshow(bleach_mask(img), cmap="gray"); ax[1].set_title("Detected white pixels (mask)"); ax[1].axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
92
plt.tight_layout(); plt.savefig("coral_mask.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
92
plt.tight_layout(); plt.savefig("coral_mask.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "coral_mask.png"
92
plt.tight_layout(); plt.savefig("coral_mask.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
93
print("Charts saved: coral_results.png, coral_bars.png, coral_mask.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: coral_results.png, โ€ฆ" on the screen
Q1. Why convert to HSV?

HSV separates colour (H, S) from brightness (V), so white = low saturation and high value is easy to test.

Q2. What is a mask?

A True/False array marking pixels that satisfy a condition.

Q3. How is the percentage calculated?

mask.sum() / mask.size x 100.

Q4. Which domain of AI?

Computer Vision.

Q5. Why is coral bleaching important?

Bleached corals may die; early detection helps protect marine life (SDG 14).

03

School Canteen Review Sentiment Analyser (NLP)

PYTHONSDG 3 - Good Health and Well-beingText normalisationtokenisationstop-word removalBag of Wordslexicon-based sentiment
๐Ÿ“ 131 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

CBSE sample project 3: classifies student reviews of the school canteen as Positive, Negative or Neutral by normalising the text and counting positive and negative words, then shows the most frequent words and a sentiment pie chart.

โœจ Features
  • NLP pipeline: lower-case, remove punctuation, tokenise, remove stop words
  • Lexicon-based sentiment with negation handling ('not good' -> negative)
  • Bag of Words: word frequency table and top words
  • Add new reviews and analyse a single sentence step by step
  • Satisfaction index and category of complaints (food / service / hygiene)
  • Pie, bar and score charts
โ˜ฐ Main menu
1Analyse All ReviewsLabel every review
2Step-by-step NLPShows each pipeline stage for one sentence
3Bag of WordsTop 10 words
4Add ReviewAppends a new review
5Complaint TopicsFood / service / hygiene counts
6ChartsPie, word bar, score bar
0ExitEnds program
๐ŸŽฏ Objectives
  • Perform text normalisation: lower case, remove punctuation, tokenise and remove stop words
  • Create a Bag of Words to find the most frequent words
  • Classify each review and summarise the overall sentiment
๐Ÿ“š Data dictionary
NameTypePurpose
reviewslistCanteen reviews
positive / negativesetsSentiment lexicon including negated forms
stop_wordssetWords removed
TOPICSdictKeywords for complaint areas
Why it matters: Applies the NLP pipeline taught in Class X (normalisation, Bag of Words) to a feedback problem every school has.
# =====================================================================
#   SCHOOL CANTEEN REVIEW SENTIMENT ANALYSER  (NLP domain)
# =====================================================================
import string
import matplotlib.pyplot as plt

reviews = ["The samosa is tasty and fresh!", "Food was not good, very oily.", "Canteen opens at 10 am.",
           "Loved the healthy sprouts salad, great price.", "Long queue and slow service, I am unhappy.",
           "The staff is polite and the place is clean.", "Juice was stale and too sweet.",
           "Excellent idli, nice chutney.", "Menu changes every Monday.", "Not bad, but the plates were dirty."]
positive = {"tasty", "fresh", "good", "loved", "healthy", "great", "polite", "clean", "excellent", "nice", "bad_not", "quick"}
negative = {"oily", "slow", "unhappy", "stale", "dirty", "bad", "good_not", "long", "sweet", "fresh_not", "clean_not"}
stop_words = {"the", "is", "and", "was", "a", "at", "i", "am", "too", "but", "were", "very", "every"}
TOPICS = {"Food": ["oily", "stale", "sweet", "tasty", "fresh", "good"], "Service": ["slow", "queue", "long", "polite", "quick"],
          "Hygiene": ["dirty", "clean", "plates"]}


def tokens_of(text):
    clean = text.lower().translate(str.maketrans("", "", string.punctuation))
    return [w for w in clean.split() if w not in stop_words]


def score_of(tokens):
    score, skip, used = 0, False, []
    for i, w in enumerate(tokens):
        if skip:
            skip = False; continue
        if w == "not" and i + 1 < len(tokens):
            w = tokens[i + 1] + "_not"; skip = True
        if w in positive:
            score += 1; used.append("+" + w)
        elif w in negative:
            score -= 1; used.append("-" + w)
    return score, used


def label(s):
    return "Positive" if s > 0 else "Negative" if s < 0 else "Neutral"


def analyse_all():
    counts = {"Positive": 0, "Negative": 0, "Neutral": 0}
    for r in reviews:
        s, _ = score_of(tokens_of(r))
        counts[label(s)] += 1
        print(f"[{label(s):<8}] (score {s:+d})  {r}")
    print("\nSummary:", counts)
    print("Satisfaction index:", round(counts["Positive"] / len(reviews) * 100), "% positive")
    return counts


def step_by_step():
    t = input("Enter a sentence: ")
    print("1. Lower case      :", t.lower())
    print("2. No punctuation  :", t.lower().translate(str.maketrans("", "", string.punctuation)))
    print("3. Tokens          :", t.lower().translate(str.maketrans("", "", string.punctuation)).split())
    tk = tokens_of(t)
    print("4. Stop words out  :", tk)
    s, used = score_of(tk)
    print("5. Sentiment words :", used)
    print("6. Score / label   :", s, "->", label(s))


def bag():
    bow = {}
    for r in reviews:
        for w in tokens_of(r):
            if w != "not":
                bow[w] = bow.get(w, 0) + 1
    top = sorted(bow.items(), key=lambda x: (-x[1], x[0]))[:10]
    print("Vocabulary size:", len(bow))
    for w, c in top:
        print(f"  {w:<10} {c}  " + "#" * c)
    return bow


def add():
    reviews.append(input("New review: "))
    print("Review added. Total reviews:", len(reviews))


def topics():
    for t, keys in TOPICS.items():
        n = sum(1 for r in reviews if any(k in tokens_of(r) for k in keys))
        print(f"{t:<8}: mentioned in {n} reviews")


def charts():
    c = {"Positive": 0, "Negative": 0, "Neutral": 0}
    sc = []
    for r in reviews:
        s, _ = score_of(tokens_of(r)); sc.append(s); c[label(s)] += 1
    plt.pie(c.values(), labels=c.keys(), autopct="%1.0f%%", colors=["#2b8a3e", "#e03131", "#adb5bd"], startangle=90)
    plt.title("Canteen review sentiment"); plt.savefig("sentiment_pie.png", dpi=90, bbox_inches="tight"); plt.show()
    bow = {}
    for r in reviews:
        for w in tokens_of(r):
            bow[w] = bow.get(w, 0) + 1
    top = sorted(bow.items(), key=lambda x: -x[1])[:10]
    plt.barh([w for w, _ in top][::-1], [n for _, n in top][::-1], color="#5c7cfa")
    plt.title("Top 10 words (Bag of Words)"); plt.savefig("word_freq.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.bar(range(1, len(sc) + 1), sc, color=["green" if s > 0 else "red" if s < 0 else "grey" for s in sc])
    plt.axhline(0, color="black"); plt.xlabel("Review no."); plt.ylabel("Score"); plt.title("Sentiment score of each review")
    plt.savefig("review_scores.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: sentiment_pie.png, word_freq.png, review_scores.png")


print("=" * 55)
print("   CANTEEN REVIEW SENTIMENT ANALYSER  (NLP)")
print("=" * 55)
while True:
    print("\n1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        analyse_all()
    elif ch == "2":
        step_by_step()
    elif ch == "3":
        bag()
    elif ch == "4":
        add()
    elif ch == "5":
        topics()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Clean text (lower, punctuation)
  4. Tokenise and remove stop words
  5. Word is 'not'? → No: look up word in lexicon
  6. Join with next word (negation)
  7. Score +1 / -1
  8. Label Positive / Negative / Neutral
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1'The samosa is tasty and fresh!'Positive (+2)PASS
2'Food was not good, very oily.'NegativePASS
3'Canteen opens at 10 am.'NeutralPASS
4'Not bad, but plates were dirty'Neutral (+1 -1)PASS
5Add reviewList growsPASS
6Bag of wordsTop wordsPASS
7TopicsHygiene / service countsPASS
โš  Limitations
  • Small hand-made lexicon
  • Sarcasm not understood
  • English only
  • Each word has equal weight
๐Ÿš€ Future scope
  • Train a Naive Bayes / logistic model (Class XII)
  • Hindi and Hinglish support
  • Google Form integration
  • Weekly report to canteen manager

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): string - ready-made sets of characters, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: reviews, positive, negative, stop_words, TOPICS.
  3. 9 functions are defined (lines 18โ€“105) - Python stores them but does NOT run them yet.
  4. Main program starts at line 108: print("=" * 55) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
tokens_of(text)18โ€“20Tokens ofanalyse_all(), step_by_step(), bag(), topics()
score_of(tokens)23โ€“34Score ofanalyse_all(), step_by_step(), charts()
label(s)37โ€“38Labelanalyse_all(), step_by_step(), charts()
analyse_all()41โ€“49Analyse allmain program
step_by_step()52โ€“61Step by stepmain program
bag()64โ€“74Bagmain program
add()77โ€“79Addmain program
topics()82โ€“85Topicsmain program
charts()88โ€“105Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
108
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
109
print("   CANTEEN REVIEW SENTIMENT ANALYSER  (NLP)")
๐Ÿ–ฅ๏ธ Output Displays the text "CANTEEN REVIEW SENTIMENT ANALYSERโ€ฆ" on the screen
110
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
111
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
112
print("\n1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Analyse All 2.Step-by-step 3.Baโ€ฆ" on the screen
113
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
114
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
115
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
116
break
๐Ÿ” Loop BREAK - leaves the loop immediately
117
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
118
analyse_all()
๐Ÿงฎ Store / Calculate Calls our own function analyse_all()
119
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
120
step_by_step()
๐Ÿงฎ Store / Calculate Calls our own function step_by_step()
121
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
122
bag()
๐Ÿงฎ Store / Calculate Calls our own function bag()
123
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
124
add()
๐Ÿงฎ Store / Calculate Calls our own function add()
125
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
126
topics()
๐Ÿงฎ Store / Calculate Calls our own function topics()
127
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
128
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
129
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
130
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CANTEEN REVIEW SENTIMENT ANALYSER (NLP) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: analyse_all() โ†’ tokens_of() โ†’ score_of() โ†’ label() ร—2 โ†’ tokens_of() โ†’ score_of() โ†’ label() ร—2 โ†’ tokens_of()
    shows: [Positive] (score +2) The samosa is tasty and fresh! (+12 more lines)
  3. You type 2 at Enter choice:
    runs: step_by_step()
  4. You type The paneer roll was not fresh and the counter is dirty! at Enter a sentence:
    runs: tokens_of() โ†’ score_of() โ†’ label()
    shows: 1. Lower case : the paneer roll was not fresh and the counter is dirty! (+6 more lines)
  5. You type 3 at Enter choice:
    runs: bag() โ†’ tokens_of() ร—10
    shows: Vocabulary size: 37 (+11 more lines)
  6. You type 4 at Enter choice:
    runs: add()
  7. You type Great pav bhaji, quick and polite service. at New review:
    shows: Review added. Total reviews: 11 (+1 more lines)
  8. You type 1 at Enter choice:
    runs: analyse_all() โ†’ tokens_of() โ†’ score_of() โ†’ label() ร—2 โ†’ tokens_of() โ†’ score_of() โ†’ label() ร—2 โ†’ tokens_of()
    shows: [Positive] (score +2) The samosa is tasty and fresh! (+13 more lines)
  9. You type 5 at Enter choice:
    runs: topics() โ†’ tokens_of() ร—134
    shows: Food : mentioned in 3 reviews (+3 more lines)
  10. You type 6 at Enter choice:
    runs: charts() โ†’ tokens_of() โ†’ score_of() โ†’ label() โ†’ tokens_of() โ†’ score_of() โ†’ label() โ†’ tokens_of()
    shows: [chart is drawn] (+4 more lines)
  11. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
tokens_of() - lines 18โ€“20
LineCodeWhat it does
18
def tokens_of(text):
๐Ÿงฉ Function DEFINES a function tokens_of(text). Python only remembers it here - its body runs later, each time tokens_of() is called.
19
clean = text.lower().translate(str.maketrans("", "", string.punctuation))
๐Ÿงฎ Store / Calculate Changes characters of text.lower() using a table; the result is stored in variable clean
20
return [w for w in clean.split() if w not in stop_words]
๐Ÿงฉ Function Sends back (returns) a new list made by a list comprehension [w for w in clean.split() if w not in stop_woโ€ฆ to the line that called the function
score_of() - lines 23โ€“34
LineCodeWhat it does
23
def score_of(tokens):
๐Ÿงฉ Function DEFINES a function score_of(tokens). Python only remembers it here - its body runs later, each time score_of() is called.
24
score, skip, used = 0, False, []
๐Ÿงฎ Store / Calculate Stores 0, False, [] into score, skip, used respectively
25
for i, w in enumerate(tokens):
๐Ÿ” Loop LOOP over tokens with position: in each round i, w get (position, item)
26
if skip:
๐Ÿ”€ Decision CHECKS whether skip is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
27
skip = False; continue
๐Ÿงฎ Store / Calculate Stores False in variable skip
27
skip = False; continue
๐Ÿงฎ Store / Calculate CONTINUE - skips the rest of this round and goes to the next round of the loop
28
if w == "not" and i + 1 < len(tokens):
๐Ÿ”€ Decision CHECKS whether (w is equal to "not" AND i + 1 is less than len(tokens)). If True, the indented lines below run; otherwise they are skipped
29
w = tokens[i + 1] + "_not"; skip = True
๐Ÿงฎ Store / Calculate Stores the value of tokens[i + 1] + "_not" (calculated using +) in variable w
29
w = tokens[i + 1] + "_not"; skip = True
๐Ÿงฎ Store / Calculate Stores True in variable skip
30
if w in positive:
๐Ÿ”€ Decision CHECKS whether w is present in positive. If True, the indented lines below run; otherwise Python jumps to the elif/else part
31
score += 1; used.append("+" + w)
๐Ÿงฎ Store / Calculate Adds 1 to score (same as score = score + 1)
31
score += 1; used.append("+" + w)
๐Ÿงฎ Store / Calculate Adds "+" + w at the end of list used
32
elif w in negative:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether w is present in negative
33
score -= 1; used.append("-" + w)
๐Ÿงฎ Store / Calculate Subtracts 1 from score (same as score = score - 1)
33
score -= 1; used.append("-" + w)
๐Ÿงฎ Store / Calculate Adds "-" + w at the end of list used
34
return score, used
๐Ÿงฉ Function Sends back (returns) the tuple score, used to the line that called the function
label() - lines 37โ€“38
LineCodeWhat it does
37
def label(s):
๐Ÿงฉ Function DEFINES a function label(s). Python only remembers it here - its body runs later, each time label() is called.
38
return "Positive" if s > 0 else "Negative" if s < 0 else "Neutral"
๐Ÿงฉ Function Sends back (returns) either "Positive" or "Negative" if s < 0 else "Neutral" depending on s > 0 to the line that called the function
analyse_all() - lines 41โ€“49
LineCodeWhat it does
41
def analyse_all():
๐Ÿงฉ Function DEFINES a function analyse_all(). Python only remembers it here - its body runs later, each time analyse_all() is called.
42
counts = {"Positive": 0, "Negative": 0, "Neutral": 0}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Positive": 0, "Negative": 0, "Neutral": 0} in variable counts
43
for r in reviews:
๐Ÿ” Loop LOOP: takes each item of reviews one-by-one into r and runs the indented block for it
44
s, _ = score_of(tokens_of(r))
๐Ÿงฎ Store / Calculate Calls our own function score_of(tokens_of(r)); the result is stored in variables s, _
45
counts[label(s)] += 1
๐Ÿงฎ Store / Calculate Adds 1 to counts[label(s)] (same as counts[label(s)] = counts[label(s)] + 1)
46
print(f"[{label(s):<8}] (score {s:+d})  {r}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"[{label(s):<8}] (score {s:+d}) {r}" with the values filled into { } on the screen
47
print("\nSummary:", counts)
๐Ÿ–ฅ๏ธ Output Displays the text "Summary:", then the value of counts on the screen
48
print("Satisfaction index:", round(counts["Positive"] / len(reviews) * 100), "% positive")
๐Ÿ–ฅ๏ธ Output Displays the text "Satisfaction index:", then the value of round(counts["Positive"] / len(reviews) * 100), then the text "% positive" on the screen
49
return counts
๐Ÿงฉ Function Sends back (returns) the value of counts to the line that called the function
step_by_step() - lines 52โ€“61
LineCodeWhat it does
52
def step_by_step():
๐Ÿงฉ Function DEFINES a function step_by_step(). Python only remembers it here - its body runs later, each time step_by_step() is called.
53
t = input("Enter a sentence: ")
โŒจ๏ธ Input Shows the message "Enter a sentence: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable t
54
print("1. Lower case      :", t.lower())
๐Ÿ–ฅ๏ธ Output Displays the text "1. Lower case :", then the value of t.lower() on the screen
55
print("2. No punctuation  :", t.lower().translate(str.maketrans("", "", string.punctuation)))
๐Ÿ–ฅ๏ธ Output Displays the text "2. No punctuation :", then the value of t.lower().translate(str.maketrans("", "", strโ€ฆ on the screen
56
print("3. Tokens          :", t.lower().translate(str.maketrans("", "", string.punctuation)).split())
๐Ÿ–ฅ๏ธ Output Displays the text "3. Tokens :", then the value of t.lower().translate(str.maketrans("", "", strโ€ฆ on the screen
57
tk = tokens_of(t)
๐Ÿงฎ Store / Calculate Calls our own function tokens_of(t); the result is stored in variable tk
58
print("4. Stop words out  :", tk)
๐Ÿ–ฅ๏ธ Output Displays the text "4. Stop words out :", then the value of tk on the screen
59
s, used = score_of(tk)
๐Ÿงฎ Store / Calculate Calls our own function score_of(tk); the result is stored in variables s, used
60
print("5. Sentiment words :", used)
๐Ÿ–ฅ๏ธ Output Displays the text "5. Sentiment words :", then the value of used on the screen
61
print("6. Score / label   :", s, "->", label(s))
๐Ÿ–ฅ๏ธ Output Displays the text "6. Score / label :", then the value of s, then the text "->", then the value of label(s) on the screen
bag() - lines 64โ€“74
LineCodeWhat it does
64
def bag():
๐Ÿงฉ Function DEFINES a function bag(). Python only remembers it here - its body runs later, each time bag() is called.
65
bow = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable bow
66
for r in reviews:
๐Ÿ” Loop LOOP: takes each item of reviews one-by-one into r and runs the indented block for it
67
for w in tokens_of(r):
๐Ÿ” Loop LOOP: takes each item of tokens_of(r) one-by-one into w and runs the indented block for it
68
if w != "not":
๐Ÿ”€ Decision CHECKS whether w is not equal to "not". If True, the indented lines below run; otherwise they are skipped
69
bow[w] = bow.get(w, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of bow.get(w, 0) + 1 (calculated using +) into bow[w] (item w of bow)
70
top = sorted(bow.items(), key=lambda x: (-x[1], x[0]))[:10]
๐Ÿงฎ Store / Calculate Stores a slice sorted(bow.items(), key=lambda x: (-x[1], x[0โ€ฆ (part of sorted(bow.items(), key=lambda x: (-x[1], x[0โ€ฆ) in variable top
71
print("Vocabulary size:", len(bow))
๐Ÿ–ฅ๏ธ Output Displays the text "Vocabulary size:", then the value of len(bow) on the screen
72
for w, c in top:
๐Ÿ” Loop LOOP: takes each item of top one-by-one into w, c and runs the indented block for it
73
print(f"  {w:<10} {c}  " + "#" * c)
๐Ÿ–ฅ๏ธ Output Displays the value of f" {w:<10} {c} " + "#" * c on the screen
74
return bow
๐Ÿงฉ Function Sends back (returns) the value of bow to the line that called the function
add() - lines 77โ€“79
LineCodeWhat it does
77
def add():
๐Ÿงฉ Function DEFINES a function add(). Python only remembers it here - its body runs later, each time add() is called.
78
reviews.append(input("New review: "))
โŒจ๏ธ Input Adds input("New review: ") at the end of list reviews
79
print("Review added. Total reviews:", len(reviews))
๐Ÿ–ฅ๏ธ Output Displays the text "Review added. Total reviews:", then the value of len(reviews) on the screen
topics() - lines 82โ€“85
LineCodeWhat it does
82
def topics():
๐Ÿงฉ Function DEFINES a function topics(). Python only remembers it here - its body runs later, each time topics() is called.
83
for t, keys in TOPICS.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary TOPICS; t, keys get one pair each round
84
n = sum(1 for r in reviews if any(k in tokens_of(r) for k in keys))
๐Ÿงฎ Store / Calculate Adds up all the values in (1 for r in reviews if any(k in tokens_of(r) โ€ฆ; the result is stored in variable n
85
print(f"{t:<8}: mentioned in {n} reviews")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{t:<8}: mentioned in {n} reviews" with the values filled into { } on the screen
charts() - lines 88โ€“105
LineCodeWhat it does
88
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
89
c = {"Positive": 0, "Negative": 0, "Neutral": 0}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Positive": 0, "Negative": 0, "Neutral": 0} in variable c
90
sc = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable sc
91
for r in reviews:
๐Ÿ” Loop LOOP: takes each item of reviews one-by-one into r and runs the indented block for it
92
s, _ = score_of(tokens_of(r)); sc.append(s); c[label(s)] += 1
๐Ÿงฎ Store / Calculate Calls our own function score_of(tokens_of(r)); the result is stored in variables s, _
92
s, _ = score_of(tokens_of(r)); sc.append(s); c[label(s)] += 1
๐Ÿงฎ Store / Calculate Adds s at the end of list sc
92
s, _ = score_of(tokens_of(r)); sc.append(s); c[label(s)] += 1
๐Ÿงฎ Store / Calculate Adds 1 to c[label(s)] (same as c[label(s)] = c[label(s)] + 1)
93
plt.pie(c.values(), labels=c.keys(), autopct="%1.0f%%", colors=["#2b8a3e", "#e03131", "#adb5bd"], startangle=90)
๐Ÿ–ฅ๏ธ Output Draws a pie chart of c.values()
94
plt.title("Canteen review sentiment"); plt.savefig("sentiment_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Canteen review sentiment" as the title of the chart
94
plt.title("Canteen review sentiment"); plt.savefig("sentiment_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "sentiment_pie.png"
94
plt.title("Canteen review sentiment"); plt.savefig("sentiment_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
95
bow = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable bow
96
for r in reviews:
๐Ÿ” Loop LOOP: takes each item of reviews one-by-one into r and runs the indented block for it
97
for w in tokens_of(r):
๐Ÿ” Loop LOOP: takes each item of tokens_of(r) one-by-one into w and runs the indented block for it
98
bow[w] = bow.get(w, 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of bow.get(w, 0) + 1 (calculated using +) into bow[w] (item w of bow)
99
top = sorted(bow.items(), key=lambda x: -x[1])[:10]
๐Ÿงฎ Store / Calculate Stores a slice sorted(bow.items(), key=lambda x: -x[1])[:10] (part of sorted(bow.items(), key=lambda x: -x[1])) in variable top
100
plt.barh([w for w, _ in top][::-1], [n for _, n in top][::-1], color="#5c7cfa")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
101
plt.title("Top 10 words (Bag of Words)"); plt.savefig("word_freq.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Top 10 words (Bag of Words)" as the title of the chart
101
plt.title("Top 10 words (Bag of Words)"); plt.savefig("word_freq.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "word_freq.png"
101
plt.title("Top 10 words (Bag of Words)"); plt.savefig("word_freq.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
102
plt.bar(range(1, len(sc) + 1), sc, color=["green" if s > 0 else "red" if s < 0 else "grey" for s in sc])
๐Ÿ–ฅ๏ธ Output Draws a bar chart of range(1, len(sc) + 1), sc
103
plt.axhline(0, color="black"); plt.xlabel("Review no."); plt.ylabel("Score"); plt.title("Sentiment score of each review")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
103
plt.axhline(0, color="black"); plt.xlabel("Review no."); plt.ylabel("Score"); plt.title("Sentiment score of each review")
๐Ÿ–ฅ๏ธ Output Writes "Review no." as the label of the X-axis
103
plt.axhline(0, color="black"); plt.xlabel("Review no."); plt.ylabel("Score"); plt.title("Sentiment score of each review")
๐Ÿ–ฅ๏ธ Output Writes "Score" as the label of the Y-axis
103
plt.axhline(0, color="black"); plt.xlabel("Review no."); plt.ylabel("Score"); plt.title("Sentiment score of each review")
๐Ÿ–ฅ๏ธ Output Writes "Sentiment score of each review" as the title of the chart
104
plt.savefig("review_scores.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "review_scores.png"
104
plt.savefig("review_scores.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
105
print("Charts saved: sentiment_pie.png, word_freq.png, review_scores.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: sentiment_pie.png, โ€ฆ" on the screen
Q1. What is NLP?

Natural Language Processing - the AI domain that helps computers understand human language.

Q2. What is tokenisation?

Splitting text into words (tokens).

Q3. What are stop words?

Very common words (the, is, and) that add little meaning and are removed.

Q4. What is Bag of Words?

A representation counting how many times each word occurs, ignoring order.

Q5. How is negation handled?

'not' is joined with the next word, so 'not good' becomes 'good_not', which is in the negative list.

04

Delhi Air Quality (AQI) Statistical Analyser (SDG 11)

PYTHON + PANDASSDG 11 - Sustainable Cities / SDG 3 - HealthPandas DataFramemean / median / mode / stdpd.cut categoriesrolling meanline chart
๐Ÿ“ 100 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 97 output lines๐Ÿ“„ 25+ page report

Analyses 30 days of AQI readings, calculates statistical measures, classifies each day into CPCB AQI categories (Good to Severe), finds the worst days and plots the trend with a 7-day moving average.

โœจ Features
  • 30 days of November AQI readings for Delhi in a DataFrame
  • Mean, median, mode, standard deviation, range and quartiles
  • CPCB category for each day with pd.cut and value_counts
  • 7-day moving average and week-wise mean
  • Health advisory for a chosen day; days to avoid outdoor activity
  • Line, bar and histogram charts
โ˜ฐ Main menu
1Show DataDay-wise AQI with category
2StatisticsMean, median, mode, std, quartiles
3Category CountDays in each CPCB band
4Weekly AverageMean of each week
5Day AdvisoryAdvice for one day
6Worst DaysTop 5 and AQI > 300 list
7ChartsTrend, category bar, histogram
0ExitEnds program
๐ŸŽฏ Objectives
  • Store and summarise time-series data with Pandas
  • Classify values into CPCB AQI categories using pd.cut
  • Visualise the trend and a moving average with Matplotlib
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameDay, AQI, Category, 7-day avg, Week
bins / nameslistsCPCB AQI bands
ADVICEdictHealth advice per category
Why it matters: Uses statistics from the Class X 'Statistical Data' unit on an issue that directly affects students' health.
# =====================================================================
#   DELHI AIR QUALITY (AQI) STATISTICAL ANALYSER   (SDG 11)
#   Sample readings for November (for practice)
# =====================================================================
import pandas as pd
import matplotlib.pyplot as plt

aqi = [286, 301, 322, 356, 389, 412, 438, 402, 371, 344, 318, 296, 275, 301, 333,
       365, 398, 421, 387, 352, 330, 309, 287, 262, 248, 266, 293, 315, 342, 301]
df = pd.DataFrame({"Day": range(1, 31), "AQI": aqi})
bins = [0, 50, 100, 200, 300, 400, 500]
names = ["Good", "Satisfactory", "Moderate", "Poor", "Very Poor", "Severe"]
df["Category"] = pd.cut(df.AQI, bins=bins, labels=names)
df["7-day avg"] = df.AQI.rolling(7).mean().round(1)
df["Week"] = (df.Day - 1) // 7 + 1
ADVICE = {"Good": "Enjoy outdoor activities.", "Satisfactory": "Sensitive people take care.", "Moderate": "Limit long outdoor exertion.",
          "Poor": "Avoid outdoor exercise; wear N95 mask.", "Very Poor": "Stay indoors; use air purifier.", "Severe": "Health emergency - avoid going out, schools may close."}


def show():
    print(df[["Day", "AQI", "Category", "7-day avg"]].to_string(index=False))


def stats():
    print("Mean    :", round(df.AQI.mean(), 2))
    print("Median  :", df.AQI.median())
    print("Mode    :", df.AQI.mode().tolist())
    print("Std dev :", round(df.AQI.std(), 2))
    print("Range   :", df.AQI.max() - df.AQI.min(), f"({df.AQI.min()} to {df.AQI.max()})")
    print("Quartiles Q1, Q2, Q3:", df.AQI.quantile([.25, .5, .75]).tolist())


def categories():
    print(df.Category.value_counts().reindex(names).to_string())


def weekly():
    w = df.groupby("Week").AQI.agg(["mean", "min", "max"]).round(1)
    print(w)
    print("Worst week:", w["mean"].idxmax())


def advisory():
    d = int(input("Day (1-30): "))
    if not 1 <= d <= 30:
        print("Day must be 1-30.")
        return
    r = df[df.Day == d].iloc[0]
    print(f"Day {d}: AQI {r.AQI} -> {r.Category}. Advice: {ADVICE[r.Category]}")


def worst():
    print("5 worst days:\n", df.nlargest(5, "AQI")[["Day", "AQI", "Category"]].to_string(index=False))
    bad = df[df.AQI > 300].Day.tolist()
    print("\nDays to avoid outdoor activity (AQI > 300):", len(bad), "days ->", bad)


def charts():
    plt.figure(figsize=(8, 4))
    plt.plot(df.Day, df.AQI, marker="o", label="Daily AQI")
    plt.plot(df.Day, df["7-day avg"], color="red", linewidth=2, label="7-day moving average")
    plt.axhline(300, color="purple", linestyle="--", label="Very Poor threshold (300)")
    plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
    plt.savefig("aqi_trend.png", dpi=90, bbox_inches="tight"); plt.show()
    df.Category.value_counts().reindex(names).plot(kind="bar", color=["#2b8a3e", "#82c91e", "#fab005", "#fd7e14", "#e03131", "#862e9c"])
    plt.ylabel("Days"); plt.title("Days in each AQI category"); plt.xticks(rotation=20)
    plt.savefig("aqi_category.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.hist(df.AQI, bins=[250, 275, 300, 325, 350, 375, 400, 425, 450], edgecolor="black", color="#74c0fc")
    plt.axvline(df.AQI.mean(), color="red", label="Mean"); plt.axvline(df.AQI.median(), color="green", ls="--", label="Median")
    plt.xlabel("AQI"); plt.ylabel("Days"); plt.title("AQI distribution"); plt.legend()
    plt.savefig("aqi_hist.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: aqi_trend.png, aqi_category.png, aqi_hist.png")


print("=" * 55)
print("   DELHI AQI STATISTICAL ANALYSER  (SDG 11)")
print("=" * 55)
while True:
    print("\n1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Breathe clean!")
        break
    elif ch == "1":
        show()
    elif ch == "2":
        stats()
    elif ch == "3":
        categories()
    elif ch == "4":
        weekly()
    elif ch == "5":
        advisory()
    elif ch == "6":
        worst()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create DataFrame and categories
  3. Show menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. Calculate statistics / filter
  6. Show result or chart
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1StatisticsMean 334.0, median 326, mode 301PASS
2Category countPoor / Very Poor / SeverePASS
3Weekly5 weeksPASS
4Advisory day 7Severe advicePASS
5Advisory day 40'Day must be 1-30'PASS
6Worst daysDay 7 = 438PASS
7Charts3 PNG filesPASS
โš  Limitations
  • Sample readings, not official CPCB data
  • One city, one month
  • No pollutant break-up
  • No forecasting
๐Ÿš€ Future scope
  • Fetch live AQI from CPCB API
  • Compare Diwali / stubble burning weeks
  • Predict tomorrow's AQI with regression
  • SMS alerts

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 5): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: aqi, df, bins, names, ADVICE.
  3. 7 functions are defined (lines 20โ€“72) - Python stores them but does NOT run them yet.
  4. Main program starts at line 13: df["Category"] = pd.cut(df.AQI, bins=bins, labels=names) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
show()20โ€“21Showmain program
stats()24โ€“30Statsmain program
categories()33โ€“34Categoriesmain program
weekly()37โ€“40Weeklymain program
advisory()43โ€“49Advisorymain program
worst()52โ€“55Worstmain program
charts()58โ€“72Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
13
df["Category"] = pd.cut(df.AQI, bins=bins, labels=names)
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["Category"] (item "Category" of df)
14
df["7-day avg"] = df.AQI.rolling(7).mean().round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.AQI.rolling(7).mean() to 1 decimal places; the result is put into df["7-day avg"] (item "7-day avg" of df)
15
df["Week"] = (df.Day - 1) // 7 + 1
๐Ÿ“ฆ Library / Data Puts the value of (df.Day - 1) // 7 + 1 (calculated using +) into df["Week"] (item "Week" of df)
16
ADVICE = {"Good": "Enjoy outdoor activities.", "Satisfactory": "Sensitive people take care.", "Moderate": "Limit long outdoor exertion.",
          "Poor": "โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Good": "Enjoy outdoor activities.", "Satisfโ€ฆ in variable ADVICE
75
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
76
print("   DELHI AQI STATISTICAL ANALYSER  (SDG 11)")
๐Ÿ–ฅ๏ธ Output Displays the text "DELHI AQI STATISTICAL ANALYSER (Sโ€ฆ" on the screen
77
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
78
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
79
print("\n1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Statistics 3.Categories โ€ฆ" on the screen
80
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
81
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
82
print("Breathe clean!")
๐Ÿ–ฅ๏ธ Output Displays the text "Breathe clean!" on the screen
83
break
๐Ÿ” Loop BREAK - leaves the loop immediately
84
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
85
show()
๐Ÿงฎ Store / Calculate Calls our own function show()
86
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
87
stats()
๐Ÿงฎ Store / Calculate Calls our own function stats()
88
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
89
categories()
๐Ÿงฎ Store / Calculate Calls our own function categories()
90
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
91
weekly()
๐Ÿงฎ Store / Calculate Calls our own function weekly()
92
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
93
advisory()
๐Ÿงฎ Store / Calculate Calls our own function advisory()
94
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
95
worst()
๐Ÿงฎ Store / Calculate Calls our own function worst()
96
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
97
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
98
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
99
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: DELHI AQI STATISTICAL ANALYSER (SDG 11) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show()
    shows: Day AQI Category 7-day avg (+31 more lines)
  3. You type 2 at Enter choice:
    runs: stats()
    shows: Mean : 334.0 (+6 more lines)
  4. You type 3 at Enter choice:
    runs: categories()
    shows: Category (+7 more lines)
  5. You type 4 at Enter choice:
    runs: weekly()
    shows: mean min max (+8 more lines)
  6. You type 5 at Enter choice:
    runs: advisory()
  7. You type 7 at Day (1-30):
    shows: Day 7: AQI 438 -> Severe. Advice: Health emergency - avoid going out, schools may close. (+1 more lines)
  8. You type 5 at Enter choice:
    runs: advisory()
  9. You type 40 at Day (1-30):
    shows: Day must be 1-30. (+1 more lines)
  10. You type 6 at Enter choice:
    runs: worst()
    shows: 5 worst days: (+8 more lines)
  11. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  12. You type 0 at Enter choice:
    shows: Breathe clean!
โ‘ค Inside each function - line by line
show() - lines 20โ€“21
LineCodeWhat it does
20
def show():
๐Ÿงฉ Function DEFINES a function show(). Python only remembers it here - its body runs later, each time show() is called.
21
print(df[["Day", "AQI", "Category", "7-day avg"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df[["Day", "AQI", "Category", "7-day avg"]].tโ€ฆ on the screen
stats() - lines 24โ€“30
LineCodeWhat it does
24
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
25
print("Mean    :", round(df.AQI.mean(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Mean :", then the value of round(df.AQI.mean(), 2) on the screen
26
print("Median  :", df.AQI.median())
๐Ÿ–ฅ๏ธ Output Displays the text "Median :", then the value of df.AQI.median() on the screen
27
print("Mode    :", df.AQI.mode().tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Mode :", then the value of df.AQI.mode().tolist() on the screen
28
print("Std dev :", round(df.AQI.std(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Std dev :", then the value of round(df.AQI.std(), 2) on the screen
29
print("Range   :", df.AQI.max() - df.AQI.min(), f"({df.AQI.min()} to {df.AQI.max()})")
๐Ÿ–ฅ๏ธ Output Displays the text "Range :", then the value of df.AQI.max() - df.AQI.min(), then the f-string f"({df.AQI.min()} to {df.AQI.max()})" with the values filled into { } on the screen
30
print("Quartiles Q1, Q2, Q3:", df.AQI.quantile([.25, .5, .75]).tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Quartiles Q1, Q2, Q3:", then the value of df.AQI.quantile([.25, .5, .75]).tolist() on the screen
categories() - lines 33โ€“34
LineCodeWhat it does
33
def categories():
๐Ÿงฉ Function DEFINES a function categories(). Python only remembers it here - its body runs later, each time categories() is called.
34
print(df.Category.value_counts().reindex(names).to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of df.Category.value_counts().reindex(names).to_โ€ฆ on the screen
weekly() - lines 37โ€“40
LineCodeWhat it does
37
def weekly():
๐Ÿงฉ Function DEFINES a function weekly(). Python only remembers it here - its body runs later, each time weekly() is called.
38
w = df.groupby("Week").AQI.agg(["mean", "min", "max"]).round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby("Week").AQI.agg(["mean", "min", "mโ€ฆ to 1 decimal places; the result is stored in variable w
39
print(w)
๐Ÿ–ฅ๏ธ Output Displays the value of w on the screen
40
print("Worst week:", w["mean"].idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Worst week:", then the value of w["mean"].idxmax() on the screen
advisory() - lines 43โ€“49
LineCodeWhat it does
43
def advisory():
๐Ÿงฉ Function DEFINES a function advisory(). Python only remembers it here - its body runs later, each time advisory() is called.
44
d = int(input("Day (1-30): "))
โŒจ๏ธ Input Shows "Day (1-30): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable d
45
if not 1 <= d <= 30:
๐Ÿ”€ Decision CHECKS whether NOT 1 <= d <= 30 is True. If True, the indented lines below run; otherwise they are skipped
46
print("Day must be 1-30.")
๐Ÿ–ฅ๏ธ Output Displays the text "Day must be 1-30." on the screen
47
return
๐Ÿงฉ Function Ends the function and goes back to the caller
48
r = df[df.Day == d].iloc[0]
๐Ÿ“ฆ Library / Data Stores the item df[df.Day == d].iloc[0] in variable r
49
print(f"Day {d}: AQI {r.AQI} -> {r.Category}. Advice: {ADVICE[r.Category]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Day {d}: AQI {r.AQI} -> {r.Category}. Advicโ€ฆ with the values filled into { } on the screen
worst() - lines 52โ€“55
LineCodeWhat it does
52
def worst():
๐Ÿงฉ Function DEFINES a function worst(). Python only remembers it here - its body runs later, each time worst() is called.
53
print("5 worst days:\n", df.nlargest(5, "AQI")[["Day", "AQI", "Category"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "5 worst days:", then the value of df.nlargest(5, "AQI")[["Day", "AQI", "Categorโ€ฆ on the screen
54
bad = df[df.AQI > 300].Day.tolist()
๐Ÿ“ฆ Library / Data Converts df[df.AQI > 300].Day into a normal Python list; the result is stored in variable bad
55
print("\nDays to avoid outdoor activity (AQI > 300):", len(bad), "days ->", bad)
๐Ÿ–ฅ๏ธ Output Displays the text "Days to avoid outdoor activity (Aโ€ฆ", then the value of len(bad), then the text "days ->", then the value of bad on the screen
charts() - lines 58โ€“72
LineCodeWhat it does
58
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
59
plt.figure(figsize=(8, 4))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
60
plt.plot(df.Day, df.AQI, marker="o", label="Daily AQI")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Day, df.AQI
61
plt.plot(df.Day, df["7-day avg"], color="red", linewidth=2, label="7-day moving average")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Day, df["7-day avg"]
62
plt.axhline(300, color="purple", linestyle="--", label="Very Poor threshold (300)")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
63
plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Day of month" as the label of the X-axis
63
plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "AQI" as the label of the Y-axis
63
plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Daily AQI trend" as the title of the chart
63
plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
63
plt.xlabel("Day of month"); plt.ylabel("AQI"); plt.title("Daily AQI trend"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
64
plt.savefig("aqi_trend.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "aqi_trend.png"
64
plt.savefig("aqi_trend.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
65
df.Category.value_counts().reindex(names).plot(kind="bar", color=["#2b8a3e", "#82c91e", "#fab005", "#fd7e14", "#e03131", "#862e9c"])
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
66
plt.ylabel("Days"); plt.title("Days in each AQI category"); plt.xticks(rotation=20)
๐Ÿ–ฅ๏ธ Output Writes "Days" as the label of the Y-axis
66
plt.ylabel("Days"); plt.title("Days in each AQI category"); plt.xticks(rotation=20)
๐Ÿ–ฅ๏ธ Output Writes "Days in each AQI category" as the title of the chart
66
plt.ylabel("Days"); plt.title("Days in each AQI category"); plt.xticks(rotation=20)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
67
plt.savefig("aqi_category.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "aqi_category.png"
67
plt.savefig("aqi_category.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
68
plt.hist(df.AQI, bins=[250, 275, 300, 325, 350, 375, 400, 425, 450], edgecolor="black", color="#74c0fc")
๐Ÿ–ฅ๏ธ Output Draws a histogram of df.AQI
69
plt.axvline(df.AQI.mean(), color="red", label="Mean"); plt.axvline(df.AQI.median(), color="green", ls="--", label="Median")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
69
plt.axvline(df.AQI.mean(), color="red", label="Mean"); plt.axvline(df.AQI.median(), color="green", ls="--", label="Median")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
70
plt.xlabel("AQI"); plt.ylabel("Days"); plt.title("AQI distribution"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "AQI" as the label of the X-axis
70
plt.xlabel("AQI"); plt.ylabel("Days"); plt.title("AQI distribution"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Days" as the label of the Y-axis
70
plt.xlabel("AQI"); plt.ylabel("Days"); plt.title("AQI distribution"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "AQI distribution" as the title of the chart
70
plt.xlabel("AQI"); plt.ylabel("Days"); plt.title("AQI distribution"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
71
plt.savefig("aqi_hist.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "aqi_hist.png"
71
plt.savefig("aqi_hist.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
72
print("Charts saved: aqi_trend.png, aqi_category.png, aqi_hist.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: aqi_trend.png, aqi_โ€ฆ" on the screen
Q1. Difference between mean and median?

Mean is the average; median is the middle value after sorting and is not affected much by extreme values.

Q2. What does standard deviation show?

How much the values spread around the mean.

Q3. What is a moving average?

The average of the last n days, recalculated every day; it smooths the trend.

Q4. Which statistic is the mode?

The most frequent value.

Q5. Which SDG?

SDG 11 - Sustainable Cities and Communities (and SDG 3 Health).

05

Study Hours vs Marks - Regression Predictor

PYTHON + NUMPYSDG 4 - Quality EducationNumPy polyfit (line of best fit)correlationMSEpredictionscatter + line plot
๐Ÿ“ 108 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 81 output lines๐Ÿ“„ 25+ page report

Fits a straight line (linear regression) to data of study hours and marks of 12 students using NumPy, measures the error (MSE) and correlation, and predicts marks for the number of hours entered by the user.

โœจ Features
  • Study-hours vs marks data of 12 students (NumPy arrays)
  • Linear regression line learnt with np.polyfit (slope and intercept)
  • Evaluation: MSE, RMSE, correlation r and R squared
  • Train-test split: learn on 9 students, test on 3
  • Predict marks for new study hours (capped at 100) and hours needed for a target mark
  • Regression, residual and train/test charts
โ˜ฐ Main menu
1Show DataHours and marks table
2Train ModelLearn slope and intercept
3EvaluateMSE, RMSE, r, R squared
4Train-Test CheckError on unseen students
5Predict MarksFor given study hours
6Hours for TargetInverse prediction
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Understand the difference between rule-based and learning-based models
  • Fit a regression line and evaluate it with MSE and correlation
  • Use the model to make predictions (deployment)
๐Ÿ“š Data dictionary
NameTypePurpose
hours, marksNumPy arraysTraining data
m, cfloatSlope and intercept
predarraym x hours + c
msefloatMean squared error
Why it matters: Introduces a learning-based regression model and its evaluation in a relatable student context.
# =====================================================================
#   STUDY HOURS vs MARKS - REGRESSION PREDICTOR
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt

hours = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5.5, 6, 7, 8])
marks = np.array([38, 42, 45, 52, 55, 58, 63, 66, 75, 78, 86, 93])
model = {}


def train():
    m, c = np.polyfit(hours, marks, 1)
    model["m"], model["c"] = m, c
    print("Model learnt : marks = %.2f x hours + %.2f" % (m, c))
    print("Meaning      : every extra hour adds about %.1f marks" % m)


def show():
    print("{:>4}{:>7}{:>7}".format("No", "Hours", "Marks"))
    for i, (h, mk) in enumerate(zip(hours, marks), 1):
        print("{:>4}{:>7}{:>7}".format(i, h, mk))


def evaluate():
    pred = model["m"] * hours + model["c"]
    mse = np.mean((marks - pred) ** 2)
    r = np.corrcoef(hours, marks)[0, 1]
    r2 = 1 - ((marks - pred) ** 2).sum() / ((marks - marks.mean()) ** 2).sum()
    print("{:>6}{:>8}{:>11}{:>8}".format("Hours", "Actual", "Predicted", "Error"))
    for h, a, p in zip(hours, marks, pred):
        print("{:>6}{:>8}{:>11.1f}{:>8.1f}".format(h, a, p, a - p))
    print(f"MSE {mse:.3f} | RMSE {np.sqrt(mse):.3f} | r {r:.4f} | R^2 {r2:.4f}")


def train_test():
    idx = np.arange(len(hours))
    test = idx[[2, 6, 10]]
    tr = np.setdiff1d(idx, test)
    m, c = np.polyfit(hours[tr], marks[tr], 1)
    p = m * hours[test] + c
    print("Trained on", len(tr), "students, tested on", len(test))
    for h, a, pp in zip(hours[test], marks[test], p):
        print(f"  hours {h}: actual {a}, predicted {pp:.1f}")
    print("Test RMSE:", round(float(np.sqrt(np.mean((marks[test] - p) ** 2))), 3))


def predict():
    h = float(input("Study hours of a new student: "))
    if not 0 <= h <= 16:
        print("Hours must be 0-16.")
        return
    p = model["m"] * h + model["c"]
    print("Predicted marks:", round(min(100, p), 1), "(capped at 100)" if p > 100 else "")


def hours_for():
    t = float(input("Target marks: "))
    h = (t - model["c"]) / model["m"]
    print(f"Study about {h:.1f} hours per day to reach {t:.0f} marks (if the trend holds).")


def charts():
    m, c = model["m"], model["c"]
    plt.scatter(hours, marks, label="Actual data")
    x = np.linspace(0, 9, 50)
    plt.plot(x, m * x + c, color="red", label="Best-fit line")
    plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
    plt.savefig("regression_line.png", dpi=90, bbox_inches="tight"); plt.show()
    res = marks - (m * hours + c)
    plt.stem(hours, res); plt.axhline(0, color="black"); plt.title("Residuals (actual - predicted)"); plt.xlabel("Hours")
    plt.savefig("residuals.png", dpi=90, bbox_inches="tight"); plt.show()
    test = [2, 6, 10]
    plt.scatter(np.delete(hours, test), np.delete(marks, test), c="blue", label="Training")
    plt.scatter(hours[test], marks[test], c="orange", s=90, marker="s", label="Testing")
    plt.plot(x, m * x + c, "r--"); plt.legend(); plt.title("Train and test points")
    plt.savefig("train_test.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: regression_line.png, residuals.png, train_test.png")


print("=" * 50)
print("   STUDY HOURS vs MARKS PREDICTOR")
print("=" * 50)
while True:
    print("\n1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Study smart!")
        break
    elif ch == "1":
        show()
    elif ch == "2":
        train()
    elif ch in "34567" and not model:
        print("Train the model first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        train_test()
    elif ch == "5":
        predict()
    elif ch == "6":
        hours_for()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Model trained? → No: train with polyfit
  4. pred = m x h + c
  5. Error = actual - predicted
  6. Show metrics / prediction
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Trainmarks = 7.91 x hours + 30.59PASS
2Evaluater ~ 0.99PASS
3Train-testTest RMSE smallPASS
4Predict 5 h~ 70PASS
5Predict 12 hCapped at 100PASS
6Target 90Hours neededPASS
7Predict -2'Hours must be 0-16'PASS
โš  Limitations
  • Only one feature (hours)
  • Small data
  • Relation may not stay linear
  • Other factors (sleep, coaching) ignored
๐Ÿš€ Future scope
  • Multiple regression with sleep and attendance
  • Collect class survey data
  • Use scikit-learn LinearRegression
  • Study planner app

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: hours, marks, model.
  3. 7 functions are defined (lines 12โ€“78) - Python stores them but does NOT run them yet.
  4. Main program starts at line 81: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
train()12โ€“16Trainmain program
show()19โ€“22Showmain program
evaluate()25โ€“33Evaluatemain program
train_test()36โ€“45Train testmain program
predict()48โ€“54Predictmain program
hours_for()57โ€“60Hours formain program
charts()63โ€“78Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
81
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
82
print("   STUDY HOURS vs MARKS PREDICTOR")
๐Ÿ–ฅ๏ธ Output Displays the text "STUDY HOURS vs MARKS PREDICTOR" on the screen
83
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
84
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
85
print("\n1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Train 3.Evaluate 4.Trainโ€ฆ" on the screen
86
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
87
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
88
print("Study smart!")
๐Ÿ–ฅ๏ธ Output Displays the text "Study smart!" on the screen
89
break
๐Ÿ” Loop BREAK - leaves the loop immediately
90
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
91
show()
๐Ÿงฎ Store / Calculate Calls our own function show()
92
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
93
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
94
elif ch in "34567" and not model:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (ch is present in "34567" AND model is False (or empty / zero))
95
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
96
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
97
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
98
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
99
train_test()
๐Ÿงฎ Store / Calculate Calls our own function train_test()
100
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
101
predict()
๐Ÿงฎ Store / Calculate Calls our own function predict()
102
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
103
hours_for()
๐Ÿงฎ Store / Calculate Calls our own function hours_for()
104
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
105
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
106
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
107
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: STUDY HOURS vs MARKS PREDICTOR (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 2 at Enter choice:
    runs: train()
    shows: Model learnt : marks = 7.91 x hours + 30.59 (+2 more lines)
  4. You type 1 at Enter choice:
    runs: show()
    shows: No Hours Marks (+13 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate()
    shows: Hours Actual Predicted Error (+14 more lines)
  6. You type 4 at Enter choice:
    runs: train_test()
    shows: Trained on 9 students, tested on 3 (+5 more lines)
  7. You type 5 at Enter choice:
    runs: predict()
  8. You type 5 at Study hours of a new student:
    shows: Predicted marks: 70.2 (+1 more lines)
  9. You type 5 at Enter choice:
    runs: predict()
  10. You type 12 at Study hours of a new student:
    shows: Predicted marks: 100 (capped at 100) (+1 more lines)
  11. You type 5 at Enter choice:
    runs: predict()
  12. You type -2 at Study hours of a new student:
    shows: Hours must be 0-16. (+1 more lines)
  13. You type 6 at Enter choice:
    runs: hours_for()
  14. You type 90 at Target marks:
    shows: Study about 7.5 hours per day to reach 90 marks (if the trend holds). (+1 more lines)
  15. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  16. You type 0 at Enter choice:
    shows: Study smart!
โ‘ค Inside each function - line by line
train() - lines 12โ€“16
LineCodeWhat it does
12
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
13
m, c = np.polyfit(hours, marks, 1)
๐Ÿ“ฆ Library / Data Fits a straight line / curve through the points; the result is stored in variables m, c
14
model["m"], model["c"] = m, c
๐Ÿงฎ Store / Calculate Stores the tuple m, c in variables model["m"], model["c"]
15
print("Model learnt : marks = %.2f x hours + %.2f" % (m, c))
๐Ÿ–ฅ๏ธ Output Displays the value of "Model learnt : marks = %.2f x hours + %.2f" โ€ฆ on the screen
16
print("Meaning      : every extra hour adds about %.1f marks" % m)
๐Ÿ–ฅ๏ธ Output Displays the value of "Meaning : every extra hour adds about %.1f mโ€ฆ on the screen
show() - lines 19โ€“22
LineCodeWhat it does
19
def show():
๐Ÿงฉ Function DEFINES a function show(). Python only remembers it here - its body runs later, each time show() is called.
20
print("{:>4}{:>7}{:>7}".format("No", "Hours", "Marks"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:>4}{:>7}{:>7}".format("No", "Hours", "Markโ€ฆ on the screen
21
for i, (h, mk) in enumerate(zip(hours, marks), 1):
๐Ÿ” Loop LOOP over zip(hours, marks) with position: in each round i, (h, mk) get (position, item)
22
print("{:>4}{:>7}{:>7}".format(i, h, mk))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:>4}{:>7}{:>7}".format(i, h, mk) on the screen
evaluate() - lines 25โ€“33
LineCodeWhat it does
25
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
26
pred = model["m"] * hours + model["c"]
๐Ÿงฎ Store / Calculate Stores the value of model["m"] * hours + model["c"] (calculated using +) in variable pred
27
mse = np.mean((marks - pred) ** 2)
๐Ÿ“ฆ Library / Data Finds the average (mean) of np; the result is stored in variable mse
28
r = np.corrcoef(hours, marks)[0, 1]
๐Ÿ“ฆ Library / Data Stores the item np.corrcoef(hours, marks)[0, 1] in variable r
29
r2 = 1 - ((marks - pred) ** 2).sum() / ((marks - marks.mean()) ** 2).sum()
๐Ÿงฎ Store / Calculate Stores the value of 1 - ((marks - pred) ** 2).sum() / ((marks - mโ€ฆ (calculated using -) in variable r2
30
print("{:>6}{:>8}{:>11}{:>8}".format("Hours", "Actual", "Predicted", "Error"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:>6}{:>8}{:>11}{:>8}".format("Hours", "Actuโ€ฆ on the screen
31
for h, a, p in zip(hours, marks, pred):
๐Ÿ” Loop LOOP that walks through hours, marks, pred together; h, a, p get one item from each
32
print("{:>6}{:>8}{:>11.1f}{:>8.1f}".format(h, a, p, a - p))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:>6}{:>8}{:>11.1f}{:>8.1f}".format(h, a, p,โ€ฆ on the screen
33
print(f"MSE {mse:.3f} | RMSE {np.sqrt(mse):.3f} | r {r:.4f} | R^2 {r2:.4f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"MSE {mse:.3f} | RMSE {np.sqrt(mse):.3f} | rโ€ฆ with the values filled into { } on the screen
train_test() - lines 36โ€“45
LineCodeWhat it does
36
def train_test():
๐Ÿงฉ Function DEFINES a function train_test(). Python only remembers it here - its body runs later, each time train_test() is called.
37
idx = np.arange(len(hours))
๐Ÿ“ฆ Library / Data Makes a NumPy array of numbers from range(len(hours)); the result is stored in variable idx
38
test = idx[[2, 6, 10]]
๐Ÿงฎ Store / Calculate Stores the item idx[[2, 6, 10]] in variable test
39
tr = np.setdiff1d(idx, test)
๐Ÿ“ฆ Library / Data Calls np.setdiff1d(idx, test); the result is stored in variable tr
40
m, c = np.polyfit(hours[tr], marks[tr], 1)
๐Ÿ“ฆ Library / Data Fits a straight line / curve through the points; the result is stored in variables m, c
41
p = m * hours[test] + c
๐Ÿงฎ Store / Calculate Stores the value of m * hours[test] + c (calculated using +) in variable p
42
print("Trained on", len(tr), "students, tested on", len(test))
๐Ÿ–ฅ๏ธ Output Displays the text "Trained on", then the value of len(tr), then the text "students, tested on", then the value of len(test) on the screen
43
for h, a, pp in zip(hours[test], marks[test], p):
๐Ÿ” Loop LOOP that walks through hours[test], marks[test], p together; h, a, pp get one item from each
44
print(f"  hours {h}: actual {a}, predicted {pp:.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" hours {h}: actual {a}, predicted {pp:.1f}" with the values filled into { } on the screen
45
print("Test RMSE:", round(float(np.sqrt(np.mean((marks[test] - p) ** 2))), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Test RMSE:", then the value of round(float(np.sqrt(np.mean((marks[test] - p)โ€ฆ on the screen
predict() - lines 48โ€“54
LineCodeWhat it does
48
def predict():
๐Ÿงฉ Function DEFINES a function predict(). Python only remembers it here - its body runs later, each time predict() is called.
49
h = float(input("Study hours of a new student: "))
โŒจ๏ธ Input Shows "Study hours of a new student: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable h
50
if not 0 <= h <= 16:
๐Ÿ”€ Decision CHECKS whether NOT 0 <= h <= 16 is True. If True, the indented lines below run; otherwise they are skipped
51
print("Hours must be 0-16.")
๐Ÿ–ฅ๏ธ Output Displays the text "Hours must be 0-16." on the screen
52
return
๐Ÿงฉ Function Ends the function and goes back to the caller
53
p = model["m"] * h + model["c"]
๐Ÿงฎ Store / Calculate Stores the value of model["m"] * h + model["c"] (calculated using +) in variable p
54
print("Predicted marks:", round(min(100, p), 1), "(capped at 100)" if p > 100 else "")
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted marks:", then the value of round(min(100, p), 1), then the value of "(capped at 100)" if p > 100 else "" on the screen
hours_for() - lines 57โ€“60
LineCodeWhat it does
57
def hours_for():
๐Ÿงฉ Function DEFINES a function hours_for(). Python only remembers it here - its body runs later, each time hours_for() is called.
58
t = float(input("Target marks: "))
โŒจ๏ธ Input Shows "Target marks: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable t
59
h = (t - model["c"]) / model["m"]
๐Ÿงฎ Store / Calculate Stores the value of (t - model["c"]) / model["m"] (calculated using รท) in variable h
60
print(f"Study about {h:.1f} hours per day to reach {t:.0f} marks (if the trend holds).")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Study about {h:.1f} hours per day to reach โ€ฆ with the values filled into { } on the screen
charts() - lines 63โ€“78
LineCodeWhat it does
63
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
64
m, c = model["m"], model["c"]
๐Ÿงฎ Store / Calculate Stores model["m"], model["c"] into m, c respectively
65
plt.scatter(hours, marks, label="Actual data")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of hours, marks
66
x = np.linspace(0, 9, 50)
๐Ÿ“ฆ Library / Data Makes 50 equally spaced numbers from 0 to 9; the result is stored in variable x
67
plt.plot(x, m * x + c, color="red", label="Best-fit line")
๐Ÿ–ฅ๏ธ Output Draws a line chart of x, m * x + c
68
plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Study hours per day" as the label of the X-axis
68
plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Marks" as the label of the Y-axis
68
plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Linear regression: hours vs marks" as the title of the chart
68
plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
68
plt.xlabel("Study hours per day"); plt.ylabel("Marks"); plt.title("Linear regression: hours vs marks"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
69
plt.savefig("regression_line.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "regression_line.png"
69
plt.savefig("regression_line.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
70
res = marks - (m * hours + c)
๐Ÿงฎ Store / Calculate Stores the value of marks - (m * hours + c) (calculated using -) in variable res
71
plt.stem(hours, res); plt.axhline(0, color="black"); plt.title("Residuals (actual - predicted)"); plt.xlabel("Hours")
๐Ÿ–ฅ๏ธ Output Draws a stem chart
71
plt.stem(hours, res); plt.axhline(0, color="black"); plt.title("Residuals (actual - predicted)"); plt.xlabel("Hours")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
71
plt.stem(hours, res); plt.axhline(0, color="black"); plt.title("Residuals (actual - predicted)"); plt.xlabel("Hours")
๐Ÿ–ฅ๏ธ Output Writes "Residuals (actual - predicted)" as the title of the chart
71
plt.stem(hours, res); plt.axhline(0, color="black"); plt.title("Residuals (actual - predicted)"); plt.xlabel("Hours")
๐Ÿ–ฅ๏ธ Output Writes "Hours" as the label of the X-axis
72
plt.savefig("residuals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "residuals.png"
72
plt.savefig("residuals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
73
test = [2, 6, 10]
๐Ÿงฎ Store / Calculate Stores a list [2, 6, 10] in variable test
74
plt.scatter(np.delete(hours, test), np.delete(marks, test), c="blue", label="Training")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of np.delete(hours, test), np.delete(marks, test)
75
plt.scatter(hours[test], marks[test], c="orange", s=90, marker="s", label="Testing")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of hours[test], marks[test]
76
plt.plot(x, m * x + c, "r--"); plt.legend(); plt.title("Train and test points")
๐Ÿ–ฅ๏ธ Output Draws a line chart of x, m * x + c, "r--"
76
plt.plot(x, m * x + c, "r--"); plt.legend(); plt.title("Train and test points")
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
76
plt.plot(x, m * x + c, "r--"); plt.legend(); plt.title("Train and test points")
๐Ÿ–ฅ๏ธ Output Writes "Train and test points" as the title of the chart
77
plt.savefig("train_test.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "train_test.png"
77
plt.savefig("train_test.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
78
print("Charts saved: regression_line.png, residuals.png, train_test.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: regression_line.pngโ€ฆ" on the screen
Q1. What is regression?

A supervised learning method that predicts a continuous number (marks) from input (hours).

Q2. What do m and c mean?

m = increase in marks per extra hour; c = predicted marks at 0 hours.

Q3. What is MSE?

Mean of squared differences between actual and predicted values; lower is better.

Q4. What is R squared?

Fraction of variation in marks explained by the model (1 = perfect).

Q5. Why cap at 100?

Marks cannot exceed 100 - the straight line does not know this rule.

06

Image Filter Studio - Convolution in Action (Computer Vision)

PYTHON + OPENCVSDG 9 - Industry, Innovation and InfrastructureKernelscv2.filter2D convolutionblur / sharpen / edge detectiongrayscaleimage grid
๐Ÿ“ 118 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 71 output lines๐Ÿ“„ 25+ page report

Applies different convolution kernels - blur, sharpen, edge detection and emboss - to an image with OpenCV, prints each kernel and the effect on pixel statistics, and saves a comparison grid.

โœจ Features
  • Image read with OpenCV and converted to grayscale
  • Convolution with Blur, Sharpen, Edge, Emboss and Sobel kernels using cv2.filter2D
  • Manual convolution on a 5x5 matrix to show how one output pixel is calculated
  • Custom kernel entered by the user
  • Statistics of each output (mean, std, edge pixels)
  • Image properties: shape, pixel value at a point, histogram
โ˜ฐ Main menu
1Image InfoShape, size, pixel values
2Apply All FiltersBlur, sharpen, edge, emboss, sobel
3Manual ConvolutionStep-by-step on a 5x5 grid
4Custom KernelUser types 9 numbers
5Resize & CropImage operations
6ChartsFilter grid, kernel demo, histograms
0ExitEnds program
๐ŸŽฏ Objectives
  • Apply convolution kernels to an image using cv2.filter2D
  • Compare the effect of blur, sharpen, edge and emboss kernels
  • Relate manual kernels to the feature maps learnt by a CNN
๐Ÿ“š Data dictionary
NameTypePurpose
img / grayNumPy arraysColour (BGR) and grayscale images
kernelsdictName -> 3x3 kernel
outputsdictFiltered images
grid5x5 arraySmall matrix for manual convolution
Why it matters: Makes the Convolution Operator and CNN kernel concept from Unit 5 visible and tangible.
# =====================================================================
#   IMAGE FILTER STUDIO - CONVOLUTION IN ACTION  (Computer Vision)
# =====================================================================
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("flower.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernels = {"Blur": np.ones((3, 3)) / 9,
           "Sharpen": np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]),
           "Edge": np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]),
           "Emboss": np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]),
           "Sobel-X": np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])}
grid = np.array([[10, 10, 10, 80, 80], [10, 10, 10, 80, 80], [10, 10, 10, 80, 80], [10, 10, 10, 80, 80], [10, 10, 10, 80, 80]])


def info():
    print("Colour image shape (rows, cols, channels):", img.shape)
    print("Total pixels:", img.shape[0] * img.shape[1], "| data type:", img.dtype)
    print("Pixel at (50, 50) BGR:", img[50, 50], "| gray:", gray[50, 50])
    print("Gray min/max/mean: %d / %d / %.1f" % (gray.min(), gray.max(), gray.mean()))


def apply_all():
    print("{:<9}{:>8}{:>8}{:>13}".format("Filter", "Mean", "Std", "Bright px"))
    print("{:<9}{:>8.1f}{:>8.1f}{:>13}".format("Original", gray.mean(), gray.std(), (gray > 200).sum()))
    for name, k in kernels.items():
        out = cv2.filter2D(gray, -1, k)
        print("{:<9}{:>8.1f}{:>8.1f}{:>13}".format(name, out.mean(), out.std(), (out > 200).sum()))
    print("Edge / Sobel give dark images with bright edges; Blur reduces std (smoother).")


def manual():
    k = kernels["Edge"]
    print("Input 5x5 grid (dark | bright boundary):\n", grid)
    print("Edge kernel:\n", k)
    out = np.zeros((3, 3), int)
    for r in range(3):
        for c in range(3):
            patch = grid[r:r + 3, c:c + 3]
            out[r, c] = (patch * k).sum()
    p = grid[1:4, 1:4]
    print("Patch at centre:\n", p)
    print("Centre output = sum(patch x kernel) =", (p * k).sum())
    print("Full 3x3 output (valid convolution):\n", out)
    print("Large values appear exactly at the boundary column - that is an EDGE!")


def custom():
    vals = input("Enter 9 kernel numbers separated by space: ").split()
    try:
        k = np.array([float(v) for v in vals]).reshape(3, 3)
    except ValueError:
        print("Enter 9 numbers only.")
        return
    out = cv2.filter2D(gray, -1, k)
    print("Your kernel:\n", k)
    print("Output mean %.1f std %.1f (original std %.1f)" % (out.mean(), out.std(), gray.std()))


def resize_crop():
    p = float(input("Resize percent: "))
    small = cv2.resize(img, None, fx=p / 100, fy=p / 100)
    h, w = gray.shape
    crop = img[h // 4: 3 * h // 4, w // 4: 3 * w // 4]
    print("Original:", img.shape, "| resized:", small.shape, "| centre crop:", crop.shape)


def charts():
    outs = {"Original": gray}
    outs.update({n: cv2.filter2D(gray, -1, k) for n, k in kernels.items()})
    fig, axes = plt.subplots(2, 3, figsize=(10, 6))
    for ax, (n, im) in zip(axes.ravel(), outs.items()):
        ax.imshow(im, cmap="gray"); ax.set_title(n); ax.axis("off")
    plt.tight_layout(); plt.savefig("filters.png", dpi=80); plt.show()
    out = np.zeros((3, 3))
    for r in range(3):
        for c in range(3):
            out[r, c] = (grid[r:r + 3, c:c + 3] * kernels["Edge"]).sum()
    fig, ax = plt.subplots(1, 3, figsize=(9, 3))
    for a, m, t in zip(ax, [grid, kernels["Edge"], out], ["Input 5x5", "Edge kernel", "Output 3x3"]):
        a.imshow(m, cmap="viridis"); a.set_title(t)
        for (i, j), v in np.ndenumerate(m):
            a.text(j, i, int(v), ha="center", va="center", color="white", fontsize=9)
        a.set_xticks([]); a.set_yticks([])
    plt.tight_layout(); plt.savefig("kernel_demo.png", dpi=90); plt.show()
    plt.hist(gray.ravel(), 50, alpha=.6, label="Original")
    plt.hist(cv2.filter2D(gray, -1, kernels["Blur"]).ravel(), 50, alpha=.6, label="Blur")
    plt.legend(); plt.title("Pixel intensity histogram"); plt.xlabel("Gray value")
    plt.savefig("histograms.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: filters.png, kernel_demo.png, histograms.png")


print("=" * 50)
print("   IMAGE FILTER STUDIO  (Computer Vision)")
print("=" * 50)
while True:
    print("\n1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        info()
    elif ch == "2":
        apply_all()
    elif ch == "3":
        manual()
    elif ch == "4":
        custom()
    elif ch == "5":
        resize_crop()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Read flower.jpg
  3. Image found? → No: show error and stop
  4. Show menu and read choice
  5. Select kernel
  6. cv2.filter2D(gray, -1, kernel)
  7. Show statistics / images
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Image infoShape (rows, cols, 3)PASS
2Apply filters5 outputs with statisticsPASS
3Manual convolutionCentre value calculatedPASS
4Custom kernel all 1/9Same as blurPASS
5Kernel with letters'Enter 9 numbers'PASS
6Resize 50 %Half shapePASS
7Charts3 PNG filesPASS
โš  Limitations
  • Fixed 3x3 kernels
  • Grayscale only for filters
  • Single image
  • No learning - kernels are hand-made (CNNs learn them)
๐Ÿš€ Future scope
  • Live webcam filters
  • Learn kernels with a CNN (Class XII)
  • Edge-based object counting
  • Photo editor GUI

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): cv2 - OpenCV image processing, numpy - fast arrays and maths, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: img, gray, kernels, grid.
  3. 6 functions are defined (lines 18โ€“92) - Python stores them but does NOT run them yet.
  4. Main program starts at line 95: print("=" * 50) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
info()18โ€“22Infomain program
apply_all()25โ€“31Apply allmain program
manual()34โ€“47Manualmain program
custom()50โ€“59Custommain program
resize_crop()62โ€“67Resize cropmain program
charts()70โ€“92Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
95
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
96
print("   IMAGE FILTER STUDIO  (Computer Vision)")
๐Ÿ–ฅ๏ธ Output Displays the text "IMAGE FILTER STUDIO (Computer Visโ€ฆ" on the screen
97
print("=" * 50)
๐Ÿ–ฅ๏ธ Output Displays a line of 50 "=" signs on the screen
98
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
99
print("\n1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Info 2.Apply Filters 3.Manual Cโ€ฆ" on the screen
100
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
101
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
102
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
103
break
๐Ÿ” Loop BREAK - leaves the loop immediately
104
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
105
info()
๐Ÿงฎ Store / Calculate Calls our own function info()
106
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
107
apply_all()
๐Ÿงฎ Store / Calculate Calls our own function apply_all()
108
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
109
manual()
๐Ÿงฎ Store / Calculate Calls our own function manual()
110
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
111
custom()
๐Ÿงฎ Store / Calculate Calls our own function custom()
112
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
113
resize_crop()
๐Ÿงฎ Store / Calculate Calls our own function resize_crop()
114
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
115
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
116
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
117
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Inside each function - line by line
info() - lines 18โ€“22
LineCodeWhat it does
18
def info():
๐Ÿงฉ Function DEFINES a function info(). Python only remembers it here - its body runs later, each time info() is called.
19
print("Colour image shape (rows, cols, channels):", img.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Colour image shape (rows, cols, cโ€ฆ", then the value of img.shape on the screen
20
print("Total pixels:", img.shape[0] * img.shape[1], "| data type:", img.dtype)
๐Ÿ–ฅ๏ธ Output Displays the text "Total pixels:", then the value of img.shape[0] * img.shape[1], then the text "| data type:", then the value of img.dtype on the screen
21
print("Pixel at (50, 50) BGR:", img[50, 50], "| gray:", gray[50, 50])
๐Ÿ–ฅ๏ธ Output Displays the text "Pixel at (50, 50) BGR:", then the value of img[50, 50], then the text "| gray:", then the value of gray[50, 50] on the screen
22
print("Gray min/max/mean: %d / %d / %.1f" % (gray.min(), gray.max(), gray.mean()))
๐Ÿ–ฅ๏ธ Output Displays the value of "Gray min/max/mean: %d / %d / %.1f" % (gray.mโ€ฆ on the screen
apply_all() - lines 25โ€“31
LineCodeWhat it does
25
def apply_all():
๐Ÿงฉ Function DEFINES a function apply_all(). Python only remembers it here - its body runs later, each time apply_all() is called.
26
print("{:<9}{:>8}{:>8}{:>13}".format("Filter", "Mean", "Std", "Bright px"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<9}{:>8}{:>8}{:>13}".format("Filter", "Meaโ€ฆ on the screen
27
print("{:<9}{:>8.1f}{:>8.1f}{:>13}".format("Original", gray.mean(), gray.std(), (gray > 200).sum()))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<9}{:>8.1f}{:>8.1f}{:>13}".format("Originaโ€ฆ on the screen
28
for name, k in kernels.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary kernels; name, k get one pair each round
29
out = cv2.filter2D(gray, -1, k)
๐Ÿ“ฆ Library / Data Applies a filter (kernel) to the image; the result is stored in variable out
30
print("{:<9}{:>8.1f}{:>8.1f}{:>13}".format(name, out.mean(), out.std(), (out > 200).sum()))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<9}{:>8.1f}{:>8.1f}{:>13}".format(name, ouโ€ฆ on the screen
31
print("Edge / Sobel give dark images with bright edges; Blur reduces std (smoother).")
๐Ÿ–ฅ๏ธ Output Displays the text "Edge / Sobel give dark images witโ€ฆ" on the screen
manual() - lines 34โ€“47
LineCodeWhat it does
34
def manual():
๐Ÿงฉ Function DEFINES a function manual(). Python only remembers it here - its body runs later, each time manual() is called.
35
k = kernels["Edge"]
๐Ÿงฎ Store / Calculate Stores the item kernels["Edge"] in variable k
36
print("Input 5x5 grid (dark | bright boundary):\n", grid)
๐Ÿ–ฅ๏ธ Output Displays the text "Input 5x5 grid (dark | bright bouโ€ฆ", then the value of grid on the screen
37
print("Edge kernel:\n", k)
๐Ÿ–ฅ๏ธ Output Displays the text "Edge kernel:", then the value of k on the screen
38
out = np.zeros((3, 3), int)
๐Ÿ“ฆ Library / Data Makes a NumPy array filled with 0s; the result is stored in variable out
39
for r in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, r takes that value and the indented block runs once
40
for c in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, c takes that value and the indented block runs once
41
patch = grid[r:r + 3, c:c + 3]
๐Ÿงฎ Store / Calculate Stores a slice grid[r:r + 3, c:c + 3] (part of grid) in variable patch
42
out[r, c] = (patch * k).sum()
๐Ÿงฎ Store / Calculate Adds up all values of patch * k; the result is put into out[r, c] (item r, c of out)
43
p = grid[1:4, 1:4]
๐Ÿงฎ Store / Calculate Stores a slice grid[1:4, 1:4] (part of grid) in variable p
44
print("Patch at centre:\n", p)
๐Ÿ–ฅ๏ธ Output Displays the text "Patch at centre:", then the value of p on the screen
45
print("Centre output = sum(patch x kernel) =", (p * k).sum())
๐Ÿ–ฅ๏ธ Output Displays the text "Centre output = sum(patch x kerneโ€ฆ", then the value of (p * k).sum() on the screen
46
print("Full 3x3 output (valid convolution):\n", out)
๐Ÿ–ฅ๏ธ Output Displays the text "Full 3x3 output (valid convolutioโ€ฆ", then the value of out on the screen
47
print("Large values appear exactly at the boundary column - that is an EDGE!")
๐Ÿ–ฅ๏ธ Output Displays the text "Large values appear exactly at thโ€ฆ" on the screen
custom() - lines 50โ€“59
LineCodeWhat it does
50
def custom():
๐Ÿงฉ Function DEFINES a function custom(). Python only remembers it here - its body runs later, each time custom() is called.
51
vals = input("Enter 9 kernel numbers separated by space: ").split()
โŒจ๏ธ Input Breaks input("Enter 9 kernel numbers separated by spโ€ฆ into a list of words (at spaces); the result is stored in variable vals
52
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
53
k = np.array([float(v) for v in vals]).reshape(3, 3)
๐Ÿ“ฆ Library / Data Changes the shape of np.array([float(v) for v in vals]) to (3, 3); the result is stored in variable k
54
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
55
print("Enter 9 numbers only.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter 9 numbers only." on the screen
56
return
๐Ÿงฉ Function Ends the function and goes back to the caller
57
out = cv2.filter2D(gray, -1, k)
๐Ÿ“ฆ Library / Data Applies a filter (kernel) to the image; the result is stored in variable out
58
print("Your kernel:\n", k)
๐Ÿ–ฅ๏ธ Output Displays the text "Your kernel:", then the value of k on the screen
59
print("Output mean %.1f std %.1f (original std %.1f)" % (out.mean(), out.std(), gray.std()))
๐Ÿ–ฅ๏ธ Output Displays the value of "Output mean %.1f std %.1f (original std %.1fโ€ฆ on the screen
resize_crop() - lines 62โ€“67
LineCodeWhat it does
62
def resize_crop():
๐Ÿงฉ Function DEFINES a function resize_crop(). Python only remembers it here - its body runs later, each time resize_crop() is called.
63
p = float(input("Resize percent: "))
โŒจ๏ธ Input Shows "Resize percent: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable p
64
small = cv2.resize(img, None, fx=p / 100, fy=p / 100)
๐Ÿ“ฆ Library / Data Changes the size of the image; the result is stored in variable small
65
h, w = gray.shape
๐Ÿงฎ Store / Calculate Stores gray.shape in variables h, w
66
crop = img[h // 4: 3 * h // 4, w // 4: 3 * w // 4]
๐Ÿงฎ Store / Calculate Stores a slice img[h // 4: 3 * h // 4, w // 4: 3 * w // 4] (part of img) in variable crop
67
print("Original:", img.shape, "| resized:", small.shape, "| centre crop:", crop.shape)
๐Ÿ–ฅ๏ธ Output Displays the text "Original:", then the value of img.shape, then the text "| resized:", then the value of small.shape, then the text "| centre crop:", then the value of crop.shape on the screen
charts() - lines 70โ€“92
LineCodeWhat it does
70
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
71
outs = {"Original": gray}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Original": gray} in variable outs
72
outs.update({n: cv2.filter2D(gray, -1, k) for n, k in kernels.items()})
๐Ÿ“ฆ Library / Data Updates outs with {n: cv2.filter2D(gray, -1, k) for n, k in kerโ€ฆ
73
fig, axes = plt.subplots(2, 3, figsize=(10, 6))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, axes
74
for ax, (n, im) in zip(axes.ravel(), outs.items()):
๐Ÿ” Loop LOOP that walks through axes.ravel(), outs.items() together; ax, (n, im) get one item from each
75
ax.imshow(im, cmap="gray"); ax.set_title(n); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
75
ax.imshow(im, cmap="gray"); ax.set_title(n); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
75
ax.imshow(im, cmap="gray"); ax.set_title(n); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
76
plt.tight_layout(); plt.savefig("filters.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
76
plt.tight_layout(); plt.savefig("filters.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "filters.png"
76
plt.tight_layout(); plt.savefig("filters.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
77
out = np.zeros((3, 3))
๐Ÿ“ฆ Library / Data Makes a NumPy array filled with 0s; the result is stored in variable out
78
for r in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, r takes that value and the indented block runs once
79
for c in range(3):
๐Ÿ” Loop LOOP: gives the numbers 0 to 2 (3 numbers); for each number, c takes that value and the indented block runs once
80
out[r, c] = (grid[r:r + 3, c:c + 3] * kernels["Edge"]).sum()
๐Ÿงฎ Store / Calculate Adds up all values of grid[r:r + 3, c:c + 3] * kernels["Edge"]; the result is put into out[r, c] (item r, c of out)
81
fig, ax = plt.subplots(1, 3, figsize=(9, 3))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax
82
for a, m, t in zip(ax, [grid, kernels["Edge"], out], ["Input 5x5", "Edge kernel", "Output 3x3"]):
๐Ÿ” Loop LOOP that walks through ax, [grid, kernels["Edge"], out], ["Input 5x5", "Edge kernel", "Output 3x3"] together; a, m, t get one item from each
83
a.imshow(m, cmap="viridis"); a.set_title(t)
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
83
a.imshow(m, cmap="viridis"); a.set_title(t)
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
84
for (i, j), v in np.ndenumerate(m):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(m) one-by-one into (i, j), v and runs the indented block for it
85
a.text(j, i, int(v), ha="center", va="center", color="white", fontsize=9)
๐Ÿงฎ Store / Calculate Writes text on the chart
86
a.set_xticks([]); a.set_yticks([])
๐Ÿงฎ Store / Calculate Calls a.set_xticks([])
86
a.set_xticks([]); a.set_yticks([])
๐Ÿงฎ Store / Calculate Calls a.set_yticks([])
87
plt.tight_layout(); plt.savefig("kernel_demo.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
87
plt.tight_layout(); plt.savefig("kernel_demo.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "kernel_demo.png"
87
plt.tight_layout(); plt.savefig("kernel_demo.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
plt.hist(gray.ravel(), 50, alpha=.6, label="Original")
๐Ÿ–ฅ๏ธ Output Draws a histogram of gray.ravel()
89
plt.hist(cv2.filter2D(gray, -1, kernels["Blur"]).ravel(), 50, alpha=.6, label="Blur")
๐Ÿ–ฅ๏ธ Output Draws a histogram of cv2.filter2D(gray, -1, kernels["Blur"]).ravelโ€ฆ
90
plt.legend(); plt.title("Pixel intensity histogram"); plt.xlabel("Gray value")
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
90
plt.legend(); plt.title("Pixel intensity histogram"); plt.xlabel("Gray value")
๐Ÿ–ฅ๏ธ Output Writes "Pixel intensity histogram" as the title of the chart
90
plt.legend(); plt.title("Pixel intensity histogram"); plt.xlabel("Gray value")
๐Ÿ–ฅ๏ธ Output Writes "Gray value" as the label of the X-axis
91
plt.savefig("histograms.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "histograms.png"
91
plt.savefig("histograms.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
92
print("Charts saved: filters.png, kernel_demo.png, histograms.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: filters.png, kernelโ€ฆ" on the screen
Q1. What is convolution?

Sliding a small kernel over the image; each output pixel is the sum of element-wise products of the kernel and the pixels under it.

Q2. What does an edge kernel do?

Highlights places where brightness changes sharply - the edges.

Q3. Why grayscale?

One channel makes convolution simpler and faster.

Q4. How is convolution used in CNNs?

Convolution layers learn their own kernels from data to detect features like edges and shapes.

Q5. What does cv2.filter2D(-1) mean?

-1 keeps the output depth same as the input image.

07

School Helpdesk Chatbot (Script Bot)

PYTHONSDG 4 - Quality EducationDictionaries of intentskeyword matchingstring methodswhile loopfallback response
๐Ÿ“ 119 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 96 output lines๐Ÿ“„ 25+ page report

A script-based chatbot that answers common questions about the school - timings, fees, library, admission, transport and exams - by matching keywords to intents, and keeps a log of unanswered questions for improvement.

โœจ Features
  • Script bot with intents (keywords + reply) stored in a dictionary
  • Keyword matching with prefix match ('timings' matches 'timing')
  • Unanswered questions saved to unanswered.txt for the admin
  • Admin mode: add a new intent at run time
  • Chat log with timestamps and conversation statistics
  • Comparison of script bot vs smart bot explained
โ˜ฐ Main menu
1Chat with BotConversation until 'bye'
2Show IntentsKeywords and replies
3Add Intent (Admin)Password protected
4Unanswered QuestionsReads unanswered.txt
5Chat StatisticsAnswered vs unanswered, top intents
6Script vs Smart BotComparison table
0ExitEnds program
๐ŸŽฏ Objectives
  • Represent intents and replies using a dictionary
  • Match user messages with keywords after normalising the text
  • Log unanswered questions to improve the bot
๐Ÿ“š Data dictionary
NameTypePurpose
intentsdictname -> (keywords, reply)
hitsdictTimes each intent was used
unanswered.txttext fileQuestions bot could not answer
loglistConversation lines
Why it matters: Clearly shows the difference between a script bot and a smart bot taught in the NLP unit.
# =====================================================================
#   SCHOOL HELPDESK CHATBOT  (Script Bot, NLP)
# =====================================================================
import os
from datetime import datetime

intents = {
    "greet":     (["hi", "hello", "namaste", "hey"], "Hello! I am KV Helpdesk Bot. How can I help you?"),
    "timing":    (["timing", "time", "start", "close"], "School timings: 7:50 AM to 1:50 PM (Mon-Sat)."),
    "fees":      (["fee", "pay", "payment"], "Fees are paid online through the KVS UBI fee portal every quarter."),
    "library":   (["library", "book"], "Library is open 8:00 AM to 1:30 PM. Issue period: 14 days."),
    "transport": (["bus", "transport", "van"], "School has no own bus; approved private vans are listed at the office."),
    "admission": (["admission", "admit", "seat"], "Admissions follow KVS guidelines; Class 1 registration is online."),
    "exam":      (["exam", "test", "result"], "Half-yearly exams in September, session-ending exams in February/March.")}
hits = {k: 0 for k in intents}
log = []
stats = {"answered": 0, "unanswered": 0}
if os.path.exists("unanswered.txt"):
    os.remove("unanswered.txt")


def reply_to(msg):
    words = msg.lower().replace("?", "").replace(",", "").split()
    for name, (keys, answer) in intents.items():
        if any(w.startswith(k) for w in words for k in keys):
            hits[name] += 1
            return answer
    return None


def chat():
    print("Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'bye' to end.")
    while True:
        msg = input("You: ").strip()
        if msg.lower() in ("bye", "exit", "quit"):
            print("Bot: Thank you! Have a great day.")
            break
        r = reply_to(msg)
        if r is None:
            r = "Sorry, I can answer only school-related questions. I have noted your query for the office."
            stats["unanswered"] += 1
            with open("unanswered.txt", "a") as f:
                f.write(msg + "\n")
        else:
            stats["answered"] += 1
        log.append((datetime(2026, 7, 1, 10, len(log)).strftime("%H:%M"), msg, r))
        print("Bot:", r)


def show_intents():
    for name, (keys, ans) in intents.items():
        print(f"{name:<10} keys={keys}\n{'':<10} -> {ans}")


def add_intent():
    if input("Admin password: ") != "kv@123":
        print("Access denied.")
        return
    name = input("Intent name: ").strip().lower()
    keys = [k.strip().lower() for k in input("Keywords (comma separated): ").split(",")]
    ans = input("Reply: ").strip()
    intents[name] = (keys, ans)
    hits[name] = 0
    print(f"Intent '{name}' added. The bot now knows {len(intents)} intents.")


def unanswered():
    if os.path.exists("unanswered.txt"):
        with open("unanswered.txt") as f:
            for i, line in enumerate(f, 1):
                print(f"{i}. {line.strip()}")
    else:
        print("No unanswered questions.")


def statistics():
    tot = stats["answered"] + stats["unanswered"]
    print(f"Messages: {tot} | Answered: {stats['answered']} | Unanswered: {stats['unanswered']}")
    print(f"Answer rate: {stats['answered'] / tot * 100:.1f} %")
    print("Intent usage:")
    for k, v in sorted(hits.items(), key=lambda x: -x[1]):
        if v:
            print(f"  {k:<10} {'#' * v} {v}")
    print("Chat log (last 3):")
    for t, m, r in log[-3:]:
        print(f"  [{t}] {m}")


def compare():
    print(f"{'Feature':<22}{'Script bot':<26}{'Smart bot'}")
    for a, b, c in [("Working", "Fixed rules / keywords", "AI + NLP models"), ("Learning", "No learning", "Learns from data"),
                    ("Flexibility", "Limited", "Handles new sentences"), ("Example", "This helpdesk bot", "Google Assistant, ChatGPT")]:
        print(f"{a:<22}{b:<26}{c}")


print("=" * 55)
print("   KV HELPDESK CHATBOT  (Script Bot)")
print("=" * 55)
while True:
    print("\n1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Goodbye!")
        break
    elif ch == "1":
        chat()
    elif ch == "2":
        show_intents()
    elif ch == "3":
        add_intent()
    elif ch == "4":
        unanswered()
    elif ch == "5":
        statistics()
    elif ch == "6":
        compare()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu
  3. Read user message
  4. Message is 'bye'? → No: search intents
  5. Keyword matched? → No: save to unanswered.txt
  6. Print reply
  7. Update statistics
  8. Stop
#Test case / inputExpected resultStatus
1'Hi'GreetingPASS
2'What are the school timings?'Timing replyPASS
3'bus near Rohini'Transport replyPASS
4'Who won the IPL?'Sorry + savedPASS
5Add intent 'canteen'New reply worksPASS
6Wrong admin passwordDeniedPASS
7StatisticsAnswered 5 / 6PASS
โš  Limitations
  • Only keyword matching - no understanding
  • Spelling mistakes not handled
  • English only
  • Fixed replies
๐Ÿš€ Future scope
  • Use NLP intent classifier (Class XI)
  • Hindi voice input
  • Connect to school website / WhatsApp
  • Learn from unanswered questions

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): os - file and folder operations, datetime - dates and times are loaded.
  2. Global variables / constants are created: intents, hits, log, stats.
  3. 7 functions are defined (lines 22โ€“93) - Python stores them but does NOT run them yet.
  4. Main program starts at line 18: if os.path.exists("unanswered.txt"): - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
reply_to(msg)22โ€“28Reply tochat()
chat()31โ€“47Chatmain program
show_intents()50โ€“52Show intentsmain program
add_intent()55โ€“64Add intentmain program
unanswered()67โ€“73Unansweredmain program
statistics()76โ€“86Statisticsmain program
compare()89โ€“93Comparemain program
โ‘ข Main program - line by line
LineCodeWhat it does
18
if os.path.exists("unanswered.txt"):
๐Ÿ”€ Decision CHECKS whether os.path.exists("unanswered.txt") is True. If True, the indented lines below run; otherwise they are skipped
19
os.remove("unanswered.txt")
๐Ÿ“ File Deletes the file "unanswered.txt"
96
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
97
print("   KV HELPDESK CHATBOT  (Script Bot)")
๐Ÿ–ฅ๏ธ Output Displays the text "KV HELPDESK CHATBOT (Script Bot)" on the screen
98
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
99
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
100
print("\n1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Chat 2.Intents 3.Add Intent 4.Uโ€ฆ" on the screen
101
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
102
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
103
print("Goodbye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Goodbye!" on the screen
104
break
๐Ÿ” Loop BREAK - leaves the loop immediately
105
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
106
chat()
๐Ÿงฎ Store / Calculate Calls our own function chat()
107
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
108
show_intents()
๐Ÿงฎ Store / Calculate Calls our own function show_intents()
109
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
110
add_intent()
๐Ÿงฎ Store / Calculate Calls our own function add_intent()
111
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
112
unanswered()
๐Ÿงฎ Store / Calculate Calls our own function unanswered()
113
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
114
statistics()
๐Ÿงฎ Store / Calculate Calls our own function statistics()
115
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
116
compare()
๐Ÿงฎ Store / Calculate Calls our own function compare()
117
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
118
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: KV HELPDESK CHATBOT (Script Bot) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: chat()
    shows: Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'by
  3. You type Hi at You:
    runs: reply_to()
    shows: Bot: Hello! I am KV Helpdesk Bot. How can I help you?
  4. You type What are the school timings? at You:
    runs: reply_to()
    shows: Bot: School timings: 7:50 AM to 1:50 PM (Mon-Sat).
  5. You type Is there a bus facility near Rohini? at You:
    runs: reply_to()
    shows: Bot: School has no own bus; approved private vans are listed at the office.
  6. You type When is the library open? at You:
    runs: reply_to()
    shows: Bot: Library is open 8:00 AM to 1:30 PM. Issue period: 14 days.
  7. You type Who won the IPL? at You:
    runs: reply_to()
    shows: Bot: Sorry, I can answer only school-related questions. I have noted your query for the of
  8. You type How do I pay the fees? at You:
    runs: reply_to()
    shows: Bot: Fees are paid online through the KVS UBI fee portal every quarter.
  9. You type Is the canteen open on Saturday? at You:
    runs: reply_to()
    shows: Bot: Sorry, I can answer only school-related questions. I have noted your query for the of
  10. You type bye at You:
    shows: Bot: Thank you! Have a great day. (+1 more lines)
  11. You type 3 at Enter choice:
    runs: add_intent()
  12. You type abc at Admin password:
    shows: Access denied. (+1 more lines)
  13. You type 3 at Enter choice:
    runs: add_intent()
  14. You type kv@123 at Admin password:
  15. You type canteen at Intent name:
  16. You type canteen, food, lunch at Keywords (comma separated):
  17. You type Canteen is open 9:30 AM to 12:30 PM on all working days. at Reply:
    shows: Intent 'canteen' added. The bot now knows 8 intents. (+1 more lines)
  18. You type 1 at Enter choice:
    runs: chat()
    shows: Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'by
  19. You type Is the canteen open on Saturday? at You:
    runs: reply_to()
    shows: Bot: Canteen is open 9:30 AM to 12:30 PM on all working days.
  20. You type bye at You:
    shows: Bot: Thank you! Have a great day. (+1 more lines)
  21. You type 2 at Enter choice:
    runs: show_intents()
    shows: greet keys=['hi', 'hello', 'namaste', 'hey'] (+16 more lines)
  22. You type 4 at Enter choice:
    runs: unanswered()
    shows: 1. Who won the IPL? (+2 more lines)
  23. You type 5 at Enter choice:
    runs: statistics()
    shows: Messages: 8 | Answered: 6 | Unanswered: 2 (+13 more lines)
  24. You type 6 at Enter choice:
    runs: compare()
    shows: Feature Script bot Smart bot (+5 more lines)
  25. You type 0 at Enter choice:
    shows: Goodbye!
โ‘ค Inside each function - line by line
reply_to() - lines 22โ€“28
LineCodeWhat it does
22
def reply_to(msg):
๐Ÿงฉ Function DEFINES a function reply_to(msg). Python only remembers it here - its body runs later, each time reply_to() is called.
23
words = msg.lower().replace("?", "").replace(",", "").split()
๐Ÿงฎ Store / Calculate Breaks msg.lower().replace("?", "").replace(",", "") into a list of words (at spaces); the result is stored in variable words
24
for name, (keys, answer) in intents.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary intents; name, (keys, answer) get one pair each round
25
if any(w.startswith(k) for w in words for k in keys):
๐Ÿ”€ Decision CHECKS whether any(w.startswith(k) for w in words for k in kโ€ฆ is True. If True, the indented lines below run; otherwise they are skipped
26
hits[name] += 1
๐Ÿงฎ Store / Calculate Adds 1 to hits[name] (same as hits[name] = hits[name] + 1)
27
return answer
๐Ÿงฉ Function Sends back (returns) the value of answer to the line that called the function
28
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
chat() - lines 31โ€“47
LineCodeWhat it does
31
def chat():
๐Ÿงฉ Function DEFINES a function chat(). Python only remembers it here - its body runs later, each time chat() is called.
32
print("Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'bye' to end.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Namaste! Ask me about timingโ€ฆ" on the screen
33
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
34
msg = input("You: ").strip()
โŒจ๏ธ Input Shows "You: ", reads the typed text, removes extra spaces (strip) and stores it in variable msg
35
if msg.lower() in ("bye", "exit", "quit"):
๐Ÿ”€ Decision CHECKS whether msg.lower() is present in ("bye", "exit", "quit"). If True, the indented lines below run; otherwise they are skipped
36
print("Bot: Thank you! Have a great day.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Thank you! Have a great day." on the screen
37
break
๐Ÿ” Loop BREAK - leaves the loop immediately
38
r = reply_to(msg)
๐Ÿงฎ Store / Calculate Calls our own function reply_to(msg); the result is stored in variable r
39
if r is None:
๐Ÿ”€ Decision CHECKS whether r is None. If True, the indented lines below run; otherwise Python jumps to the elif/else part
40
r = "Sorry, I can answer only school-related questions. I have noted your query for the office."
๐Ÿงฎ Store / Calculate Stores the text "Sorry, I can answer only school-related quesโ€ฆ in variable r
41
stats["unanswered"] += 1
๐Ÿงฎ Store / Calculate Adds 1 to stats["unanswered"] (same as stats["unanswered"] = stats["unanswered"] + 1)
42
with open("unanswered.txt", "a") as f:
๐Ÿ“ File Opens the file "unanswered.txt" in "a" mode - append (add at the end) and calls it f. "with" closes the file automatically when the block ends
43
f.write(msg + "\n")
๐Ÿ“ File Writes msg + "\n" into file f
44
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
45
stats["answered"] += 1
๐Ÿงฎ Store / Calculate Adds 1 to stats["answered"] (same as stats["answered"] = stats["answered"] + 1)
46
log.append((datetime(2026, 7, 1, 10, len(log)).strftime("%H:%M"), msg, r))
๐Ÿงฎ Store / Calculate Adds (datetime(2026, 7, 1, 10, len(log)).strftime(โ€ฆ at the end of list log
47
print("Bot:", r)
๐Ÿ–ฅ๏ธ Output Displays the text "Bot:", then the value of r on the screen
show_intents() - lines 50โ€“52
LineCodeWhat it does
50
def show_intents():
๐Ÿงฉ Function DEFINES a function show_intents(). Python only remembers it here - its body runs later, each time show_intents() is called.
51
for name, (keys, ans) in intents.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary intents; name, (keys, ans) get one pair each round
52
print(f"{name:<10} keys={keys}\n{'':<10} -> {ans}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name:<10} keys={keys}\n{'':<10} -> {ans}" with the values filled into { } on the screen
add_intent() - lines 55โ€“64
LineCodeWhat it does
55
def add_intent():
๐Ÿงฉ Function DEFINES a function add_intent(). Python only remembers it here - its body runs later, each time add_intent() is called.
56
if input("Admin password: ") != "kv@123":
๐Ÿ”€ Decision CHECKS whether input("Admin password: ") is not equal to "kv@123". If True, the indented lines below run; otherwise they are skipped
57
print("Access denied.")
๐Ÿ–ฅ๏ธ Output Displays the text "Access denied." on the screen
58
return
๐Ÿงฉ Function Ends the function and goes back to the caller
59
name = input("Intent name: ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable name
60
keys = [k.strip().lower() for k in input("Keywords (comma separated): ").split(",")]
โŒจ๏ธ Input Stores a new list made by a list comprehension [k.strip().lower() for k in input("Keywords (โ€ฆ in variable keys
61
ans = input("Reply: ").strip()
โŒจ๏ธ Input Shows "Reply: ", reads the typed text, removes extra spaces (strip) and stores it in variable ans
62
intents[name] = (keys, ans)
๐Ÿงฎ Store / Calculate Puts the tuple (keys, ans) into intents[name] (item name of intents)
63
hits[name] = 0
๐Ÿงฎ Store / Calculate Puts the number 0 into hits[name] (item name of hits)
64
print(f"Intent '{name}' added. The bot now knows {len(intents)} intents.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Intent '{name}' added. The bot now knows {lโ€ฆ with the values filled into { } on the screen
unanswered() - lines 67โ€“73
LineCodeWhat it does
67
def unanswered():
๐Ÿงฉ Function DEFINES a function unanswered(). Python only remembers it here - its body runs later, each time unanswered() is called.
68
if os.path.exists("unanswered.txt"):
๐Ÿ”€ Decision CHECKS whether os.path.exists("unanswered.txt") is True. If True, the indented lines below run; otherwise Python jumps to the elif/else part
69
with open("unanswered.txt") as f:
๐Ÿ“ File Opens the file "unanswered.txt" in "r" mode - read and calls it f. "with" closes the file automatically when the block ends
70
for i, line in enumerate(f, 1):
๐Ÿ” Loop LOOP over f with position: in each round i, line get (position, item)
71
print(f"{i}. {line.strip()}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{i}. {line.strip()}" with the values filled into { } on the screen
72
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
73
print("No unanswered questions.")
๐Ÿ–ฅ๏ธ Output Displays the text "No unanswered questions." on the screen
statistics() - lines 76โ€“86
LineCodeWhat it does
76
def statistics():
๐Ÿงฉ Function DEFINES a function statistics(). Python only remembers it here - its body runs later, each time statistics() is called.
77
tot = stats["answered"] + stats["unanswered"]
๐Ÿงฎ Store / Calculate Stores the value of stats["answered"] + stats["unanswered"] (calculated using +) in variable tot
78
print(f"Messages: {tot} | Answered: {stats['answered']} | Unanswered: {stats['unanswered']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Messages: {tot} | Answered: {stats['answereโ€ฆ with the values filled into { } on the screen
79
print(f"Answer rate: {stats['answered'] / tot * 100:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Answer rate: {stats['answered'] / tot * 100โ€ฆ with the values filled into { } on the screen
80
print("Intent usage:")
๐Ÿ–ฅ๏ธ Output Displays the text "Intent usage:" on the screen
81
for k, v in sorted(hits.items(), key=lambda x: -x[1]):
๐Ÿ” Loop LOOP: takes each item of sorted(hits.items(), key=lambda x: -x[1]) one-by-one into k, v and runs the indented block for it
82
if v:
๐Ÿ”€ Decision CHECKS whether v is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
83
print(f"  {k:<10} {'#' * v} {v}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {k:<10} {'#' * v} {v}" with the values filled into { } on the screen
84
print("Chat log (last 3):")
๐Ÿ–ฅ๏ธ Output Displays the text "Chat log (last 3):" on the screen
85
for t, m, r in log[-3:]:
๐Ÿ” Loop LOOP: takes each item of log[-3:] one-by-one into t, m, r and runs the indented block for it
86
print(f"  [{t}] {m}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" [{t}] {m}" with the values filled into { } on the screen
compare() - lines 89โ€“93
LineCodeWhat it does
89
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
90
print(f"{'Feature':<22}{'Script bot':<26}{'Smart bot'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Feature':<22}{'Script bot':<26}{'Smart boโ€ฆ with the values filled into { } on the screen
91
for a, b, c in [("Working", "Fixed rules / keywords", "AI + NLP models"), ("Learning", "No learning", "Learns from data"),
                ("Flexibility", "Lโ€ฆ
๐Ÿ” Loop LOOP: takes each item of [("Working", "Fixed rules / keywords", "AI + โ€ฆ one-by-one into a, b, c and runs the indented block for it
93
print(f"{a:<22}{b:<26}{c}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{a:<22}{b:<26}{c}" with the values filled into { } on the screen
Q1. What is a script bot?

A chatbot that follows fixed rules / scripts and replies only to known keywords.

Q2. Difference between script bot and smart bot?

Script bots use fixed rules; smart bots use AI / NLP to understand and learn.

Q3. Why save unanswered questions?

So the admin can add new intents and improve the bot.

Q4. What is an intent?

The purpose of a user's message, e.g. asking about fees.

Q5. Which domain of AI?

Natural Language Processing.

08

Rainfall and Temperature Explorer (SDG 13)

PYTHON + PANDASSDG 13 - Climate Actionread_csvdescribecorrelationmonsoon filteringtwin-axis bar + line chart
๐Ÿ“ 88 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 67 output lines๐Ÿ“„ 25+ page report

Reads monthly rainfall and temperature data from rainfall.csv, finds statistical measures, the monsoon contribution and the correlation between temperature and rainfall, and draws a combined bar-line chart.

โœจ Features
  • Monthly rainfall and temperature normals read from rainfall.csv
  • Descriptive statistics and wettest / driest / hottest months
  • Season-wise totals (Winter, Summer, Monsoon, Post-monsoon) using a mapping
  • Monsoon share and correlation between rainfall and temperature
  • What-if: rainfall deficit / excess scenario
  • Twin-axis chart, pie and season bar chart
โ˜ฐ Main menu
1Show DataCSV contents
2Statisticsdescribe()
3ExtremesWettest, driest, hottest, coolest
4Season SummarySeason totals
5CorrelationRain vs temperature
6What-if ScenarioMonsoon change %
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Read a CSV file and compute descriptive statistics
  • Measure the share of monsoon rainfall and correlation between features
  • Build a combined bar and line chart with two y-axes
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameMonth, Rainfall_mm, Avg_Temp_C
SEASONdictMonth -> season
monsoonfloatJun-Sep rainfall
Why it matters: Shows students how climate data is explored before any AI prediction model is built (data exploration stage).
# =====================================================================
#   RAINFALL AND TEMPERATURE EXPLORER   (SDG 13 : Climate Action)
# =====================================================================
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("rainfall.csv")
SEASON = {"Dec": "Winter", "Jan": "Winter", "Feb": "Winter", "Mar": "Summer", "Apr": "Summer", "May": "Summer",
          "Jun": "Monsoon", "Jul": "Monsoon", "Aug": "Monsoon", "Sep": "Monsoon", "Oct": "Post-monsoon", "Nov": "Post-monsoon"}
df["Season"] = df.Month.map(SEASON)


def show():
    print(df.to_string(index=False))


def stats():
    print(df[["Rainfall_mm", "Avg_Temp_C"]].describe().round(1))
    print("Annual rainfall:", df.Rainfall_mm.sum(), "mm")


def extremes():
    print("Wettest month :", df.loc[df.Rainfall_mm.idxmax(), "Month"], df.Rainfall_mm.max(), "mm")
    print("Driest month  :", df.loc[df.Rainfall_mm.idxmin(), "Month"], df.Rainfall_mm.min(), "mm")
    print("Hottest month :", df.loc[df.Avg_Temp_C.idxmax(), "Month"], df.Avg_Temp_C.max(), "C")
    print("Coolest month :", df.loc[df.Avg_Temp_C.idxmin(), "Month"], df.Avg_Temp_C.min(), "C")


def seasons():
    s = df.groupby("Season").agg(Rain=("Rainfall_mm", "sum"), Temp=("Avg_Temp_C", "mean")).round(1)
    s["Share_%"] = (s.Rain / s.Rain.sum() * 100).round(1)
    print(s.sort_values("Rain", ascending=False))


def correlation():
    r = df.Rainfall_mm.corr(df.Avg_Temp_C)
    print("Correlation (rain vs temp):", round(r, 3))
    print("Interpretation:", "positive - rain falls in the warm months" if r > 0.3 else "weak / negative relation")


def what_if():
    ch = float(input("Change in monsoon rainfall (%): "))
    new = df.Rainfall_mm.where(df.Season != "Monsoon", df.Rainfall_mm * (1 + ch / 100))
    print(f"Annual rainfall: {df.Rainfall_mm.sum():.0f} mm -> {new.sum():.0f} mm")
    print("Status:", "DEFICIENT year (drought risk)" if ch <= -20 else "EXCESS year (flood risk)" if ch >= 20 else "Normal range")


def charts():
    fig, ax1 = plt.subplots(figsize=(8, 4))
    ax1.bar(df.Month, df.Rainfall_mm, color="steelblue", label="Rainfall (mm)"); ax1.set_ylabel("Rainfall (mm)")
    ax2 = ax1.twinx()
    ax2.plot(df.Month, df.Avg_Temp_C, color="orangered", marker="o", label="Avg temp (C)"); ax2.set_ylabel("Temperature (C)")
    plt.title("Monthly rainfall and temperature - Delhi (sample normals)")
    fig.legend(loc="upper left", bbox_to_anchor=(0.1, 0.9))
    plt.savefig("rain_temp.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.pie(df.Rainfall_mm, labels=df.Month, autopct=lambda p: f"{p:.0f}%" if p > 4 else "", startangle=90)
    plt.title("Share of annual rainfall by month"); plt.savefig("monthly_rain_pie.png", dpi=90, bbox_inches="tight"); plt.show()
    df.groupby("Season").Rainfall_mm.sum().sort_values().plot(kind="barh", color="#4dabf7", title="Season-wise rainfall (mm)")
    plt.savefig("season_bar.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: rain_temp.png, monthly_rain_pie.png, season_bar.png")


print("=" * 55)
print("   RAINFALL & TEMPERATURE EXPLORER  (SDG 13)")
print("=" * 55)
while True:
    print("\n1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Act on climate!")
        break
    elif ch == "1":
        show()
    elif ch == "2":
        stats()
    elif ch == "3":
        extremes()
    elif ch == "4":
        seasons()
    elif ch == "5":
        correlation()
    elif ch == "6":
        what_if()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. read_csv('rainfall.csv')
  3. Show menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. Compute statistics / groupby
  6. Show result / chart
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Show data12 monthsPASS
2ExtremesWettest Jul/AugPASS
3Season summaryMonsoon highestPASS
4CorrelationValue -1 to 1PASS
5What-if -20 %New annual totalPASS
6Charts3 PNG filesPASS
โš  Limitations
  • Monthly normals only
  • One city
  • No year-to-year data
  • Correlation is not causation
๐Ÿš€ Future scope
  • IMD year-wise data for trend
  • Predict monsoon with regression
  • Compare cities
  • Link to crop advice

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: df, SEASON.
  3. 7 functions are defined (lines 13โ€“60) - Python stores them but does NOT run them yet.
  4. Main program starts at line 10: df["Season"] = df.Month.map(SEASON) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
show()13โ€“14Showmain program
stats()17โ€“19Statsmain program
extremes()22โ€“26Extremesmain program
seasons()29โ€“32Seasonsmain program
correlation()35โ€“38Correlationmain program
what_if()41โ€“45What ifmain program
charts()48โ€“60Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
10
df["Season"] = df.Month.map(SEASON)
๐Ÿ“ฆ Library / Data Applies SEASON to every item of ; the result is put into df["Season"] (item "Season" of df)
63
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
64
print("   RAINFALL & TEMPERATURE EXPLORER  (SDG 13)")
๐Ÿ–ฅ๏ธ Output Displays the text "RAINFALL & TEMPERATURE EXPLORER (โ€ฆ" on the screen
65
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
66
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
67
print("\n1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Statistics 3.Extremes 4.โ€ฆ" on the screen
68
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
69
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
70
print("Act on climate!")
๐Ÿ–ฅ๏ธ Output Displays the text "Act on climate!" on the screen
71
break
๐Ÿ” Loop BREAK - leaves the loop immediately
72
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
73
show()
๐Ÿงฎ Store / Calculate Calls our own function show()
74
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
75
stats()
๐Ÿงฎ Store / Calculate Calls our own function stats()
76
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
77
extremes()
๐Ÿงฎ Store / Calculate Calls our own function extremes()
78
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
79
seasons()
๐Ÿงฎ Store / Calculate Calls our own function seasons()
80
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
81
correlation()
๐Ÿงฎ Store / Calculate Calls our own function correlation()
82
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
83
what_if()
๐Ÿงฎ Store / Calculate Calls our own function what_if()
84
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
85
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
86
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
87
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: RAINFALL & TEMPERATURE EXPLORER (SDG 13) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show()
    shows: Month Rainfall_mm Avg_Temp_C Season (+13 more lines)
  3. You type 2 at Enter choice:
    runs: stats()
    shows: Rainfall_mm Avg_Temp_C (+10 more lines)
  4. You type 3 at Enter choice:
    runs: extremes()
    shows: Wettest month : Aug 233 mm (+4 more lines)
  5. You type 4 at Enter choice:
    runs: seasons()
    shows: Rain Temp Share_% (+6 more lines)
  6. You type 5 at Enter choice:
    runs: correlation()
    shows: Correlation (rain vs temp): 0.507 (+2 more lines)
  7. You type 6 at Enter choice:
    runs: what_if()
  8. You type -20 at Change in monsoon rainfall (%):
    shows: Annual rainfall: 756 mm -> 629 mm (+2 more lines)
  9. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  10. You type 0 at Enter choice:
    shows: Act on climate!
โ‘ค Inside each function - line by line
show() - lines 13โ€“14
LineCodeWhat it does
13
def show():
๐Ÿงฉ Function DEFINES a function show(). Python only remembers it here - its body runs later, each time show() is called.
14
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
stats() - lines 17โ€“19
LineCodeWhat it does
17
def stats():
๐Ÿงฉ Function DEFINES a function stats(). Python only remembers it here - its body runs later, each time stats() is called.
18
print(df[["Rainfall_mm", "Avg_Temp_C"]].describe().round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of df[["Rainfall_mm", "Avg_Temp_C"]].describe().โ€ฆ on the screen
19
print("Annual rainfall:", df.Rainfall_mm.sum(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Annual rainfall:", then the value of df.Rainfall_mm.sum(), then the text "mm" on the screen
extremes() - lines 22โ€“26
LineCodeWhat it does
22
def extremes():
๐Ÿงฉ Function DEFINES a function extremes(). Python only remembers it here - its body runs later, each time extremes() is called.
23
print("Wettest month :", df.loc[df.Rainfall_mm.idxmax(), "Month"], df.Rainfall_mm.max(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Wettest month :", then the value of df.loc[df.Rainfall_mm.idxmax(), "Month"], then the value of df.Rainfall_mm.max(), then the text "mm" on the screen
24
print("Driest month  :", df.loc[df.Rainfall_mm.idxmin(), "Month"], df.Rainfall_mm.min(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Driest month :", then the value of df.loc[df.Rainfall_mm.idxmin(), "Month"], then the value of df.Rainfall_mm.min(), then the text "mm" on the screen
25
print("Hottest month :", df.loc[df.Avg_Temp_C.idxmax(), "Month"], df.Avg_Temp_C.max(), "C")
๐Ÿ–ฅ๏ธ Output Displays the text "Hottest month :", then the value of df.loc[df.Avg_Temp_C.idxmax(), "Month"], then the value of df.Avg_Temp_C.max(), then the text "C" on the screen
26
print("Coolest month :", df.loc[df.Avg_Temp_C.idxmin(), "Month"], df.Avg_Temp_C.min(), "C")
๐Ÿ–ฅ๏ธ Output Displays the text "Coolest month :", then the value of df.loc[df.Avg_Temp_C.idxmin(), "Month"], then the value of df.Avg_Temp_C.min(), then the text "C" on the screen
seasons() - lines 29โ€“32
LineCodeWhat it does
29
def seasons():
๐Ÿงฉ Function DEFINES a function seasons(). Python only remembers it here - its body runs later, each time seasons() is called.
30
s = df.groupby("Season").agg(Rain=("Rainfall_mm", "sum"), Temp=("Avg_Temp_C", "mean")).round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby("Season").agg(Rain=("Rainfall_mm",โ€ฆ to 1 decimal places; the result is stored in variable s
31
s["Share_%"] = (s.Rain / s.Rain.sum() * 100).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of s.Rain / s.Rain.sum() * 100 to 1 decimal places; the result is put into s["Share_%"] (item "Share_%" of s)
32
print(s.sort_values("Rain", ascending=False))
๐Ÿ–ฅ๏ธ Output Displays the value of s.sort_values("Rain", ascending=False) on the screen
correlation() - lines 35โ€“38
LineCodeWhat it does
35
def correlation():
๐Ÿงฉ Function DEFINES a function correlation(). Python only remembers it here - its body runs later, each time correlation() is called.
36
r = df.Rainfall_mm.corr(df.Avg_Temp_C)
๐Ÿ“ฆ Library / Data Finds the correlation between df.Rainfall_mm columns; the result is stored in variable r
37
print("Correlation (rain vs temp):", round(r, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Correlation (rain vs temp):", then the value of round(r, 3) on the screen
38
print("Interpretation:", "positive - rain falls in the warm months" if r > 0.3 else "weak / negative relation")
๐Ÿ–ฅ๏ธ Output Displays the text "Interpretation:", then the value of "positive - rain falls in the warm months" ifโ€ฆ on the screen
what_if() - lines 41โ€“45
LineCodeWhat it does
41
def what_if():
๐Ÿงฉ Function DEFINES a function what_if(). Python only remembers it here - its body runs later, each time what_if() is called.
42
ch = float(input("Change in monsoon rainfall (%): "))
โŒจ๏ธ Input Shows "Change in monsoon rainfall (%): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable ch
43
new = df.Rainfall_mm.where(df.Season != "Monsoon", df.Rainfall_mm * (1 + ch / 100))
๐Ÿ“ฆ Library / Data Chooses values depending on condition df.Season != "Monsoon"; the result is stored in variable new
44
print(f"Annual rainfall: {df.Rainfall_mm.sum():.0f} mm -> {new.sum():.0f} mm")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Annual rainfall: {df.Rainfall_mm.sum():.0f}โ€ฆ with the values filled into { } on the screen
45
print("Status:", "DEFICIENT year (drought risk)" if ch <= -20 else "EXCESS year (flood risk)" if ch >= 20 else "Normal range")
๐Ÿ–ฅ๏ธ Output Displays the text "Status:", then the value of "DEFICIENT year (drought risk)" if ch <= -20 โ€ฆ on the screen
charts() - lines 48โ€“60
LineCodeWhat it does
48
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
49
fig, ax1 = plt.subplots(figsize=(8, 4))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax1
50
ax1.bar(df.Month, df.Rainfall_mm, color="steelblue", label="Rainfall (mm)"); ax1.set_ylabel("Rainfall (mm)")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of df.Month, df.Rainfall_mm
50
ax1.bar(df.Month, df.Rainfall_mm, color="steelblue", label="Rainfall (mm)"); ax1.set_ylabel("Rainfall (mm)")
๐Ÿ–ฅ๏ธ Output Sets the Y-axis label
51
ax2 = ax1.twinx()
๐Ÿงฎ Store / Calculate Adds a second Y-axis; the result is stored in variable ax2
52
ax2.plot(df.Month, df.Avg_Temp_C, color="orangered", marker="o", label="Avg temp (C)"); ax2.set_ylabel("Temperature (C)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Month, df.Avg_Temp_C
52
ax2.plot(df.Month, df.Avg_Temp_C, color="orangered", marker="o", label="Avg temp (C)"); ax2.set_ylabel("Temperature (C)")
๐Ÿ–ฅ๏ธ Output Sets the Y-axis label
53
plt.title("Monthly rainfall and temperature - Delhi (sample normals)")
๐Ÿ–ฅ๏ธ Output Writes "Monthly rainfall and temperature - Delhi (saโ€ฆ as the title of the chart
54
fig.legend(loc="upper left", bbox_to_anchor=(0.1, 0.9))
๐Ÿงฎ Store / Calculate Shows the legend (which colour means what)
55
plt.savefig("rain_temp.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "rain_temp.png"
55
plt.savefig("rain_temp.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
56
plt.pie(df.Rainfall_mm, labels=df.Month, autopct=lambda p: f"{p:.0f}%" if p > 4 else "", startangle=90)
๐Ÿ–ฅ๏ธ Output Draws a pie chart of df.Rainfall_mm
57
plt.title("Share of annual rainfall by month"); plt.savefig("monthly_rain_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Share of annual rainfall by month" as the title of the chart
57
plt.title("Share of annual rainfall by month"); plt.savefig("monthly_rain_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "monthly_rain_pie.png"
57
plt.title("Share of annual rainfall by month"); plt.savefig("monthly_rain_pie.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
58
df.groupby("Season").Rainfall_mm.sum().sort_values().plot(kind="barh", color="#4dabf7", title="Season-wise rainfall (mm)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
59
plt.savefig("season_bar.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "season_bar.png"
59
plt.savefig("season_bar.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
60
print("Charts saved: rain_temp.png, monthly_rain_pie.png, season_bar.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: rain_temp.png, montโ€ฆ" on the screen
Q1. What is correlation?

A number from -1 to +1 showing how two variables move together.

Q2. What is a twin-axis chart?

A chart with two y-axes (rainfall and temperature) sharing the same x-axis.

Q3. Which months are monsoon in India?

June to September (south-west monsoon).

Q4. How is the season total found?

Map each month to a season and use groupby('Season').sum().

Q5. Which SDG?

SDG 13 - Climate Action.

09

Smart Waste Bin Fill-Level Monitor (SDG 11)

PYTHON + PANDASSDG 11 - Sustainable Cities and CommunitiesPandas DataFrame from sensor readingsconditional filteringsortinggroupbybar chart with threshold
๐Ÿ“ 108 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 103 output lines๐Ÿ“„ 25+ page report

Simulates ultrasonic fill-level sensor data from smart dustbins across a colony, identifies bins that are more than 80 % full, creates an optimised pickup list sorted by urgency and plots fill levels zone-wise.

โœจ Features
  • Fill level (%) of 10 smart bins in 3 zones, as sent by ultrasonic sensors
  • Status OK / HALF / FULL with pd.cut; pickup alert for bins >= 80 %
  • Optimised pickup route sorted by fill level and trips saved
  • Fill-rate per hour and time until a bin becomes full (prediction)
  • Update a sensor reading; zone-wise summary
  • Bar, zone and forecast charts
โ˜ฐ Main menu
1Bin StatusAll bins with status
2Pickup Alert & RouteFULL bins and route
3Zone SummaryAverage fill by zone
4Predict Full TimeHours until 100 %
5Update SensorNew fill value for a bin
6Empty a BinSet fill to 0 after pickup
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Represent sensor data in a Pandas DataFrame
  • Filter and sort data to create a priority pickup list
  • Summarise zone-wise status and visualise it
๐Ÿ“š Data dictionary
NameTypePurpose
binsDataFrameBin, Zone, Fill, Hours_since_pickup
RatecolumnFill % per hour
Statuscolumnpd.cut OK / HALF / FULL
THRESHOLDint80 % pickup level
Why it matters: Demonstrates how IoT data plus simple analytics can save fuel and keep cities clean.
# =====================================================================
#   SMART WASTE BIN FILL-LEVEL MONITOR   (SDG 11)
# =====================================================================
import pandas as pd
import matplotlib.pyplot as plt

THRESHOLD = 80
bins = pd.DataFrame({
    "Bin":  ["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B09", "B10"],
    "Zone": ["A", "A", "A", "B", "B", "B", "C", "C", "C", "C"],
    "Fill": [92, 35, 81, 67, 88, 22, 95, 54, 40, 79],
    "Hours_since_pickup": [30, 8, 26, 20, 28, 6, 34, 18, 12, 24]})


def refresh():
    bins["Status"] = pd.cut(bins.Fill, [-1, 39, 79, 100], labels=["OK", "HALF", "FULL"])
    bins["Rate"] = (bins.Fill / bins.Hours_since_pickup.clip(lower=1)).round(2)


def status():
    print(bins.to_string(index=False))


def pickup():
    p = bins[bins.Fill >= THRESHOLD].sort_values("Fill", ascending=False)
    print(f"ALERT: bins to empty today (fill >= {THRESHOLD} %):")
    print(p[["Bin", "Zone", "Fill"]].to_string(index=False))
    print("Pickup route: Depot -> " + " -> ".join(p.Bin) + " -> Depot")
    print("Trips saved today:", len(bins) - len(p), "of", len(bins), f"({(len(bins) - len(p)) / len(bins) * 100:.0f} % fuel saving)")


def zones():
    z = bins.groupby("Zone").agg(Bins=("Bin", "count"), Avg_Fill=("Fill", "mean"), Full=("Fill", lambda s: (s >= THRESHOLD).sum()))
    print(z.round(1))
    print("Most loaded zone:", z.Avg_Fill.idxmax())


def predict():
    t = ((100 - bins.Fill) / bins.Rate).round(1)
    out = pd.DataFrame({"Bin": bins.Bin, "Fill": bins.Fill, "Rate_%/h": bins.Rate, "Hours_to_full": t})
    print(out.sort_values("Hours_to_full").to_string(index=False))
    print("Bins that will be full within 6 hours:", out[out.Hours_to_full <= 6].Bin.tolist())


def update():
    b = input("Bin id: ").strip().upper()
    f = int(input("New fill %: "))
    if not 0 <= f <= 100:
        print("Fill must be 0-100.")
        return
    if b not in bins.Bin.values:
        print("No such bin.")
        return
    bins.loc[bins.Bin == b, "Fill"] = f
    refresh()
    print(b, "updated ->", bins.loc[bins.Bin == b, "Status"].iloc[0])


def empty():
    b = input("Bin emptied: ").strip().upper()
    bins.loc[bins.Bin == b, ["Fill", "Hours_since_pickup"]] = [0, 0]
    refresh()
    print(b, "emptied. Status OK.")


def charts():
    colors = ["red" if f >= 80 else "orange" if f >= 40 else "green" for f in bins.Fill]
    plt.bar(bins.Bin, bins.Fill, color=colors)
    plt.axhline(THRESHOLD, color="black", linestyle="--", label="Pickup threshold 80 %")
    plt.ylabel("Fill level (%)"); plt.title("Smart bin fill levels"); plt.legend()
    plt.savefig("bin_levels.png", dpi=90, bbox_inches="tight"); plt.show()
    bins.groupby("Zone").Fill.mean().plot(kind="bar", color=["#748ffc", "#63e6be", "#ffa94d"], title="Average fill by zone")
    plt.ylabel("%"); plt.xticks(rotation=0); plt.savefig("zone_fill.png", dpi=90, bbox_inches="tight"); plt.show()
    hrs = range(0, 13)
    for _, r in bins.nlargest(4, "Rate").iterrows():
        plt.plot(hrs, [min(100, r.Fill + r.Rate * h) for h in hrs], marker=".", label=r.Bin)
    plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
    plt.savefig("fill_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: bin_levels.png, zone_fill.png, fill_forecast.png")


refresh()
print("=" * 55)
print("   SMART BIN MONITOR  (SDG 11)")
print("=" * 55)
while True:
    print("\n1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Clean city, green city!")
        break
    elif ch == "1":
        status()
    elif ch == "2":
        pickup()
    elif ch == "3":
        zones()
    elif ch == "4":
        predict()
    elif ch == "5":
        update()
    elif ch == "6":
        empty()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create bin DataFrame
  3. Show menu and read choice
  4. Choice is Update? → No: run report
  5. Read bin and fill
  6. 0 <= fill <= 100? → No: error
  7. Update and recompute status
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Status10 binsPASS
2PickupB07, B01, B05, B03 routePASS
3Zone summaryZone A highestPASS
4PredictHours to fullPASS
5Update B02 = 85B02 becomes FULLPASS
6Update 120'Fill must be 0-100'PASS
7Empty B07Fill 0, OKPASS
โš  Limitations
  • Sensor values typed / simulated
  • Straight-line fill-rate assumption
  • Route ignores road distance
  • No GPS
๐Ÿš€ Future scope
  • Real IoT sensors with ESP32
  • Map-based shortest route
  • Predict festival-day waste
  • Citizen complaint app

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: THRESHOLD, bins.
  3. 8 functions are defined (lines 15โ€“79) - Python stores them but does NOT run them yet.
  4. Main program starts at line 82: refresh() - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
refresh()15โ€“17Refreshupdate(), empty(), main program
status()20โ€“21Statusmain program
pickup()24โ€“29Pickupmain program
zones()32โ€“35Zonesmain program
predict()38โ€“42Predictmain program
update()45โ€“56Updatemain program
empty()59โ€“63Emptymain program
charts()66โ€“79Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
82
refresh()
๐Ÿงฎ Store / Calculate Calls our own function refresh()
83
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
84
print("   SMART BIN MONITOR  (SDG 11)")
๐Ÿ–ฅ๏ธ Output Displays the text "SMART BIN MONITOR (SDG 11)" on the screen
85
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
86
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
87
print("\n1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Status 2.Pickup 3.Zones 4.Prediโ€ฆ" on the screen
88
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
89
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
90
print("Clean city, green city!")
๐Ÿ–ฅ๏ธ Output Displays the text "Clean city, green city!" on the screen
91
break
๐Ÿ” Loop BREAK - leaves the loop immediately
92
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
93
status()
๐Ÿงฎ Store / Calculate Calls our own function status()
94
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
95
pickup()
๐Ÿงฎ Store / Calculate Calls our own function pickup()
96
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
97
zones()
๐Ÿงฎ Store / Calculate Calls our own function zones()
98
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
99
predict()
๐Ÿงฎ Store / Calculate Calls our own function predict()
100
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
101
update()
๐Ÿงฎ Store / Calculate Calls our own function update()
102
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
103
empty()
๐Ÿงฎ Store / Calculate Calls our own function empty()
104
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
105
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
106
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
107
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    runs: refresh()
    shows: SMART BIN MONITOR (SDG 11) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: status()
    shows: Bin Zone Fill Hours_since_pickup Status Rate (+11 more lines)
  3. You type 2 at Enter choice:
    runs: pickup()
    shows: ALERT: bins to empty today (fill >= 80 %): (+8 more lines)
  4. You type 3 at Enter choice:
    runs: zones()
    shows: Bins Avg_Fill Full (+6 more lines)
  5. You type 4 at Enter choice:
    runs: predict()
    shows: Bin Fill Rate_%/h Hours_to_full (+12 more lines)
  6. You type 5 at Enter choice:
    runs: update()
  7. You type B02 at Bin id:
  8. You type 85 at New fill %:
    runs: refresh()
    shows: B02 updated -> FULL (+1 more lines)
  9. You type 5 at Enter choice:
    runs: update()
  10. You type B03 at Bin id:
  11. You type 120 at New fill %:
    shows: Fill must be 0-100. (+1 more lines)
  12. You type 2 at Enter choice:
    runs: pickup()
    shows: ALERT: bins to empty today (fill >= 80 %): (+9 more lines)
  13. You type 6 at Enter choice:
    runs: empty()
  14. You type B07 at Bin emptied:
    runs: refresh()
    shows: B07 emptied. Status OK. (+1 more lines)
  15. You type 1 at Enter choice:
    runs: status()
    shows: Bin Zone Fill Hours_since_pickup Status Rate (+11 more lines)
  16. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  17. You type 0 at Enter choice:
    shows: Clean city, green city!
โ‘ค Inside each function - line by line
refresh() - lines 15โ€“17
LineCodeWhat it does
15
def refresh():
๐Ÿงฉ Function DEFINES a function refresh(). Python only remembers it here - its body runs later, each time refresh() is called.
16
bins["Status"] = pd.cut(bins.Fill, [-1, 39, 79, 100], labels=["OK", "HALF", "FULL"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into bins["Status"] (item "Status" of bins)
17
bins["Rate"] = (bins.Fill / bins.Hours_since_pickup.clip(lower=1)).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of bins.Fill / bins.Hours_since_pickup.clip(loweโ€ฆ to 2 decimal places; the result is put into bins["Rate"] (item "Rate" of bins)
status() - lines 20โ€“21
LineCodeWhat it does
20
def status():
๐Ÿงฉ Function DEFINES a function status(). Python only remembers it here - its body runs later, each time status() is called.
21
print(bins.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of bins.to_string(index=False) on the screen
pickup() - lines 24โ€“29
LineCodeWhat it does
24
def pickup():
๐Ÿงฉ Function DEFINES a function pickup(). Python only remembers it here - its body runs later, each time pickup() is called.
25
p = bins[bins.Fill >= THRESHOLD].sort_values("Fill", ascending=False)
๐Ÿงฎ Store / Calculate Sorts bins[bins.Fill >= THRESHOLD] by "Fill" in descending order; the result is stored in variable p
26
print(f"ALERT: bins to empty today (fill >= {THRESHOLD} %):")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"ALERT: bins to empty today (fill >= {THRESHโ€ฆ with the values filled into { } on the screen
27
print(p[["Bin", "Zone", "Fill"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of p[["Bin", "Zone", "Fill"]].to_string(index=Faโ€ฆ on the screen
28
print("Pickup route: Depot -> " + " -> ".join(p.Bin) + " -> Depot")
๐Ÿ–ฅ๏ธ Output Displays the value of "Pickup route: Depot -> " + " -> ".join(p.Binโ€ฆ on the screen
29
print("Trips saved today:", len(bins) - len(p), "of", len(bins), f"({(len(bins) - len(p)) / len(bins) * 100:.0f} % fuel saving)")
๐Ÿ–ฅ๏ธ Output Displays the text "Trips saved today:", then the value of len(bins) - len(p), then the text "of", then the value of len(bins), then the f-string f"({(len(bins) - len(p)) / len(bins) * 100:.0โ€ฆ with the values filled into { } on the screen
zones() - lines 32โ€“35
LineCodeWhat it does
32
def zones():
๐Ÿงฉ Function DEFINES a function zones(). Python only remembers it here - its body runs later, each time zones() is called.
33
z = bins.groupby("Zone").agg(Bins=("Bin", "count"), Avg_Fill=("Fill", "mean"), Full=("Fill", lambda s: (s >= THRESHOLD).sum()))
๐Ÿงฎ Store / Calculate Calculates the given summary values for every group; the result is stored in variable z
34
print(z.round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of z.round(1) on the screen
35
print("Most loaded zone:", z.Avg_Fill.idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Most loaded zone:", then the value of z.Avg_Fill.idxmax() on the screen
predict() - lines 38โ€“42
LineCodeWhat it does
38
def predict():
๐Ÿงฉ Function DEFINES a function predict(). Python only remembers it here - its body runs later, each time predict() is called.
39
t = ((100 - bins.Fill) / bins.Rate).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of (100 - bins.Fill) / bins.Rate to 1 decimal places; the result is stored in variable t
40
out = pd.DataFrame({"Bin": bins.Bin, "Fill": bins.Fill, "Rate_%/h": bins.Rate, "Hours_to_full": t})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Bin": bins.Bin, "Fill": bins.Fill, "Rate_%/โ€ฆ; the result is stored in variable out
41
print(out.sort_values("Hours_to_full").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of out.sort_values("Hours_to_full").to_string(inโ€ฆ on the screen
42
print("Bins that will be full within 6 hours:", out[out.Hours_to_full <= 6].Bin.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Bins that will be full within 6 hโ€ฆ", then the value of out[out.Hours_to_full <= 6].Bin.tolist() on the screen
update() - lines 45โ€“56
LineCodeWhat it does
45
def update():
๐Ÿงฉ Function DEFINES a function update(). Python only remembers it here - its body runs later, each time update() is called.
46
b = input("Bin id: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable b
47
f = int(input("New fill %: "))
โŒจ๏ธ Input Shows "New fill %: ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable f
48
if not 0 <= f <= 100:
๐Ÿ”€ Decision CHECKS whether NOT 0 <= f <= 100 is True. If True, the indented lines below run; otherwise they are skipped
49
print("Fill must be 0-100.")
๐Ÿ–ฅ๏ธ Output Displays the text "Fill must be 0-100." on the screen
50
return
๐Ÿงฉ Function Ends the function and goes back to the caller
51
if b not in bins.Bin.values:
๐Ÿ”€ Decision CHECKS whether b is not present in bins.Bin.values. If True, the indented lines below run; otherwise they are skipped
52
print("No such bin.")
๐Ÿ–ฅ๏ธ Output Displays the text "No such bin." on the screen
53
return
๐Ÿงฉ Function Ends the function and goes back to the caller
54
bins.loc[bins.Bin == b, "Fill"] = f
๐Ÿงฎ Store / Calculate Puts the value of f into bins.loc[bins.Bin == b, "Fill"] (item bins.Bin == b, "Fill" of bins.loc)
55
refresh()
๐Ÿงฎ Store / Calculate Calls our own function refresh()
56
print(b, "updated ->", bins.loc[bins.Bin == b, "Status"].iloc[0])
๐Ÿ–ฅ๏ธ Output Displays the value of b, then the text "updated ->", then the value of bins.loc[bins.Bin == b, "Status"].iloc[0] on the screen
empty() - lines 59โ€“63
LineCodeWhat it does
59
def empty():
๐Ÿงฉ Function DEFINES a function empty(). Python only remembers it here - its body runs later, each time empty() is called.
60
b = input("Bin emptied: ").strip().upper()
โŒจ๏ธ Input Reads the typed text, changes its case with .upper() and stores it in variable b
61
bins.loc[bins.Bin == b, ["Fill", "Hours_since_pickup"]] = [0, 0]
๐Ÿงฎ Store / Calculate Puts a list [0, 0] into bins.loc[bins.Bin == b, ["Fill", "Hours_sinceโ€ฆ (item bins.Bin == b, ["Fill", "Hours_since_pickup"] of bins.loc)
62
refresh()
๐Ÿงฎ Store / Calculate Calls our own function refresh()
63
print(b, "emptied. Status OK.")
๐Ÿ–ฅ๏ธ Output Displays the value of b, then the text "emptied. Status OK." on the screen
charts() - lines 66โ€“79
LineCodeWhat it does
66
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
67
colors = ["red" if f >= 80 else "orange" if f >= 40 else "green" for f in bins.Fill]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension ["red" if f >= 80 else "orange" if f >= 40 elโ€ฆ in variable colors
68
plt.bar(bins.Bin, bins.Fill, color=colors)
๐Ÿ–ฅ๏ธ Output Draws a bar chart of bins.Bin, bins.Fill
69
plt.axhline(THRESHOLD, color="black", linestyle="--", label="Pickup threshold 80 %")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
70
plt.ylabel("Fill level (%)"); plt.title("Smart bin fill levels"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Fill level (%)" as the label of the Y-axis
70
plt.ylabel("Fill level (%)"); plt.title("Smart bin fill levels"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Smart bin fill levels" as the title of the chart
70
plt.ylabel("Fill level (%)"); plt.title("Smart bin fill levels"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
71
plt.savefig("bin_levels.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "bin_levels.png"
71
plt.savefig("bin_levels.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
72
bins.groupby("Zone").Fill.mean().plot(kind="bar", color=["#748ffc", "#63e6be", "#ffa94d"], title="Average fill by zone")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
73
plt.ylabel("%"); plt.xticks(rotation=0); plt.savefig("zone_fill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "%" as the label of the Y-axis
73
plt.ylabel("%"); plt.xticks(rotation=0); plt.savefig("zone_fill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
73
plt.ylabel("%"); plt.xticks(rotation=0); plt.savefig("zone_fill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "zone_fill.png"
73
plt.ylabel("%"); plt.xticks(rotation=0); plt.savefig("zone_fill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
74
hrs = range(0, 13)
๐Ÿงฎ Store / Calculate Gives the numbers 0 to 12; the result is stored in variable hrs
75
for _, r in bins.nlargest(4, "Rate").iterrows():
๐Ÿ” Loop LOOP over each row of bins.nlargest(4, "Rate"); _, r get (index, row)
76
plt.plot(hrs, [min(100, r.Fill + r.Rate * h) for h in hrs], marker=".", label=r.Bin)
๐Ÿ–ฅ๏ธ Output Draws a line chart of hrs, [min(100, r.Fill + r.Rate * h) for h in hrs]
77
plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
77
plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Hours from now" as the label of the X-axis
77
plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Fill %" as the label of the Y-axis
77
plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Fill forecast (fastest bins)" as the title of the chart
77
plt.axhline(100, color="red", ls=":"); plt.xlabel("Hours from now"); plt.ylabel("Fill %"); plt.title("Fill forecast (fastest bins)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
78
plt.savefig("fill_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "fill_forecast.png"
78
plt.savefig("fill_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
79
print("Charts saved: bin_levels.png, zone_fill.png, fill_forecast.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: bin_levels.png, zonโ€ฆ" on the screen
Q1. How do smart bins measure fill level?

An ultrasonic sensor measures distance from lid to waste; less distance = more filled.

Q2. What is pd.cut used for?

Converting fill % into categories OK / HALF / FULL.

Q3. How is time-to-full predicted?

(100 - fill) / fill rate per hour.

Q4. How does this save fuel?

Trucks visit only FULL bins instead of all bins.

Q5. Which SDG?

SDG 11 - Sustainable Cities and Communities.

10

Crop Yield Data Insights (SDG 2)

PYTHON + PANDASSDG 2 - Zero HungerDataFramegroupbyaggregate functionspercentage changemode
๐Ÿ“ 110 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 113 output lines๐Ÿ“„ 25+ page report

Analyses sample yield data (quintal per hectare) of wheat and rice for five states over three years, finds the best-performing state, the year-on-year growth and the crop with the highest average yield, and plots a grouped bar chart.

โœจ Features
  • Yield (quintal / hectare) of wheat and rice for 5 states over 3 years built into a DataFrame
  • Average yield by crop and by state (groupby + unstack)
  • Growth 2022 -> 2024 and fastest-growing state
  • Simple trend forecast for 2025 using average yearly increase
  • Search a state; compare with national (sample) average
  • Bar, line and heat-map charts
โ˜ฐ Main menu
1Show DataLong table
2Average YieldsBy crop and state
3Growth Analysis% growth 2022-2024
4Forecast 2025Trend-based
5State ReportOne state's details
6Above Average StatesFilter
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Aggregate data using groupby with mean and max
  • Calculate percentage growth between years
  • Present insights using a grouped bar chart
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameState, Crop, Year, Yield
avgDataFrameState x Crop average
growthDataFrame% growth
fcDataFrame2025 forecast
Why it matters: Trains students to draw insights from agricultural data - the basis of AI advisory systems for farmers.
# =====================================================================
#   CROP YIELD DATA INSIGHTS   (SDG 2 : Zero Hunger) - sample data
# =====================================================================
import pandas as pd
import matplotlib.pyplot as plt

data = {"Punjab":  {"Wheat": [48.2, 49.0, 50.1], "Rice": [41.5, 42.3, 43.0]},
        "Haryana": {"Wheat": [46.0, 46.8, 47.9], "Rice": [32.4, 33.0, 34.1]},
        "UP":      {"Wheat": [34.1, 35.0, 35.6], "Rice": [26.2, 27.0, 27.4]},
        "MP":      {"Wheat": [33.0, 34.2, 35.5], "Rice": [22.8, 23.5, 24.6]},
        "Bihar":   {"Wheat": [28.9, 29.4, 30.2], "Rice": [24.1, 24.6, 25.0]}}
rows = []
for state, crops in data.items():
    for crop, ylds in crops.items():
        for year, y in zip([2022, 2023, 2024], ylds):
            rows.append([state, crop, year, y])
df = pd.DataFrame(rows, columns=["State", "Crop", "Year", "Yield"])
avg = df.groupby(["State", "Crop"]).Yield.mean().unstack().round(2)
first = df[df.Year == 2022].set_index(["State", "Crop"]).Yield
last = df[df.Year == 2024].set_index(["State", "Crop"]).Yield
growth = ((last - first) / first * 100).round(2).unstack()


def show():
    print(df.to_string(index=False))
    print("Records:", len(df))


def averages():
    print("Average yield by crop:\n" + df.groupby("Crop").Yield.mean().round(2).to_string())
    print("\nAverage yield by state:\n", avg)
    print("\nBest state - Wheat:", avg.Wheat.idxmax(), "| Rice:", avg.Rice.idxmax())


def growth_rep():
    print("Growth 2022 -> 2024 (%):\n", growth)
    print("Fastest growing - Wheat:", growth.Wheat.idxmax(), "| Rice:", growth.Rice.idxmax())


def forecast():
    p = df.pivot_table(index=["State", "Crop"], columns="Year", values="Yield")
    p["Avg_increase"] = ((p[2024] - p[2022]) / 2).round(2)
    p["Forecast_2025"] = (p[2024] + p["Avg_increase"]).round(1)
    print(p)


def state_report():
    s = input("State: ").strip()
    r = df[df.State.str.lower() == s.lower()]
    if r.empty:
        print("State not found in data.")
        return
    print(r.pivot(index="Year", columns="Crop", values="Yield"))
    nat = df.groupby("Crop").Yield.mean()
    for c in ["Wheat", "Rice"]:
        diff = avg.loc[r.State.iloc[0], c] - nat[c]
        print(f"{c}: {'above' if diff > 0 else 'below'} the 5-state average by {abs(diff):.2f} q/ha")


def above():
    nat = avg.mean()
    print("States above the average:")
    for c in ["Wheat", "Rice"]:
        print(f"  {c}: {avg[avg[c] > nat[c]].index.tolist()} (average {nat[c]:.2f})")


def charts():
    avg.plot(kind="bar", figsize=(7, 4), color=["#f08c00", "#2b8a3e"])
    plt.ylabel("Average yield (quintal/ha)"); plt.title("State-wise average yield (sample data)"); plt.xticks(rotation=0); plt.tight_layout()
    plt.savefig("crop_yield.png", dpi=90); plt.show()
    for st in data:
        y = df[(df.State == st) & (df.Crop == "Wheat")]
        plt.plot(y.Year, y.Yield, marker="o", label=st)
    plt.xticks([2022, 2023, 2024]); plt.ylabel("q/ha"); plt.title("Wheat yield trend"); plt.legend()
    plt.savefig("yield_trend.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.imshow(growth.values, cmap="YlGn")
    plt.xticks(range(2), growth.columns); plt.yticks(range(len(growth)), growth.index)
    for (i, j), v in pd.DataFrame(growth.values).stack().items():
        plt.text(j, i, f"{v}%", ha="center", va="center")
    plt.colorbar(label="% growth"); plt.title("Growth 2022-2024 heat map")
    plt.savefig("growth_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: crop_yield.png, yield_trend.png, growth_heatmap.png")


print("=" * 55)
print("   CROP YIELD DATA INSIGHTS  (SDG 2)")
print("=" * 55)
while True:
    print("\n1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Jai Kisan!")
        break
    elif ch == "1":
        show()
    elif ch == "2":
        averages()
    elif ch == "3":
        growth_rep()
    elif ch == "4":
        forecast()
    elif ch == "5":
        state_report()
    elif ch == "6":
        above()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Build DataFrame from dictionary
  3. Show menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. groupby / unstack / compute
  6. Show result / chart
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Data30 recordsPASS
2AveragesPunjab bestPASS
3GrowthMP fastest wheatPASS
4Forecast2025 valuesPASS
5State 'Bihar'Bihar rowsPASS
6State 'Goa'Not foundPASS
7Charts3 PNG filesPASS
โš  Limitations
  • Sample data for practice
  • Only two crops
  • Three years only
  • Linear trend assumption
๐Ÿš€ Future scope
  • Use data.gov.in crop production data
  • Add rainfall and fertiliser features
  • ML regression model
  • District-level map

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: data, rows, df, avg, first, last, growth.
  3. 7 functions are defined (lines 24โ€“82) - Python stores them but does NOT run them yet.
  4. Main program starts at line 13: for state, crops in data.items(): - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
show()24โ€“26Showmain program
averages()29โ€“32Averagesmain program
growth_rep()35โ€“37Growth repmain program
forecast()40โ€“44Forecastmain program
state_report()47โ€“57State reportmain program
above()60โ€“64Abovemain program
charts()67โ€“82Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
13
for state, crops in data.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary data; state, crops get one pair each round
14
for crop, ylds in crops.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary crops; crop, ylds get one pair each round
15
for year, y in zip([2022, 2023, 2024], ylds):
๐Ÿ” Loop LOOP that walks through [2022, 2023, 2024], ylds together; year, y get one item from each
16
rows.append([state, crop, year, y])
๐Ÿงฎ Store / Calculate Adds [state, crop, year, y] at the end of list rows
17
df = pd.DataFrame(rows, columns=["State", "Crop", "Year", "Yield"])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from rows; the result is stored in variable df
18
avg = df.groupby(["State", "Crop"]).Yield.mean().unstack().round(2)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby(["State", "Crop"]).Yield.mean().unโ€ฆ to 2 decimal places; the result is stored in variable avg
19
first = df[df.Year == 2022].set_index(["State", "Crop"]).Yield
๐Ÿ“ฆ Library / Data Stores df[df.Year == 2022].set_index(["State", "Cropโ€ฆ in variable first
20
last = df[df.Year == 2024].set_index(["State", "Crop"]).Yield
๐Ÿ“ฆ Library / Data Stores df[df.Year == 2024].set_index(["State", "Cropโ€ฆ in variable last
21
growth = ((last - first) / first * 100).round(2).unstack()
๐Ÿงฎ Store / Calculate Turns inner row labels into columns; the result is stored in variable growth
85
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
86
print("   CROP YIELD DATA INSIGHTS  (SDG 2)")
๐Ÿ–ฅ๏ธ Output Displays the text "CROP YIELD DATA INSIGHTS (SDG 2)" on the screen
87
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
88
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
89
print("\n1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Averages 3.Growth 4.Foreโ€ฆ" on the screen
90
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
91
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
print("Jai Kisan!")
๐Ÿ–ฅ๏ธ Output Displays the text "Jai Kisan!" on the screen
93
break
๐Ÿ” Loop BREAK - leaves the loop immediately
94
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
95
show()
๐Ÿงฎ Store / Calculate Calls our own function show()
96
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
97
averages()
๐Ÿงฎ Store / Calculate Calls our own function averages()
98
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
99
growth_rep()
๐Ÿงฎ Store / Calculate Calls our own function growth_rep()
100
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
101
forecast()
๐Ÿงฎ Store / Calculate Calls our own function forecast()
102
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
103
state_report()
๐Ÿงฎ Store / Calculate Calls our own function state_report()
104
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
105
above()
๐Ÿงฎ Store / Calculate Calls our own function above()
106
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
107
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
108
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
109
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CROP YIELD DATA INSIGHTS (SDG 2) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: show()
    shows: State Crop Year Yield (+32 more lines)
  3. You type 2 at Enter choice:
    runs: averages()
    shows: Average yield by crop: (+13 more lines)
  4. You type 3 at Enter choice:
    runs: growth_rep()
    shows: Growth 2022 -> 2024 (%): (+9 more lines)
  5. You type 4 at Enter choice:
    runs: forecast()
    shows: Year 2022 2023 2024 Avg_increase Forecast_2025 (+12 more lines)
  6. You type 5 at Enter choice:
    runs: state_report()
  7. You type Bihar at State:
    shows: Crop Rice Wheat (+7 more lines)
  8. You type 5 at Enter choice:
    runs: state_report()
  9. You type Goa at State:
    shows: State not found in data. (+1 more lines)
  10. You type 6 at Enter choice:
    runs: above()
    shows: States above the average: (+3 more lines)
  11. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  12. You type 0 at Enter choice:
    shows: Jai Kisan!
โ‘ค Inside each function - line by line
show() - lines 24โ€“26
LineCodeWhat it does
24
def show():
๐Ÿงฉ Function DEFINES a function show(). Python only remembers it here - its body runs later, each time show() is called.
25
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
26
print("Records:", len(df))
๐Ÿ–ฅ๏ธ Output Displays the text "Records:", then the value of len(df) on the screen
averages() - lines 29โ€“32
LineCodeWhat it does
29
def averages():
๐Ÿงฉ Function DEFINES a function averages(). Python only remembers it here - its body runs later, each time averages() is called.
30
print("Average yield by crop:\n" + df.groupby("Crop").Yield.mean().round(2).to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "Average yield by crop:\n" + df.groupby("Cropโ€ฆ on the screen
31
print("\nAverage yield by state:\n", avg)
๐Ÿ–ฅ๏ธ Output Displays the text "Average yield by state:", then the value of avg on the screen
32
print("\nBest state - Wheat:", avg.Wheat.idxmax(), "| Rice:", avg.Rice.idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Best state - Wheat:", then the value of avg.Wheat.idxmax(), then the text "| Rice:", then the value of avg.Rice.idxmax() on the screen
growth_rep() - lines 35โ€“37
LineCodeWhat it does
35
def growth_rep():
๐Ÿงฉ Function DEFINES a function growth_rep(). Python only remembers it here - its body runs later, each time growth_rep() is called.
36
print("Growth 2022 -> 2024 (%):\n", growth)
๐Ÿ–ฅ๏ธ Output Displays the text "Growth 2022 -> 2024 (%):", then the value of growth on the screen
37
print("Fastest growing - Wheat:", growth.Wheat.idxmax(), "| Rice:", growth.Rice.idxmax())
๐Ÿ–ฅ๏ธ Output Displays the text "Fastest growing - Wheat:", then the value of growth.Wheat.idxmax(), then the text "| Rice:", then the value of growth.Rice.idxmax() on the screen
forecast() - lines 40โ€“44
LineCodeWhat it does
40
def forecast():
๐Ÿงฉ Function DEFINES a function forecast(). Python only remembers it here - its body runs later, each time forecast() is called.
41
p = df.pivot_table(index=["State", "Crop"], columns="Year", values="Yield")
๐Ÿ“ฆ Library / Data Makes a summary (pivot) table from df; the result is stored in variable p
42
p["Avg_increase"] = ((p[2024] - p[2022]) / 2).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of (p[2024] - p[2022]) / 2 to 2 decimal places; the result is put into p["Avg_increase"] (item "Avg_increase" of p)
43
p["Forecast_2025"] = (p[2024] + p["Avg_increase"]).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of p[2024] + p["Avg_increase"] to 1 decimal places; the result is put into p["Forecast_2025"] (item "Forecast_2025" of p)
44
print(p)
๐Ÿ–ฅ๏ธ Output Displays the value of p on the screen
state_report() - lines 47โ€“57
LineCodeWhat it does
47
def state_report():
๐Ÿงฉ Function DEFINES a function state_report(). Python only remembers it here - its body runs later, each time state_report() is called.
48
s = input("State: ").strip()
โŒจ๏ธ Input Shows "State: ", reads the typed text, removes extra spaces (strip) and stores it in variable s
49
r = df[df.State.str.lower() == s.lower()]
๐Ÿ“ฆ Library / Data Stores the item df[df.State.str.lower() == s.lower()] in variable r
50
if r.empty:
๐Ÿ”€ Decision CHECKS whether r.empty is True. If True, the indented lines below run; otherwise they are skipped
51
print("State not found in data.")
๐Ÿ–ฅ๏ธ Output Displays the text "State not found in data." on the screen
52
return
๐Ÿงฉ Function Ends the function and goes back to the caller
53
print(r.pivot(index="Year", columns="Crop", values="Yield"))
๐Ÿ–ฅ๏ธ Output Displays the value of r.pivot(index="Year", columns="Crop", values=โ€ฆ on the screen
54
nat = df.groupby("Crop").Yield.mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of df.groupby("Crop").Yield; the result is stored in variable nat
55
for c in ["Wheat", "Rice"]:
๐Ÿ” Loop LOOP: takes each item of ["Wheat", "Rice"] one-by-one into c and runs the indented block for it
56
diff = avg.loc[r.State.iloc[0], c] - nat[c]
๐Ÿงฎ Store / Calculate Stores the value of avg.loc[r.State.iloc[0], c] - nat[c] (calculated using -) in variable diff
57
print(f"{c}: {'above' if diff > 0 else 'below'} the 5-state average by {abs(diff):.2f} q/ha")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c}: {'above' if diff > 0 else 'below'} theโ€ฆ with the values filled into { } on the screen
above() - lines 60โ€“64
LineCodeWhat it does
60
def above():
๐Ÿงฉ Function DEFINES a function above(). Python only remembers it here - its body runs later, each time above() is called.
61
nat = avg.mean()
๐Ÿงฎ Store / Calculate Finds the average (mean) of avg; the result is stored in variable nat
62
print("States above the average:")
๐Ÿ–ฅ๏ธ Output Displays the text "States above the average:" on the screen
63
for c in ["Wheat", "Rice"]:
๐Ÿ” Loop LOOP: takes each item of ["Wheat", "Rice"] one-by-one into c and runs the indented block for it
64
print(f"  {c}: {avg[avg[c] > nat[c]].index.tolist()} (average {nat[c]:.2f})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {c}: {avg[avg[c] > nat[c]].index.tolist()}โ€ฆ with the values filled into { } on the screen
charts() - lines 67โ€“82
LineCodeWhat it does
67
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
68
avg.plot(kind="bar", figsize=(7, 4), color=["#f08c00", "#2b8a3e"])
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
69
plt.ylabel("Average yield (quintal/ha)"); plt.title("State-wise average yield (sample data)"); plt.xticks(rotation=0); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Writes "Average yield (quintal/ha)" as the label of the Y-axis
69
plt.ylabel("Average yield (quintal/ha)"); plt.title("State-wise average yield (sample data)"); plt.xticks(rotation=0); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Writes "State-wise average yield (sample data)" as the title of the chart
69
plt.ylabel("Average yield (quintal/ha)"); plt.title("State-wise average yield (sample data)"); plt.xticks(rotation=0); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
69
plt.ylabel("Average yield (quintal/ha)"); plt.title("State-wise average yield (sample data)"); plt.xticks(rotation=0); plt.tight_layout()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
70
plt.savefig("crop_yield.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "crop_yield.png"
70
plt.savefig("crop_yield.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
71
for st in data:
๐Ÿ” Loop LOOP: takes each item of data one-by-one into st and runs the indented block for it
72
y = df[(df.State == st) & (df.Crop == "Wheat")]
๐Ÿ“ฆ Library / Data Stores the item df[(df.State == st) & (df.Crop == "Wheat")] in variable y
73
plt.plot(y.Year, y.Yield, marker="o", label=st)
๐Ÿ–ฅ๏ธ Output Draws a line chart of y.Year, y.Yield
74
plt.xticks([2022, 2023, 2024]); plt.ylabel("q/ha"); plt.title("Wheat yield trend"); plt.legend()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
74
plt.xticks([2022, 2023, 2024]); plt.ylabel("q/ha"); plt.title("Wheat yield trend"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "q/ha" as the label of the Y-axis
74
plt.xticks([2022, 2023, 2024]); plt.ylabel("q/ha"); plt.title("Wheat yield trend"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Wheat yield trend" as the title of the chart
74
plt.xticks([2022, 2023, 2024]); plt.ylabel("q/ha"); plt.title("Wheat yield trend"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
75
plt.savefig("yield_trend.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "yield_trend.png"
75
plt.savefig("yield_trend.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
76
plt.imshow(growth.values, cmap="YlGn")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
77
plt.xticks(range(2), growth.columns); plt.yticks(range(len(growth)), growth.index)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
77
plt.xticks(range(2), growth.columns); plt.yticks(range(len(growth)), growth.index)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
78
for (i, j), v in pd.DataFrame(growth.values).stack().items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary pd.DataFrame(growth.values).stack(); (i, j), v get one pair each round
79
plt.text(j, i, f"{v}%", ha="center", va="center")
๐Ÿ–ฅ๏ธ Output Writes text on the chart
80
plt.colorbar(label="% growth"); plt.title("Growth 2022-2024 heat map")
๐Ÿ–ฅ๏ธ Output Shows a colour scale bar
80
plt.colorbar(label="% growth"); plt.title("Growth 2022-2024 heat map")
๐Ÿ–ฅ๏ธ Output Writes "Growth 2022-2024 heat map" as the title of the chart
81
plt.savefig("growth_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "growth_heatmap.png"
81
plt.savefig("growth_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
print("Charts saved: crop_yield.png, yield_trend.png, growth_heatmap.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: crop_yield.png, yieโ€ฆ" on the screen
Q1. What does unstack() do?

Moves an index level (Crop) into columns, making a State x Crop table.

Q2. How is growth % calculated?

(2024 yield - 2022 yield) / 2022 yield x 100.

Q3. How is 2025 forecast made?

2024 yield + average yearly increase.

Q4. Why use a heat map?

Colours show high and low growth at a glance.

Q5. Which SDG?

SDG 2 - Zero Hunger.

๐Ÿ“Š Class XI Artificial Intelligence (843) โ€” 10 Machine Learning Projects 10 projects

01

Rainfall Data Analysis and Visualisation (rainfall.csv)

PYTHON + PANDASSDG 13 - Climate Actionread_csvstatistical measures (meanmedianmodestd
๐Ÿ“ 88 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

Uses the rainfall.csv file mentioned in the CBSE Unit 5 practical list to compute all statistical measures, group months into seasons, and visualise the data with four types of charts in a single dashboard.

โœจ Features
  • Monthly rainfall and temperature read from rainfall.csv with Pandas
  • Measures of central tendency (mean, median, mode) and dispersion (variance, std, range, IQR) using pandas and statistics
  • Season mapping and season-wise totals
  • Outlier detection with the IQR rule (1.5 x IQR)
  • Z-score of each month and normalisation (min-max)
  • 4-chart dashboard, box plot and cumulative rainfall chart
โ˜ฐ Main menu
1View DataCSV contents
2Central TendencyMean, median, mode
3DispersionVariance, std, range, IQR
4Season Analysisgroupby season
5Outliers (IQR)Months outside Q1-1.5IQR / Q3+1.5IQR
6Z-score & NormaliseStandardised values
7Dashboard Charts3 chart files
0ExitEnds program
๐ŸŽฏ Objectives
  • Calculate mean, median, mode, standard deviation and variance of real-world data
  • Aggregate monthly data into seasons using a mapping dictionary
  • Create a multi-chart dashboard with matplotlib subplots
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameMonth, Rainfall_mm, Avg_Temp_C, Season
rSeriesRainfall column
season_ofdictMonth -> season
q1, q3, iqrfloatQuartiles and inter-quartile range
Why it matters: Directly covers the Unit 5 practicals (statistics + matplotlib) in one complete, presentable mini-project.
# =====================================================================
#   RAINFALL DATA ANALYSIS AND VISUALISATION   (SDG 13)
#   Statistics + Pandas + Matplotlib  (Unit: Data Literacy)
# =====================================================================
import pandas as pd
import statistics as st
import matplotlib.pyplot as plt

df = pd.read_csv("rainfall.csv")
r = df["Rainfall_mm"]
season_of = {"Dec": "Winter", "Jan": "Winter", "Feb": "Winter", "Mar": "Summer", "Apr": "Summer", "May": "Summer",
             "Jun": "Monsoon", "Jul": "Monsoon", "Aug": "Monsoon", "Sep": "Monsoon", "Oct": "Post-monsoon", "Nov": "Post-monsoon"}
df["Season"] = df["Month"].map(season_of)
q1, q3 = r.quantile(0.25), r.quantile(0.75)
iqr = q3 - q1


def view():
    print(df.to_string(index=False))
    print("Months loaded:", len(df), "| Total:", r.sum(), "mm")


def central():
    print("Mean   :", round(r.mean(), 2))
    print("Median :", r.median())
    print("Mode   :", st.mode(r), "(statistics.mode)")
    print("Skew   :", round(r.skew(), 3), "-> right-skewed (monsoon months pull the mean up)")


def dispersion():
    print("Variance (sample)    :", round(r.var(), 2))
    print("Variance (population):", round(st.pvariance(r), 2))
    print("Std deviation        :", round(r.std(), 2))
    print("Range                :", r.max() - r.min())
    print(f"Q1 = {q1}, Q3 = {q3}, IQR = {iqr}")


def seasons():
    s = df.groupby("Season").agg(Total=("Rainfall_mm", "sum"), Mean=("Rainfall_mm", "mean"), Temp=("Avg_Temp_C", "mean")).round(1)
    s["Share_%"] = (s.Total / s.Total.sum() * 100).round(1)
    print(s.sort_values("Total", ascending=False))
    print("\nMonths above average:", df[r > r.mean()]["Month"].tolist())


def outliers():
    lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr
    print(f"Normal range: {lo:.2f} to {hi:.2f} mm")
    o = df[(r < lo) | (r > hi)]
    print("Outlier months:\n", o[["Month", "Rainfall_mm"]].to_string(index=False))
    print("These are monsoon months - outliers here are real, not errors.")


def zscore():
    z = ((r - r.mean()) / r.std()).round(2)
    mm = ((r - r.min()) / (r.max() - r.min())).round(3)
    print(pd.DataFrame({"Month": df.Month, "Rain": r, "Z-score": z, "MinMax": mm}).to_string(index=False))


def charts():
    season = df.groupby("Season")["Rainfall_mm"].sum().sort_values(ascending=False)
    fig, ax = plt.subplots(2, 2, figsize=(10, 7))
    ax[0, 0].plot(df.Month, r, marker="o"); ax[0, 0].set_title("Line: monthly trend")
    ax[0, 1].bar(df.Month, r, color="teal"); ax[0, 1].set_title("Bar: rainfall by month")
    ax[1, 0].pie(season, labels=season.index, autopct="%1.0f%%"); ax[1, 0].set_title("Pie: seasonal share")
    ax[1, 1].hist(r, bins=[0, 25, 50, 100, 150, 250], edgecolor="black", color="orange"); ax[1, 1].set_title("Histogram: distribution")
    for a in (ax[0, 0], ax[0, 1]):
        a.tick_params(axis="x", labelsize=8)
    plt.suptitle("Rainfall dashboard (sample Delhi normals)"); plt.tight_layout(); plt.savefig("rain_dashboard.png", dpi=80); plt.show()
    plt.boxplot([r, df.Avg_Temp_C * 5]); plt.xticks([1, 2], ["Rainfall (mm)", "Temp x5 (C)"]); plt.title("Box plot - spread and outliers")
    plt.savefig("rain_box.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.fill_between(df.Month, r.cumsum(), color="#74c0fc"); plt.plot(df.Month, r.cumsum(), "b-o")
    plt.title("Cumulative rainfall through the year"); plt.ylabel("mm")
    plt.savefig("rain_cumulative.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: rain_dashboard.png, rain_box.png, rain_cumulative.png")


print("=" * 55)
print("   RAINFALL DATA ANALYSIS  (SDG 13)")
print("=" * 55)
menu = {"1": view, "2": central, "3": dispersion, "4": seasons, "5": outliers, "6": zscore, "7": charts}
while True:
    print("\n1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Read rainfall.csv
  3. Show menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. Compute statistics
  6. Show result / charts
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1View12 rowsPASS
2Central tendencyMean 63.0, median 19.5PASS
3DispersionStd 81.5PASS
4SeasonMonsoon 637 mmPASS
5OutliersJul, Aug, Sep flaggedPASS
6Z-scoreAug highestPASS
7Charts3 PNG filesPASS
โš  Limitations
  • Monthly normals (12 values)
  • One station
  • Mode not meaningful for continuous data
  • No year-wise variation
๐Ÿš€ Future scope
  • Use 30 years of IMD data
  • Forecast monsoon with ML
  • Compare cities
  • Interactive Plotly dashboard

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 5): pandas - data tables (Series & DataFrame), statistics - mean, median, mode functions, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: df, r, season_of, iqr.
  3. 7 functions are defined (lines 18โ€“74) - Python stores them but does NOT run them yet.
  4. Main program starts at line 13: df["Season"] = df["Month"].map(season_of) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
view()18โ€“20Viewmain program (menu)
central()23โ€“27Centralmain program (menu)
dispersion()30โ€“35Dispersionmain program (menu)
seasons()38โ€“42Seasonsmain program (menu)
outliers()45โ€“50Outliersmain program (menu)
zscore()53โ€“56Zscoremain program (menu)
charts()59โ€“74Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
13
df["Season"] = df["Month"].map(season_of)
๐Ÿงฎ Store / Calculate Applies season_of to every item of ; the result is put into df["Season"] (item "Season" of df)
14
q1, q3 = r.quantile(0.25), r.quantile(0.75)
๐Ÿงฎ Store / Calculate Stores r.quantile(0.25), r.quantile(0.75) into q1, q3 respectively
15
iqr = q3 - q1
๐Ÿงฎ Store / Calculate Stores the value of q3 - q1 (calculated using -) in variable iqr
77
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
78
print("   RAINFALL DATA ANALYSIS  (SDG 13)")
๐Ÿ–ฅ๏ธ Output Displays the text "RAINFALL DATA ANALYSIS (SDG 13)" on the screen
79
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
80
menu = {"1": view, "2": central, "3": dispersion, "4": seasons, "5": outliers, "6": zscore, "7": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": central, "3": dispersion, "4โ€ฆ in variable menu
81
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
82
print("\n1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Central Tendency 3.Dispeโ€ฆ" on the screen
83
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
84
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
85
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
86
break
๐Ÿ” Loop BREAK - leaves the loop immediately
87
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: RAINFALL DATA ANALYSIS (SDG 13) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: view()
    shows: Month Rainfall_mm Avg_Temp_C Season (+14 more lines)
  3. You type 2 at Enter choice:
    runs: central()
    shows: Mean : 63.0 (+4 more lines)
  4. You type 3 at Enter choice:
    runs: dispersion()
    shows: Variance (sample) : 6644.55 (+5 more lines)
  5. You type 4 at Enter choice:
    runs: seasons()
    shows: Total Mean Temp Share_% (+7 more lines)
  6. You type 5 at Enter choice:
    runs: outliers()
    shows: Normal range: -90.88 to 188.12 mm (+6 more lines)
  7. You type 6 at Enter choice:
    runs: zscore()
    shows: Month Rain Z-score MinMax (+13 more lines)
  8. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  9. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
view() - lines 18โ€“20
LineCodeWhat it does
18
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
19
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
20
print("Months loaded:", len(df), "| Total:", r.sum(), "mm")
๐Ÿ–ฅ๏ธ Output Displays the text "Months loaded:", then the value of len(df), then the text "| Total:", then the value of r.sum(), then the text "mm" on the screen
central() - lines 23โ€“27
LineCodeWhat it does
23
def central():
๐Ÿงฉ Function DEFINES a function central(). Python only remembers it here - its body runs later, each time central() is called.
24
print("Mean   :", round(r.mean(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Mean :", then the value of round(r.mean(), 2) on the screen
25
print("Median :", r.median())
๐Ÿ–ฅ๏ธ Output Displays the text "Median :", then the value of r.median() on the screen
26
print("Mode   :", st.mode(r), "(statistics.mode)")
๐Ÿ–ฅ๏ธ Output Displays the text "Mode :", then the value of st.mode(r), then the text "(statistics.mode)" on the screen
27
print("Skew   :", round(r.skew(), 3), "-> right-skewed (monsoon months pull the mean up)")
๐Ÿ–ฅ๏ธ Output Displays the text "Skew :", then the value of round(r.skew(), 3), then the text "-> right-skewed (monsoon months pโ€ฆ" on the screen
dispersion() - lines 30โ€“35
LineCodeWhat it does
30
def dispersion():
๐Ÿงฉ Function DEFINES a function dispersion(). Python only remembers it here - its body runs later, each time dispersion() is called.
31
print("Variance (sample)    :", round(r.var(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Variance (sample) :", then the value of round(r.var(), 2) on the screen
32
print("Variance (population):", round(st.pvariance(r), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Variance (population):", then the value of round(st.pvariance(r), 2) on the screen
33
print("Std deviation        :", round(r.std(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Std deviation :", then the value of round(r.std(), 2) on the screen
34
print("Range                :", r.max() - r.min())
๐Ÿ–ฅ๏ธ Output Displays the text "Range :", then the value of r.max() - r.min() on the screen
35
print(f"Q1 = {q1}, Q3 = {q3}, IQR = {iqr}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Q1 = {q1}, Q3 = {q3}, IQR = {iqr}" with the values filled into { } on the screen
seasons() - lines 38โ€“42
LineCodeWhat it does
38
def seasons():
๐Ÿงฉ Function DEFINES a function seasons(). Python only remembers it here - its body runs later, each time seasons() is called.
39
s = df.groupby("Season").agg(Total=("Rainfall_mm", "sum"), Mean=("Rainfall_mm", "mean"), Temp=("Avg_Temp_C", "mean")).round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby("Season").agg(Total=("Rainfall_mm"โ€ฆ to 1 decimal places; the result is stored in variable s
40
s["Share_%"] = (s.Total / s.Total.sum() * 100).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of s.Total / s.Total.sum() * 100 to 1 decimal places; the result is put into s["Share_%"] (item "Share_%" of s)
41
print(s.sort_values("Total", ascending=False))
๐Ÿ–ฅ๏ธ Output Displays the value of s.sort_values("Total", ascending=False) on the screen
42
print("\nMonths above average:", df[r > r.mean()]["Month"].tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Months above average:", then the value of df[r > r.mean()]["Month"].tolist() on the screen
outliers() - lines 45โ€“50
LineCodeWhat it does
45
def outliers():
๐Ÿงฉ Function DEFINES a function outliers(). Python only remembers it here - its body runs later, each time outliers() is called.
46
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr
๐Ÿงฎ Store / Calculate Stores q1 - 1.5 * iqr, q3 + 1.5 * iqr into lo, hi respectively
47
print(f"Normal range: {lo:.2f} to {hi:.2f} mm")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Normal range: {lo:.2f} to {hi:.2f} mm" with the values filled into { } on the screen
48
o = df[(r < lo) | (r > hi)]
๐Ÿงฎ Store / Calculate Stores the item df[(r < lo) | (r > hi)] in variable o
49
print("Outlier months:\n", o[["Month", "Rainfall_mm"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the text "Outlier months:", then the value of o[["Month", "Rainfall_mm"]].to_string(index=Fโ€ฆ on the screen
50
print("These are monsoon months - outliers here are real, not errors.")
๐Ÿ–ฅ๏ธ Output Displays the text "These are monsoon months - outlieโ€ฆ" on the screen
zscore() - lines 53โ€“56
LineCodeWhat it does
53
def zscore():
๐Ÿงฉ Function DEFINES a function zscore(). Python only remembers it here - its body runs later, each time zscore() is called.
54
z = ((r - r.mean()) / r.std()).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of (r - r.mean()) / r.std() to 2 decimal places; the result is stored in variable z
55
mm = ((r - r.min()) / (r.max() - r.min())).round(3)
๐Ÿงฎ Store / Calculate Rounds the values of (r - r.min()) / (r.max() - r.min()) to 3 decimal places; the result is stored in variable mm
56
print(pd.DataFrame({"Month": df.Month, "Rain": r, "Z-score": z, "MinMax": mm}).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.DataFrame({"Month": df.Month, "Rain": r, "โ€ฆ on the screen
charts() - lines 59โ€“74
LineCodeWhat it does
59
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
60
season = df.groupby("Season")["Rainfall_mm"].sum().sort_values(ascending=False)
๐Ÿ“ฆ Library / Data Sorts df.groupby("Season")["Rainfall_mm"].sum() by in descending order; the result is stored in variable season
61
fig, ax = plt.subplots(2, 2, figsize=(10, 7))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax
62
ax[0, 0].plot(df.Month, r, marker="o"); ax[0, 0].set_title("Line: monthly trend")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Month, r
62
ax[0, 0].plot(df.Month, r, marker="o"); ax[0, 0].set_title("Line: monthly trend")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
63
ax[0, 1].bar(df.Month, r, color="teal"); ax[0, 1].set_title("Bar: rainfall by month")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of df.Month, r
63
ax[0, 1].bar(df.Month, r, color="teal"); ax[0, 1].set_title("Bar: rainfall by month")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
64
ax[1, 0].pie(season, labels=season.index, autopct="%1.0f%%"); ax[1, 0].set_title("Pie: seasonal share")
๐Ÿ–ฅ๏ธ Output Draws a pie chart of season
64
ax[1, 0].pie(season, labels=season.index, autopct="%1.0f%%"); ax[1, 0].set_title("Pie: seasonal share")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
65
ax[1, 1].hist(r, bins=[0, 25, 50, 100, 150, 250], edgecolor="black", color="orange"); ax[1, 1].set_title("Histogram: distribution")
๐Ÿ–ฅ๏ธ Output Draws a histogram of r
65
ax[1, 1].hist(r, bins=[0, 25, 50, 100, 150, 250], edgecolor="black", color="orange"); ax[1, 1].set_title("Histogram: distribution")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
66
for a in (ax[0, 0], ax[0, 1]):
๐Ÿ” Loop LOOP: takes each item of (ax[0, 0], ax[0, 1]) one-by-one into a and runs the indented block for it
67
a.tick_params(axis="x", labelsize=8)
๐Ÿงฎ Store / Calculate Calls a.tick_params()
68
plt.suptitle("Rainfall dashboard (sample Delhi normals)"); plt.tight_layout(); plt.savefig("rain_dashboard.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the main title of the figure
68
plt.suptitle("Rainfall dashboard (sample Delhi normals)"); plt.tight_layout(); plt.savefig("rain_dashboard.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
68
plt.suptitle("Rainfall dashboard (sample Delhi normals)"); plt.tight_layout(); plt.savefig("rain_dashboard.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "rain_dashboard.png"
68
plt.suptitle("Rainfall dashboard (sample Delhi normals)"); plt.tight_layout(); plt.savefig("rain_dashboard.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
69
plt.boxplot([r, df.Avg_Temp_C * 5]); plt.xticks([1, 2], ["Rainfall (mm)", "Temp x5 (C)"]); plt.title("Box plot - spread and outliers")
๐Ÿ–ฅ๏ธ Output Draws a box plot of [r, df.Avg_Temp_C * 5]
69
plt.boxplot([r, df.Avg_Temp_C * 5]); plt.xticks([1, 2], ["Rainfall (mm)", "Temp x5 (C)"]); plt.title("Box plot - spread and outliers")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
69
plt.boxplot([r, df.Avg_Temp_C * 5]); plt.xticks([1, 2], ["Rainfall (mm)", "Temp x5 (C)"]); plt.title("Box plot - spread and outliers")
๐Ÿ–ฅ๏ธ Output Writes "Box plot - spread and outliers" as the title of the chart
70
plt.savefig("rain_box.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "rain_box.png"
70
plt.savefig("rain_box.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
71
plt.fill_between(df.Month, r.cumsum(), color="#74c0fc"); plt.plot(df.Month, r.cumsum(), "b-o")
๐Ÿ–ฅ๏ธ Output Shades the area between lines
71
plt.fill_between(df.Month, r.cumsum(), color="#74c0fc"); plt.plot(df.Month, r.cumsum(), "b-o")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Month, r.cumsum(), "b-o"
72
plt.title("Cumulative rainfall through the year"); plt.ylabel("mm")
๐Ÿ–ฅ๏ธ Output Writes "Cumulative rainfall through the year" as the title of the chart
72
plt.title("Cumulative rainfall through the year"); plt.ylabel("mm")
๐Ÿ–ฅ๏ธ Output Writes "mm" as the label of the Y-axis
73
plt.savefig("rain_cumulative.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "rain_cumulative.png"
73
plt.savefig("rain_cumulative.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
74
print("Charts saved: rain_dashboard.png, rain_box.png, rain_cumulative.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: rain_dashboard.png,โ€ฆ" on the screen
Q1. Mean vs median - which is better here?

Median, because rainfall is highly skewed by monsoon months; mean is pulled up by outliers.

Q2. What is IQR?

Q3 - Q1, the spread of the middle 50 % of data.

Q3. What is a z-score?

(x - mean) / std - how many standard deviations a value is from the mean.

Q4. What does a box plot show?

Median, quartiles, whiskers and outliers.

Q5. Difference between variance and standard deviation?

Std is the square root of variance and has the same unit as the data (mm).

02

House Price Predictor - Linear Regression (SDG 11)

PYTHON + SKLEARNSDG 11 - Sustainable Cities and CommunitiesMultiple linear regressiontrain_test_splitcoefficientsMAE / RMSE / R2prediction from user input
๐Ÿ“ 121 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

Trains a linear regression model on sample housing data (area, bedrooms, age, distance to metro) to predict flat prices, interprets the learnt coefficients, evaluates the model on test data and predicts the price of a flat entered by the user.

โœจ Features
  • Sample dataset of 60 flats: area, bedrooms, age, metro distance and price (lakh)
  • Exploration: describe(), correlation of each feature with price
  • Linear Regression (scikit-learn) with 75:25 train-test split
  • Evaluation: MAE, RMSE, R squared on train and test (overfitting check)
  • Compare with a single-feature model (area only)
  • Price estimate for a new flat with price per sq ft; 3 charts
โ˜ฐ Main menu
1Explore Datahead, describe, correlation
2Train ModelFit LinearRegression
3CoefficientsEffect of each feature
4EvaluateMAE, RMSE, R2 train vs test
5Compare ModelsArea-only vs all features
6Predict PriceNew flat details
7ChartsActual vs predicted, coefficients, residuals
0ExitEnds program
๐ŸŽฏ Objectives
  • Prepare features and target and split them into train and test sets
  • Train a multiple linear regression model and interpret coefficients
  • Evaluate with MAE, RMSE and R2 and deploy for user predictions
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameArea, Bedrooms, Age, Metro_km, Price_lakh
FEATlistFeature names
modelLinearRegressionTrained model
X_train ... y_testDataFramesSplit data
Why it matters: Applies the Unit 6 regression concept to a multi-feature real-life problem with proper evaluation.
# =====================================================================
#   HOUSE PRICE PREDICTOR - LINEAR REGRESSION   (SDG 11)
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

rng = np.random.default_rng(11)
n = 60
area = rng.integers(500, 2000, n)
bed = np.clip(area // 450, 1, 4)
age = rng.integers(0, 25, n)
metro = np.round(rng.uniform(0.2, 6, n), 1)
price = 0.06 * area + 4 * bed - 0.5 * age - 2.5 * metro + 10 + rng.normal(0, 3, n)
df = pd.DataFrame({"Area": area, "Bedrooms": bed, "Age": age, "Metro_km": metro, "Price_lakh": price.round(1)})
FEAT = ["Area", "Bedrooms", "Age", "Metro_km"]
X_train, X_test, y_train, y_test = train_test_split(df[FEAT], df.Price_lakh, test_size=0.25, random_state=1)
model = None


def explore():
    print(df.head())
    print("\n", df.describe().round(1))
    print("\nCorrelation with price:\n" + df.corr()["Price_lakh"].drop("Price_lakh").round(3).to_string())


def train():
    global model
    model = LinearRegression().fit(X_train, y_train)
    print("Model trained on", len(X_train), "flats; testing on", len(X_test))


def coefficients():
    for f, c in zip(FEAT, model.coef_):
        print(f"  {f:<9}: {c:+.3f}  lakh per unit")
    print("  Intercept:", round(model.intercept_, 3))
    print("Price = %.2f + %.3f*Area + %.2f*Bed %+.2f*Age %+.2f*Metro" % (model.intercept_, *model.coef_))


def scores(m, Xtr, Xte):
    out = []
    for X, y in ((Xtr, y_train), (Xte, y_test)):
        p = m.predict(X)
        out.append((mean_absolute_error(y, p), np.sqrt(mean_squared_error(y, p)), r2_score(y, p)))
    return out


def evaluate():
    tr, te = scores(model, X_train, X_test)
    print(f"{'Set':<7}{'MAE':>8}{'RMSE':>8}{'R2':>8}")
    print(f"{'Train':<7}{tr[0]:>8.2f}{tr[1]:>8.2f}{tr[2]:>8.3f}")
    print(f"{'Test':<7}{te[0]:>8.2f}{te[1]:>8.2f}{te[2]:>8.3f}")
    print("Small gap between train and test -> no overfitting.")


def compare():
    m1 = LinearRegression().fit(X_train[["Area"]], y_train)
    s1 = scores(m1, X_train[["Area"]], X_test[["Area"]])[1]
    s2 = scores(model, X_train, X_test)[1]
    print(f"Area only    : test RMSE {s1[1]:.2f}, R2 {s1[2]:.3f}")
    print(f"All features : test RMSE {s2[1]:.2f}, R2 {s2[2]:.3f}")
    print("More relevant features -> better predictions.")


def predict():
    a = float(input("Area (sq ft)       : "))
    if not 300 <= a <= 5000:
        print("Area must be 300-5000 sq ft.")
        return
    b, g, m = int(input("Bedrooms           : ")), float(input("Age of building    : ")), float(input("Distance to metro  : "))
    p = model.predict(pd.DataFrame([[a, b, g, m]], columns=FEAT))[0]
    print(f"Estimated price: Rs. {p:.2f} lakh  (Rs. {p * 100000 / a:,.0f} per sq ft)")


def charts():
    pred = model.predict(X_test)
    plt.scatter(y_test, pred, color="purple"); lim = [df.Price_lakh.min(), df.Price_lakh.max()]
    plt.plot(lim, lim, "k--", label="Perfect prediction")
    plt.xlabel("Actual price (lakh)"); plt.ylabel("Predicted price (lakh)"); plt.title("Actual vs predicted (test data)"); plt.legend()
    plt.savefig("house_pred.png", dpi=90, bbox_inches="tight"); plt.show()
    eff = model.coef_ * df[FEAT].std().values
    plt.barh(FEAT, eff, color=["green" if e > 0 else "red" for e in eff]); plt.axvline(0, color="k")
    plt.title("Effect on price of 1 std change in each feature (lakh)")
    plt.savefig("house_coef.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.scatter(pred, y_test - pred, color="teal"); plt.axhline(0, color="red")
    plt.xlabel("Predicted"); plt.ylabel("Residual"); plt.title("Residual plot")
    plt.savefig("house_residuals.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: house_pred.png, house_coef.png, house_residuals.png")


print("=" * 55)
print("   HOUSE PRICE PREDICTOR  (Linear Regression)")
print("=" * 55)
while True:
    print("\n1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        explore()
    elif ch == "2":
        train()
    elif model is None:
        print("Train the model first (option 2).")
    elif ch == "3":
        coefficients()
    elif ch == "4":
        evaluate()
    elif ch == "5":
        compare()
    elif ch == "6":
        predict()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create dataset
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. model.predict()
  6. Calculate MAE, RMSE, R2
  7. Show result
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Explore60 rows, Area most correlatedPASS
2Evaluate before training'Train first'PASS
3CoefficientsArea +, Age -, Metro -PASS
4EvaluateTest R2 0.993, train 0.994PASS
5CompareAll features betterPASS
6Predict 1100, 2, 5, 1.5Estimated pricePASS
7Area 50'Area must be 300-5000'PASS
โš  Limitations
  • Synthetic data
  • Linear relation assumed
  • Location / floor ignored
  • Small dataset
๐Ÿš€ Future scope
  • Use real housing data (e.g. Kaggle Bengaluru)
  • Polynomial / random-forest models
  • Web price calculator
  • Feature scaling + regularisation

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, train_test_split, LinearRegression, mean_absolute_error, mean_squared_error, r2_score are loaded.
  2. Global variables / constants are created: rng, n, area, bed, age, metro, price, df, FEAT, model.
  3. 8 functions are defined (lines 24โ€“91) - Python stores them but does NOT run them yet.
  4. Main program starts at line 20: X_train, X_test, y_train, y_test = train_test_split(df[FEAT], df.Price - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
explore()24โ€“27Exploremain program
train()30โ€“33Trainmain program
coefficients()36โ€“40Coefficientsmain program
scores(m, Xtr, Xte)43โ€“48Scoresevaluate(), compare()
evaluate()51โ€“56Evaluatemain program
compare()59โ€“65Comparemain program
predict()68โ€“75Predictmain program
charts()78โ€“91Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
20
X_train, X_test, y_train, y_test = train_test_split(df[FEAT], df.Price_lakh, test_size=0.25, random_state=1)
๐Ÿ“ฆ Library / Data Splits the data into training and testing parts (25% for testing) and stores them in X_train, X_test, y_train, y_test
21
model = None
๐Ÿงฎ Store / Calculate Stores None (nothing) in variable model
94
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
95
print("   HOUSE PRICE PREDICTOR  (Linear Regression)")
๐Ÿ–ฅ๏ธ Output Displays the text "HOUSE PRICE PREDICTOR (Linear Regโ€ฆ" on the screen
96
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
97
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
98
print("\n1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Explore 2.Train 3.Coefficients โ€ฆ" on the screen
99
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
100
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
101
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
102
break
๐Ÿ” Loop BREAK - leaves the loop immediately
103
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
104
explore()
๐Ÿงฎ Store / Calculate Calls our own function explore()
105
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
106
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
107
elif model is None:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether model is None
108
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
109
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
110
coefficients()
๐Ÿงฎ Store / Calculate Calls our own function coefficients()
111
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
112
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
113
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
114
compare()
๐Ÿงฎ Store / Calculate Calls our own function compare()
115
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
116
predict()
๐Ÿงฎ Store / Calculate Calls our own function predict()
117
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
118
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
119
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
120
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HOUSE PRICE PREDICTOR (Linear Regression) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: explore()
    shows: Area Bedrooms Age Metro_km Price_lakh (+20 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Model trained on 45 flats; testing on 15 (+1 more lines)
  5. You type 3 at Enter choice:
    runs: coefficients()
    shows: Area : +0.063 lakh per unit (+6 more lines)
  6. You type 4 at Enter choice:
    runs: evaluate() โ†’ scores()
    shows: Set MAE RMSE R2 (+4 more lines)
  7. You type 5 at Enter choice:
    runs: compare() โ†’ scores() ร—2
    shows: Area only : test RMSE 5.92, R2 0.958 (+3 more lines)
  8. You type 6 at Enter choice:
    runs: predict()
  9. You type 1100 at Area (sq ft) :
  10. You type 2 at Bedrooms :
  11. You type 5 at Age of building :
  12. You type 1.5 at Distance to metro :
    shows: Estimated price: Rs. 76.83 lakh (Rs. 6,984 per sq ft) (+1 more lines)
  13. You type 6 at Enter choice:
    runs: predict()
  14. You type 50 at Area (sq ft) :
    shows: Area must be 300-5000 sq ft. (+1 more lines)
  15. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  16. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
explore() - lines 24โ€“27
LineCodeWhat it does
24
def explore():
๐Ÿงฉ Function DEFINES a function explore(). Python only remembers it here - its body runs later, each time explore() is called.
25
print(df.head())
๐Ÿ–ฅ๏ธ Output Displays the value of df.head() on the screen
26
print("\n", df.describe().round(1))
๐Ÿ–ฅ๏ธ Output Displays a blank, then the value of df.describe().round(1) on the screen
27
print("\nCorrelation with price:\n" + df.corr()["Price_lakh"].drop("Price_lakh").round(3).to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "\nCorrelation with price:\n" + df.corr()["Prโ€ฆ on the screen
train() - lines 30โ€“33
LineCodeWhat it does
30
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
31
global model
๐Ÿงฉ Function Tells Python that model means the GLOBAL variable (outside the function)
32
model = LinearRegression().fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model LinearRegression() on the given data; the result is stored in variable model
33
print("Model trained on", len(X_train), "flats; testing on", len(X_test))
๐Ÿ–ฅ๏ธ Output Displays the text "Model trained on", then the value of len(X_train), then the text "flats; testing on", then the value of len(X_test) on the screen
coefficients() - lines 36โ€“40
LineCodeWhat it does
36
def coefficients():
๐Ÿงฉ Function DEFINES a function coefficients(). Python only remembers it here - its body runs later, each time coefficients() is called.
37
for f, c in zip(FEAT, model.coef_):
๐Ÿ” Loop LOOP that walks through FEAT, model.coef_ together; f, c get one item from each
38
print(f"  {f:<9}: {c:+.3f}  lakh per unit")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {f:<9}: {c:+.3f} lakh per unit" with the values filled into { } on the screen
39
print("  Intercept:", round(model.intercept_, 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Intercept:", then the value of round(model.intercept_, 3) on the screen
40
print("Price = %.2f + %.3f*Area + %.2f*Bed %+.2f*Age %+.2f*Metro" % (model.intercept_, *model.coef_))
๐Ÿ–ฅ๏ธ Output Displays the value of "Price = %.2f + %.3f*Area + %.2f*Bed %+.2f*Agโ€ฆ on the screen
scores() - lines 43โ€“48
LineCodeWhat it does
43
def scores(m, Xtr, Xte):
๐Ÿงฉ Function DEFINES a function scores(m, Xtr, Xte). Python only remembers it here - its body runs later, each time scores() is called.
44
out = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable out
45
for X, y in ((Xtr, y_train), (Xte, y_test)):
๐Ÿ” Loop LOOP: takes each item of ((Xtr, y_train), (Xte, y_test)) one-by-one into X, y and runs the indented block for it
46
p = m.predict(X)
๐Ÿ“ฆ Library / Data Uses the trained model m to predict answers for X; the result is stored in variable p
47
out.append((mean_absolute_error(y, p), np.sqrt(mean_squared_error(y, p)), r2_score(y, p)))
๐Ÿ“ฆ Library / Data Adds (mean_absolute_error(y, p), np.sqrt(mean_squaโ€ฆ at the end of list out
48
return out
๐Ÿงฉ Function Sends back (returns) the value of out to the line that called the function
evaluate() - lines 51โ€“56
LineCodeWhat it does
51
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
52
tr, te = scores(model, X_train, X_test)
๐Ÿงฎ Store / Calculate Calls our own function scores(model, X_train, X_test); the result is stored in variables tr, te
53
print(f"{'Set':<7}{'MAE':>8}{'RMSE':>8}{'R2':>8}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Set':<7}{'MAE':>8}{'RMSE':>8}{'R2':>8}" with the values filled into { } on the screen
54
print(f"{'Train':<7}{tr[0]:>8.2f}{tr[1]:>8.2f}{tr[2]:>8.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Train':<7}{tr[0]:>8.2f}{tr[1]:>8.2f}{tr[2โ€ฆ with the values filled into { } on the screen
55
print(f"{'Test':<7}{te[0]:>8.2f}{te[1]:>8.2f}{te[2]:>8.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Test':<7}{te[0]:>8.2f}{te[1]:>8.2f}{te[2]โ€ฆ with the values filled into { } on the screen
56
print("Small gap between train and test -> no overfitting.")
๐Ÿ–ฅ๏ธ Output Displays the text "Small gap between train and test โ€ฆ" on the screen
compare() - lines 59โ€“65
LineCodeWhat it does
59
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
60
m1 = LinearRegression().fit(X_train[["Area"]], y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model LinearRegression() on the given data; the result is stored in variable m1
61
s1 = scores(m1, X_train[["Area"]], X_test[["Area"]])[1]
๐Ÿงฎ Store / Calculate Stores the item scores(m1, X_train[["Area"]], X_test[["Area"]โ€ฆ in variable s1
62
s2 = scores(model, X_train, X_test)[1]
๐Ÿงฎ Store / Calculate Stores the item scores(model, X_train, X_test)[1] in variable s2
63
print(f"Area only    : test RMSE {s1[1]:.2f}, R2 {s1[2]:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Area only : test RMSE {s1[1]:.2f}, R2 {s1[2โ€ฆ with the values filled into { } on the screen
64
print(f"All features : test RMSE {s2[1]:.2f}, R2 {s2[2]:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"All features : test RMSE {s2[1]:.2f}, R2 {sโ€ฆ with the values filled into { } on the screen
65
print("More relevant features -> better predictions.")
๐Ÿ–ฅ๏ธ Output Displays the text "More relevant features -> better โ€ฆ" on the screen
predict() - lines 68โ€“75
LineCodeWhat it does
68
def predict():
๐Ÿงฉ Function DEFINES a function predict(). Python only remembers it here - its body runs later, each time predict() is called.
69
a = float(input("Area (sq ft)       : "))
โŒจ๏ธ Input Shows "Area (sq ft) : ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable a
70
if not 300 <= a <= 5000:
๐Ÿ”€ Decision CHECKS whether NOT 300 <= a <= 5000 is True. If True, the indented lines below run; otherwise they are skipped
71
print("Area must be 300-5000 sq ft.")
๐Ÿ–ฅ๏ธ Output Displays the text "Area must be 300-5000 sq ft." on the screen
72
return
๐Ÿงฉ Function Ends the function and goes back to the caller
73
b, g, m = int(input("Bedrooms           : ")), float(input("Age of building    : ")), float(input("Distance to metro  : "))
โŒจ๏ธ Input Stores int(input("Bedrooms : ")), float(input("Age of building : ")), float(input("Distance to metro : ")) into b, g, m respectively
74
p = model.predict(pd.DataFrame([[a, b, g, m]], columns=FEAT))[0]
๐Ÿ“ฆ Library / Data Stores the item model.predict(pd.DataFrame([[a, b, g, m]], coโ€ฆ in variable p
75
print(f"Estimated price: Rs. {p:.2f} lakh  (Rs. {p * 100000 / a:,.0f} per sq ft)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Estimated price: Rs. {p:.2f} lakh (Rs. {p *โ€ฆ with the values filled into { } on the screen
charts() - lines 78โ€“91
LineCodeWhat it does
78
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
79
pred = model.predict(X_test)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for X_test; the result is stored in variable pred
80
plt.scatter(y_test, pred, color="purple"); lim = [df.Price_lakh.min(), df.Price_lakh.max()]
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of y_test, pred
80
plt.scatter(y_test, pred, color="purple"); lim = [df.Price_lakh.min(), df.Price_lakh.max()]
๐Ÿ–ฅ๏ธ Output Stores a list [df.Price_lakh.min(), df.Price_lakh.max()] in variable lim
81
plt.plot(lim, lim, "k--", label="Perfect prediction")
๐Ÿ–ฅ๏ธ Output Draws a line chart of lim, lim, "k--"
82
plt.xlabel("Actual price (lakh)"); plt.ylabel("Predicted price (lakh)"); plt.title("Actual vs predicted (test data)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Actual price (lakh)" as the label of the X-axis
82
plt.xlabel("Actual price (lakh)"); plt.ylabel("Predicted price (lakh)"); plt.title("Actual vs predicted (test data)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Predicted price (lakh)" as the label of the Y-axis
82
plt.xlabel("Actual price (lakh)"); plt.ylabel("Predicted price (lakh)"); plt.title("Actual vs predicted (test data)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Actual vs predicted (test data)" as the title of the chart
82
plt.xlabel("Actual price (lakh)"); plt.ylabel("Predicted price (lakh)"); plt.title("Actual vs predicted (test data)"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
83
plt.savefig("house_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "house_pred.png"
83
plt.savefig("house_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
84
eff = model.coef_ * df[FEAT].std().values
๐Ÿงฎ Store / Calculate Stores the value of model.coef_ * df[FEAT].std().values (calculated using ร—) in variable eff
85
plt.barh(FEAT, eff, color=["green" if e > 0 else "red" for e in eff]); plt.axvline(0, color="k")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
85
plt.barh(FEAT, eff, color=["green" if e > 0 else "red" for e in eff]); plt.axvline(0, color="k")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
86
plt.title("Effect on price of 1 std change in each feature (lakh)")
๐Ÿ–ฅ๏ธ Output Writes "Effect on price of 1 std change in each featโ€ฆ as the title of the chart
87
plt.savefig("house_coef.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "house_coef.png"
87
plt.savefig("house_coef.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
plt.scatter(pred, y_test - pred, color="teal"); plt.axhline(0, color="red")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of pred, y_test - pred
88
plt.scatter(pred, y_test - pred, color="teal"); plt.axhline(0, color="red")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
89
plt.xlabel("Predicted"); plt.ylabel("Residual"); plt.title("Residual plot")
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the X-axis
89
plt.xlabel("Predicted"); plt.ylabel("Residual"); plt.title("Residual plot")
๐Ÿ–ฅ๏ธ Output Writes "Residual" as the label of the Y-axis
89
plt.xlabel("Predicted"); plt.ylabel("Residual"); plt.title("Residual plot")
๐Ÿ–ฅ๏ธ Output Writes "Residual plot" as the title of the chart
90
plt.savefig("house_residuals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "house_residuals.png"
90
plt.savefig("house_residuals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
91
print("Charts saved: house_pred.png, house_coef.png, house_residuals.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: house_pred.png, houโ€ฆ" on the screen
Q1. What is linear regression?

A supervised model that fits y = b0 + b1x1 + ... + bnxn to predict a continuous value.

Q2. What does a negative coefficient for Age mean?

Older buildings have lower predicted price, keeping other features same.

Q3. Difference between MAE and RMSE?

MAE is average absolute error; RMSE squares errors so big mistakes count more.

Q4. What is R2?

Proportion of variance in price explained by the model.

Q5. How do you detect overfitting?

Train score much better than test score.

03

Iris Flower Classifier using k-Nearest Neighbour

PYTHON + SKLEARNSDG 15 - Life on LandKNN classificationchoosing kaccuracy for different kconfusion matrixuser prediction
๐Ÿ“ 112 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 94 output lines๐Ÿ“„ 25+ page report

Classifies iris flowers into Setosa, Versicolor and Virginica with the KNN algorithm, tests k = 1 to 15 to find the best value, shows the confusion matrix and predicts the species of a flower measured by the user.

โœจ Features
  • Iris dataset (150 flowers, 4 measurements, 3 species) from scikit-learn
  • Stratified 70:30 train-test split
  • Choosing k: accuracy for k = 1 to 15 and best k
  • Confusion matrix and classification report (precision, recall, F1)
  • Prediction for a new flower with its k nearest neighbours and distances
  • Charts: k vs accuracy, petal scatter, confusion matrix
โ˜ฐ Main menu
1Explore DatasetShape, classes, feature means
2Find Best kAccuracy for k = 1..15
3Evaluate Best ModelConfusion matrix + report
4Predict New Flower4 measurements
5Neighbour DetailsDistances of k nearest flowers
6Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Train and evaluate a KNN classifier on the Iris dataset
  • Compare accuracy for different values of k and choose the best
  • Interpret the confusion matrix and make predictions
๐Ÿ“š Data dictionary
NameTypePurpose
irisBunchdata, target, names
scoreslistAccuracy for each k
best_kintk with highest accuracy
modelKNeighborsClassifierTrained classifier
Why it matters: Demonstrates the complete supervised classification workflow and the effect of the hyper-parameter k.
# =====================================================================
#   IRIS FLOWER CLASSIFIER USING k-NEAREST NEIGHBOUR
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=4, stratify=iris.target)
NAMES = ["Sepal length", "Sepal width", "Petal length", "Petal width"]
state = {}


def explore():
    print("Data shape:", iris.data.shape, "| classes:", [str(n) for n in iris.target_names])
    print("Training flowers:", len(X_train), " Test flowers:", len(X_test))
    for i, sp in enumerate(iris.target_names):
        m = iris.data[iris.target == i].mean(axis=0).round(2)
        print(f"  {sp:<11} mean " + ", ".join(f"{n} {v}" for n, v in zip(NAMES, m)))


def best_k():
    scores = []
    for k in range(1, 16):
        knn = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
        scores.append(accuracy_score(y_test, knn.predict(X_test)))
    for k, s in enumerate(scores, 1):
        print(f"k = {k:2} : {s * 100:6.2f} %  " + "#" * int(s * 30))
    state["scores"] = scores
    state["k"] = scores.index(max(scores)) + 1
    state["model"] = KNeighborsClassifier(n_neighbors=state["k"]).fit(X_train, y_train)
    print("Best k =", state["k"])


def evaluate():
    p = state["model"].predict(X_test)
    print("Accuracy:", round(accuracy_score(y_test, p) * 100, 2), "%")
    print("Confusion matrix (rows = actual setosa, versicolor, virginica):\n", confusion_matrix(y_test, p))
    print(classification_report(y_test, p, target_names=iris.target_names))


def read_flower():
    f = [float(input(n + ": ")) for n in NAMES]
    if min(f) <= 0:
        print("Measurements must be positive.")
        return None
    return f


def predict():
    f = read_flower()
    if f:
        pr = state["model"].predict_proba([f])[0]
        print("Predicted species:", iris.target_names[pr.argmax()].upper(), "| votes share:", {str(n): round(float(v), 2) for n, v in zip(iris.target_names, pr)})


def neighbours():
    f = read_flower()
    if f:
        dist, idx = state["model"].kneighbors([f])
        for d, i in zip(dist[0], idx[0]):
            print(f"  distance {d:.3f} -> {iris.target_names[y_train[i]]:<11} {X_train[i]}")


def charts():
    plt.plot(range(1, 16), [s * 100 for s in state["scores"]], marker="o")
    plt.xlabel("k (number of neighbours)"); plt.ylabel("Test accuracy (%)"); plt.title("Choosing k for KNN"); plt.grid(alpha=0.3)
    plt.savefig("knn_k.png", dpi=90, bbox_inches="tight"); plt.show()
    for i, c in zip(range(3), ["tab:red", "tab:green", "tab:blue"]):
        d = iris.data[iris.target == i]
        plt.scatter(d[:, 2], d[:, 3], c=c, s=20, label=iris.target_names[i])
    plt.xlabel("Petal length"); plt.ylabel("Petal width"); plt.title("Iris species by petal size"); plt.legend()
    plt.savefig("iris_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
    cm = confusion_matrix(y_test, state["model"].predict(X_test))
    plt.imshow(cm, cmap="Blues")
    for (i, j), v in np.ndenumerate(cm):
        plt.text(j, i, v, ha="center", va="center", fontsize=14)
    plt.xticks(range(3), iris.target_names); plt.yticks(range(3), iris.target_names)
    plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix (k = %d)" % state["k"])
    plt.savefig("iris_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: knn_k.png, iris_scatter.png, iris_confusion.png")


print("=" * 55)
print("   IRIS FLOWER CLASSIFIER (KNN)")
print("=" * 55)
while True:
    print("\n1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        explore()
    elif ch == "2":
        best_k()
    elif "model" not in state and ch in "3456":
        print("Find the best k first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        predict()
    elif ch == "5":
        neighbours()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Load iris and split
  3. Show menu and read choice
  4. Best k found? → No: compute scores for k=1..15
  5. Fit KNN with best k
  6. Predict / evaluate
  7. Show result
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Explore150 x 4, 3 classesPASS
2Best kAccuracy tablePASS
3EvaluateConfusion matrixPASS
4Predict 6.3, 2.9, 5.6, 1.8virginicaPASS
5Predict 5.0, 3.4, 1.5, 0.2setosaPASS
6Negative value'Measurements must be positive'PASS
7Charts3 PNG filesPASS
โš  Limitations
  • Small classic dataset
  • KNN is slow for very large data
  • Features not scaled (similar units here)
  • Only 3 species
๐Ÿš€ Future scope
  • Use scaling and cross-validation
  • Classify flower images with CNN
  • Deploy as a mobile app
  • Try decision tree and compare

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, load_iris, train_test_split, KNeighborsClassifier, accuracy_score, confusion_matrix, classification_report are loaded.
  2. Global variables / constants are created: iris, NAMES, state.
  3. 7 functions are defined (lines 17โ€“84) - Python stores them but does NOT run them yet.
  4. Main program starts at line 12: X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.ta - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
explore()17โ€“22Exploremain program
best_k()25โ€“35Best kmain program
evaluate()38โ€“42Evaluatemain program
read_flower()45โ€“50Read flowerpredict(), neighbours()
predict()53โ€“57Predictmain program
neighbours()60โ€“65Neighboursmain program
charts()68โ€“84Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
12
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=4, stratify=iris.target)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (30% for testing) and stores them in X_train, X_test, y_train, y_test
13
NAMES = ["Sepal length", "Sepal width", "Petal length", "Petal width"]
๐Ÿงฎ Store / Calculate Stores a list ["Sepal length", "Sepal width", "Petal lengthโ€ฆ in variable NAMES
14
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
87
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
88
print("   IRIS FLOWER CLASSIFIER (KNN)")
๐Ÿ–ฅ๏ธ Output Displays the text "IRIS FLOWER CLASSIFIER (KNN)" on the screen
89
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
90
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
91
print("\n1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Explore 2.Best k 3.Evaluate 4.Pโ€ฆ" on the screen
92
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
93
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
94
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
95
break
๐Ÿ” Loop BREAK - leaves the loop immediately
96
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
97
explore()
๐Ÿงฎ Store / Calculate Calls our own function explore()
98
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
99
best_k()
๐Ÿงฎ Store / Calculate Calls our own function best_k()
100
elif "model" not in state and ch in "3456":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "3456")
101
print("Find the best k first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Find the best k first (option 2)." on the screen
102
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
103
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
104
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
105
predict()
๐Ÿงฎ Store / Calculate Calls our own function predict()
106
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
107
neighbours()
๐Ÿงฎ Store / Calculate Calls our own function neighbours()
108
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
109
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
110
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
111
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: IRIS FLOWER CLASSIFIER (KNN) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Find the best k first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: explore()
    shows: Data shape: (150, 4) | classes: ['setosa', 'versicolor', 'virginica'] (+5 more lines)
  4. You type 2 at Enter choice:
    runs: best_k()
    shows: k = 1 : 95.56 % ############################ (+16 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate()
    shows: Accuracy: 97.78 % (+12 more lines)
  6. You type 4 at Enter choice:
    runs: predict() โ†’ read_flower()
  7. You type 6.3 at Sepal length:
  8. You type 2.9 at Sepal width:
  9. You type 5.6 at Petal length:
  10. You type 1.8 at Petal width:
    shows: Predicted species: VIRGINICA | votes share: {'setosa': 0.0, 'versicolor': 0.0, 'virginica' (+1 more lines)
  11. You type 4 at Enter choice:
    runs: predict() โ†’ read_flower()
  12. You type 5.0 at Sepal length:
  13. You type 3.4 at Sepal width:
  14. You type 1.5 at Petal length:
  15. You type 0.2 at Petal width:
    shows: Predicted species: SETOSA | votes share: {'setosa': 1.0, 'versicolor': 0.0, 'virginica': 0 (+1 more lines)
  16. You type 4 at Enter choice:
    runs: predict() โ†’ read_flower()
  17. You type -1 at Sepal length:
  18. You type 2 at Sepal width:
  19. You type 3 at Petal length:
  20. You type 4 at Petal width:
    shows: Measurements must be positive. (+1 more lines)
  21. You type 5 at Enter choice:
    runs: neighbours() โ†’ read_flower()
  22. You type 6.3 at Sepal length:
  23. You type 2.9 at Sepal width:
  24. You type 5.6 at Petal length:
  25. You type 1.8 at Petal width:
    shows: distance 0.000 -> virginica [6.3 2.9 5.6 1.8] (+3 more lines)
  26. You type 6 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  27. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
explore() - lines 17โ€“22
LineCodeWhat it does
17
def explore():
๐Ÿงฉ Function DEFINES a function explore(). Python only remembers it here - its body runs later, each time explore() is called.
18
print("Data shape:", iris.data.shape, "| classes:", [str(n) for n in iris.target_names])
๐Ÿ–ฅ๏ธ Output Displays the text "Data shape:", then the value of iris.data.shape, then the text "| classes:", then the value of [str(n) for n in iris.target_names] on the screen
19
print("Training flowers:", len(X_train), " Test flowers:", len(X_test))
๐Ÿ–ฅ๏ธ Output Displays the text "Training flowers:", then the value of len(X_train), then the text "Test flowers:", then the value of len(X_test) on the screen
20
for i, sp in enumerate(iris.target_names):
๐Ÿ” Loop LOOP over iris.target_names with position: in each round i, sp get (position, item)
21
m = iris.data[iris.target == i].mean(axis=0).round(2)
๐Ÿงฎ Store / Calculate Rounds the values of iris.data[iris.target == i].mean(axis=0) to 2 decimal places; the result is stored in variable m
22
print(f"  {sp:<11} mean " + ", ".join(f"{n} {v}" for n, v in zip(NAMES, m)))
๐Ÿ–ฅ๏ธ Output Displays the value of f" {sp:<11} mean " + ", ".join(f"{n} {v}" forโ€ฆ on the screen
best_k() - lines 25โ€“35
LineCodeWhat it does
25
def best_k():
๐Ÿงฉ Function DEFINES a function best_k(). Python only remembers it here - its body runs later, each time best_k() is called.
26
scores = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable scores
27
for k in range(1, 16):
๐Ÿ” Loop LOOP: gives the numbers 1 to 15; for each number, k takes that value and the indented block runs once
28
knn = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model KNeighborsClassifier(n_neighbors=k) on the given data; the result is stored in variable knn
29
scores.append(accuracy_score(y_test, knn.predict(X_test)))
๐Ÿ“ฆ Library / Data Adds accuracy_score(y_test, knn.predict(X_test)) at the end of list scores
30
for k, s in enumerate(scores, 1):
๐Ÿ” Loop LOOP over scores with position: in each round k, s get (position, item)
31
print(f"k = {k:2} : {s * 100:6.2f} %  " + "#" * int(s * 30))
๐Ÿ–ฅ๏ธ Output Displays the value of f"k = {k:2} : {s * 100:6.2f} % " + "#" * int(โ€ฆ on the screen
32
state["scores"] = scores
๐Ÿงฎ Store / Calculate Puts the value of scores into state["scores"] (item "scores" of state)
33
state["k"] = scores.index(max(scores)) + 1
๐Ÿงฎ Store / Calculate Puts the value of scores.index(max(scores)) + 1 (calculated using +) into state["k"] (item "k" of state)
34
state["model"] = KNeighborsClassifier(n_neighbors=state["k"]).fit(X_train, y_train)
๐Ÿ“ฆ Library / Data Trains (fits) the model KNeighborsClassifier(n_neighbors=state["k"]) on the given data; the result is put into state["model"] (item "model" of state)
35
print("Best k =", state["k"])
๐Ÿ–ฅ๏ธ Output Displays the text "Best k =", then the value of state["k"] on the screen
evaluate() - lines 38โ€“42
LineCodeWhat it does
38
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
39
p = state["model"].predict(X_test)
๐Ÿ“ฆ Library / Data Uses the trained model state["model"] to predict answers for X_test; the result is stored in variable p
40
print("Accuracy:", round(accuracy_score(y_test, p) * 100, 2), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Accuracy:", then the value of round(accuracy_score(y_test, p) * 100, 2), then the text "%" on the screen
41
print("Confusion matrix (rows = actual setosa, versicolor, virginica):\n", confusion_matrix(y_test, p))
๐Ÿ–ฅ๏ธ Output Displays the text "Confusion matrix (rows = actual sโ€ฆ", then the value of confusion_matrix(y_test, p) on the screen
42
print(classification_report(y_test, p, target_names=iris.target_names))
๐Ÿ–ฅ๏ธ Output Displays the value of classification_report(y_test, p, target_namesโ€ฆ on the screen
read_flower() - lines 45โ€“50
LineCodeWhat it does
45
def read_flower():
๐Ÿงฉ Function DEFINES a function read_flower(). Python only remembers it here - its body runs later, each time read_flower() is called.
46
f = [float(input(n + ": ")) for n in NAMES]
โŒจ๏ธ Input Stores a new list made by a list comprehension [float(input(n + ": ")) for n in NAMES] in variable f
47
if min(f) <= 0:
๐Ÿ”€ Decision CHECKS whether min(f) is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
48
print("Measurements must be positive.")
๐Ÿ–ฅ๏ธ Output Displays the text "Measurements must be positive." on the screen
49
return None
๐Ÿงฉ Function Sends back (returns) None (nothing) to the line that called the function
50
return f
๐Ÿงฉ Function Sends back (returns) the value of f to the line that called the function
predict() - lines 53โ€“57
LineCodeWhat it does
53
def predict():
๐Ÿงฉ Function DEFINES a function predict(). Python only remembers it here - its body runs later, each time predict() is called.
54
f = read_flower()
๐Ÿงฎ Store / Calculate Calls our own function read_flower(); the result is stored in variable f
55
if f:
๐Ÿ”€ Decision CHECKS whether f is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
56
pr = state["model"].predict_proba([f])[0]
๐Ÿงฎ Store / Calculate Stores the item state["model"].predict_proba([f])[0] in variable pr
57
print("Predicted species:", iris.target_names[pr.argmax()].upper(), "| votes share:", {str(n): round(float(v), 2) for n, v in zip(iris.target_names, pr)})
๐Ÿ–ฅ๏ธ Output Displays the text "Predicted species:", then the value of iris.target_names[pr.argmax()].upper(), then the text "| votes share:", then the value of {str(n): round(float(v), 2) for n, v in zip(iโ€ฆ on the screen
neighbours() - lines 60โ€“65
LineCodeWhat it does
60
def neighbours():
๐Ÿงฉ Function DEFINES a function neighbours(). Python only remembers it here - its body runs later, each time neighbours() is called.
61
f = read_flower()
๐Ÿงฎ Store / Calculate Calls our own function read_flower(); the result is stored in variable f
62
if f:
๐Ÿ”€ Decision CHECKS whether f is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
63
dist, idx = state["model"].kneighbors([f])
๐Ÿงฎ Store / Calculate Finds the nearest neighbours; the result is stored in variables dist, idx
64
for d, i in zip(dist[0], idx[0]):
๐Ÿ” Loop LOOP that walks through dist[0], idx[0] together; d, i get one item from each
65
print(f"  distance {d:.3f} -> {iris.target_names[y_train[i]]:<11} {X_train[i]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" distance {d:.3f} -> {iris.target_names[y_tโ€ฆ with the values filled into { } on the screen
charts() - lines 68โ€“84
LineCodeWhat it does
68
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
69
plt.plot(range(1, 16), [s * 100 for s in state["scores"]], marker="o")
๐Ÿ–ฅ๏ธ Output Draws a line chart of range(1, 16), [s * 100 for s in state["scores"]]
70
plt.xlabel("k (number of neighbours)"); plt.ylabel("Test accuracy (%)"); plt.title("Choosing k for KNN"); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "k (number of neighbours)" as the label of the X-axis
70
plt.xlabel("k (number of neighbours)"); plt.ylabel("Test accuracy (%)"); plt.title("Choosing k for KNN"); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Test accuracy (%)" as the label of the Y-axis
70
plt.xlabel("k (number of neighbours)"); plt.ylabel("Test accuracy (%)"); plt.title("Choosing k for KNN"); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Choosing k for KNN" as the title of the chart
70
plt.xlabel("k (number of neighbours)"); plt.ylabel("Test accuracy (%)"); plt.title("Choosing k for KNN"); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
71
plt.savefig("knn_k.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "knn_k.png"
71
plt.savefig("knn_k.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
72
for i, c in zip(range(3), ["tab:red", "tab:green", "tab:blue"]):
๐Ÿ” Loop LOOP that walks through range(3), ["tab:red", "tab:green", "tab:blue"] together; i, c get one item from each
73
d = iris.data[iris.target == i]
๐Ÿงฎ Store / Calculate Stores the item iris.data[iris.target == i] in variable d
74
plt.scatter(d[:, 2], d[:, 3], c=c, s=20, label=iris.target_names[i])
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of d[:, 2], d[:, 3]
75
plt.xlabel("Petal length"); plt.ylabel("Petal width"); plt.title("Iris species by petal size"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Petal length" as the label of the X-axis
75
plt.xlabel("Petal length"); plt.ylabel("Petal width"); plt.title("Iris species by petal size"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Petal width" as the label of the Y-axis
75
plt.xlabel("Petal length"); plt.ylabel("Petal width"); plt.title("Iris species by petal size"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Iris species by petal size" as the title of the chart
75
plt.xlabel("Petal length"); plt.ylabel("Petal width"); plt.title("Iris species by petal size"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
76
plt.savefig("iris_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "iris_scatter.png"
76
plt.savefig("iris_scatter.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
77
cm = confusion_matrix(y_test, state["model"].predict(X_test))
๐Ÿ“ฆ Library / Data Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
78
plt.imshow(cm, cmap="Blues")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
79
for (i, j), v in np.ndenumerate(cm):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(cm) one-by-one into (i, j), v and runs the indented block for it
80
plt.text(j, i, v, ha="center", va="center", fontsize=14)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
81
plt.xticks(range(3), iris.target_names); plt.yticks(range(3), iris.target_names)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
81
plt.xticks(range(3), iris.target_names); plt.yticks(range(3), iris.target_names)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
82
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix (k = %d)" % state["k"])
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the X-axis
82
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix (k = %d)" % state["k"])
๐Ÿ–ฅ๏ธ Output Writes "Actual" as the label of the Y-axis
82
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix (k = %d)" % state["k"])
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix (k = %d)" % state["k"] as the title of the chart
83
plt.savefig("iris_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "iris_confusion.png"
83
plt.savefig("iris_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
84
print("Charts saved: knn_k.png, iris_scatter.png, iris_confusion.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: knn_k.png, iris_scaโ€ฆ" on the screen
Q1. How does KNN classify?

It finds the k closest training points (distance) and takes the majority class.

Q2. Why is k chosen odd?

To avoid ties in voting between two classes.

Q3. What is stratify in train_test_split?

Keeps the same class proportion in train and test sets.

Q4. Is KNN supervised?

Yes - it uses labelled training data.

Q5. What is precision vs recall?

Precision: correct among predicted positive; recall: found among actual positive.

04

Customer Segmentation using k-Means Clustering (SDG 8)

PYTHON + SKLEARNSDG 8 - Decent Work and Economic GrowthUnsupervised learningk-Meanselbow method (inertia)feature scalingcluster profiling
๐Ÿ“ 118 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 96 output lines๐Ÿ“„ 25+ page report

Groups customers of a local store by annual income and spending score using k-Means clustering, uses the elbow method to choose the number of clusters and describes each segment so the shopkeeper can plan targeted offers.

โœจ Features
  • 60 customers with annual income and spending score (sample mall data)
  • Features standardised with StandardScaler
  • Elbow method: inertia for k = 1 to 8
  • k-Means clustering with k = 4 and cluster profile (size, average income, spending)
  • Business name and marketing action for every segment
  • Assign a new customer to a segment; 3 charts
โ˜ฐ Main menu
1View DataFirst rows and statistics
2Elbow MethodInertia for k = 1..8
3Cluster (k=4)Fit k-Means and profile
4Marketing ActionsAction per segment
5New CustomerPredict segment
6Try Another kProfile with chosen k
7ChartsClusters, elbow, sizes
0ExitEnds program
๐ŸŽฏ Objectives
  • Scale features and apply k-Means clustering
  • Select the number of clusters using the elbow method
  • Profile each cluster and suggest business actions
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameIncome_k, Spending, Cluster
scalerStandardScalerFitted scaler
kmKMeansFitted model
profDataFrameCluster profile with segment names
Why it matters: Shows how unsupervised learning finds hidden groups without labels - widely used in marketing and banking.
# =====================================================================
#   CUSTOMER SEGMENTATION USING k-MEANS CLUSTERING   (SDG 8)
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(5)
groups = [(25, 20), (25, 80), (80, 20), (80, 82)]
df = pd.DataFrame(np.vstack([rng.normal(c, (6, 7), (15, 2)) for c in groups]).round(1), columns=["Income_k", "Spending"])
scaler = StandardScaler().fit(df[["Income_k", "Spending"]])
X = scaler.transform(df[["Income_k", "Spending"]])
ACTIONS = {"Premium customers": "loyalty card, new arrivals preview", "Careful savers": "quality & warranty offers",
           "Impulse buyers": "festival combos, easy EMI", "Budget shoppers": "discount coupons, value packs"}
state = {}


def seg_name(inc, sp):
    return {(True, True): "Premium customers", (True, False): "Careful savers",
            (False, True): "Impulse buyers", (False, False): "Budget shoppers"}[(inc > 50, sp > 50)]


def view():
    print(df.head(8))
    print("\nCustomers:", len(df))
    print(df.describe().round(1))


def elbow():
    inert = []
    for k in range(1, 9):
        inert.append(KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_)
        print(f"k = {k} : inertia {inert[-1]:7.1f}  " + "#" * int(inert[-1] / 4))
    state["inertia"] = inert
    print("The curve bends at k = 4 -> choose 4 clusters.")


def profile(k):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    d = df.copy()
    d["Cluster"] = km.labels_
    prof = d.groupby("Cluster").agg(Customers=("Income_k", "size"), Avg_income=("Income_k", "mean"), Avg_spending=("Spending", "mean")).round(1)
    prof["Segment"] = [seg_name(r.Avg_income, r.Avg_spending) for r in prof.itertuples()]
    return km, d, prof


def cluster():
    km, d, prof = profile(4)
    state.update(km=km, d=d, prof=prof)
    print(prof.to_string())


def actions():
    for s in state["prof"].Segment:
        print(f" - {s:<18} -> {ACTIONS[s]}")


def new_customer():
    inc, sp = float(input("Annual income (thousand Rs): ")), float(input("Spending score (1-100): "))
    c = state["km"].predict(scaler.transform(pd.DataFrame([[inc, sp]], columns=["Income_k", "Spending"])))[0]
    seg = state["prof"].loc[c, "Segment"]
    print(f"Customer belongs to cluster {c}: {seg} -> {ACTIONS[seg]}")


def try_k():
    k = int(input("Number of clusters k (2-8): "))
    if not 2 <= k <= 8:
        print("k must be 2-8.")
        return
    print(profile(k)[2].to_string())


def charts():
    d = state["d"]
    plt.scatter(d.Income_k, d.Spending, c=d.Cluster, cmap="tab10", s=40)
    cen = scaler.inverse_transform(state["km"].cluster_centers_)
    plt.scatter(cen[:, 0], cen[:, 1], marker="X", s=250, c="black", label="Centres")
    plt.xlabel("Annual income (thousand Rs)"); plt.ylabel("Spending score (1-100)"); plt.title("Customer segments found by k-Means"); plt.legend()
    plt.savefig("kmeans_segments.png", dpi=90, bbox_inches="tight"); plt.show()
    if "inertia" not in state:
        state["inertia"] = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_ for k in range(1, 9)]
    plt.plot(range(1, 9), state["inertia"], "o-"); plt.axvline(4, ls="--", c="red")
    plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
    state["prof"].set_index("Segment").Customers.plot(kind="bar", color="#845ef7", title="Customers per segment")
    plt.xticks(rotation=15); plt.savefig("segment_sizes.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: kmeans_segments.png, kmeans_elbow.png, segment_sizes.png")


print("=" * 55)
print("   CUSTOMER SEGMENTATION  (k-Means)")
print("=" * 55)
while True:
    print("\n1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        view()
    elif ch == "2":
        elbow()
    elif ch == "3":
        cluster()
    elif "km" not in state and ch in "4567":
        print("Run clustering first (option 3).")
    elif ch == "4":
        actions()
    elif ch == "5":
        new_customer()
    elif ch == "6":
        try_k()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create customer data and scale
  3. Show menu and read choice
  4. Clustered? → No: fit k-Means
  5. Profile clusters and name segments
  6. Show profile / segment
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1ElbowInertia drops sharply till k = 4PASS
2Cluster4 segments of ~15PASS
3Actions4 actionsPASS
4New customer 85, 90Premium customersPASS
5New customer 20, 15Budget shoppersPASS
6k = 22-cluster profilePASS
7k = 1'k must be 2-8'PASS
โš  Limitations
  • Synthetic data
  • Only 2 features
  • k chosen manually
  • Clusters change if data changes
๐Ÿš€ Future scope
  • Add age, visits, online orders
  • Use real POS data
  • Hierarchical clustering
  • Dashboard for the store manager

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, KMeans, StandardScaler are loaded.
  2. Global variables / constants are created: rng, groups, df, scaler, X, ACTIONS, state.
  3. 9 functions are defined (lines 20โ€“88) - Python stores them but does NOT run them yet.
  4. Main program starts at line 91: print("=" * 55) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
seg_name(inc, sp)20โ€“22Seg nameprofile()
view()25โ€“28Viewmain program
elbow()31โ€“37Elbowmain program
profile(k)40โ€“46Profilecluster(), try_k()
cluster()49โ€“52Clustermain program
actions()55โ€“57Actionsmain program
new_customer()60โ€“64New customermain program
try_k()67โ€“72Try kmain program
charts()75โ€“88Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
91
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
92
print("   CUSTOMER SEGMENTATION  (k-Means)")
๐Ÿ–ฅ๏ธ Output Displays the text "CUSTOMER SEGMENTATION (k-Means)" on the screen
93
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
94
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
95
print("\n1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Elbow 3.Cluster 4.Actionโ€ฆ" on the screen
96
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
97
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
98
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
99
break
๐Ÿ” Loop BREAK - leaves the loop immediately
100
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
101
view()
๐Ÿงฎ Store / Calculate Calls our own function view()
102
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
103
elbow()
๐Ÿงฎ Store / Calculate Calls our own function elbow()
104
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
105
cluster()
๐Ÿงฎ Store / Calculate Calls our own function cluster()
106
elif "km" not in state and ch in "4567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("km" is not present in state AND ch is present in "4567")
107
print("Run clustering first (option 3).")
๐Ÿ–ฅ๏ธ Output Displays the text "Run clustering first (option 3)." on the screen
108
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
109
actions()
๐Ÿงฎ Store / Calculate Calls our own function actions()
110
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
111
new_customer()
๐Ÿงฎ Store / Calculate Calls our own function new_customer()
112
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
113
try_k()
๐Ÿงฎ Store / Calculate Calls our own function try_k()
114
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
115
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
116
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
117
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CUSTOMER SEGMENTATION (k-Means) (+1 more lines)
  2. You type 3 at Enter choice:
    runs: cluster() โ†’ profile() โ†’ seg_name() ร—4
    shows: Customers Avg_income Avg_spending Segment (+6 more lines)
  3. You type 1 at Enter choice:
    runs: view()
    shows: Income_k Spending (+19 more lines)
  4. You type 2 at Enter choice:
    runs: elbow()
    shows: k = 1 : inertia 120.0 ############################## (+9 more lines)
  5. You type 3 at Enter choice:
    runs: cluster() โ†’ profile() โ†’ seg_name() ร—4
    shows: Customers Avg_income Avg_spending Segment (+6 more lines)
  6. You type 4 at Enter choice:
    runs: actions()
    shows: - Careful savers -> quality & warranty offers (+4 more lines)
  7. You type 5 at Enter choice:
    runs: new_customer()
  8. You type 85 at Annual income (thousand Rs):
  9. You type 90 at Spending score (1-100):
    shows: Customer belongs to cluster 3: Premium customers -> loyalty card, new arrivals preview (+1 more lines)
  10. You type 5 at Enter choice:
    runs: new_customer()
  11. You type 20 at Annual income (thousand Rs):
  12. You type 15 at Spending score (1-100):
    shows: Customer belongs to cluster 2: Budget shoppers -> discount coupons, value packs (+1 more lines)
  13. You type 6 at Enter choice:
    runs: try_k()
  14. You type 2 at Number of clusters k (2-8):
    runs: profile() โ†’ seg_name() ร—2
    shows: Customers Avg_income Avg_spending Segment (+4 more lines)
  15. You type 6 at Enter choice:
    runs: try_k()
  16. You type 1 at Number of clusters k (2-8):
    shows: k must be 2-8. (+1 more lines)
  17. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  18. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
seg_name() - lines 20โ€“22
LineCodeWhat it does
20
def seg_name(inc, sp):
๐Ÿงฉ Function DEFINES a function seg_name(inc, sp). Python only remembers it here - its body runs later, each time seg_name() is called.
21
return {(True, True): "Premium customers", (True, False): "Careful savers",
        (False, True): "Impulse buyers", (False, False): "Budget shoppers"}[(inc โ€ฆ
๐Ÿงฉ Function Sends back (returns) the item {(True, True): "Premium customers", (True, Faโ€ฆ to the line that called the function
view() - lines 25โ€“28
LineCodeWhat it does
25
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
26
print(df.head(8))
๐Ÿ–ฅ๏ธ Output Displays the value of df.head(8) on the screen
27
print("\nCustomers:", len(df))
๐Ÿ–ฅ๏ธ Output Displays the text "Customers:", then the value of len(df) on the screen
28
print(df.describe().round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of df.describe().round(1) on the screen
elbow() - lines 31โ€“37
LineCodeWhat it does
31
def elbow():
๐Ÿงฉ Function DEFINES a function elbow(). Python only remembers it here - its body runs later, each time elbow() is called.
32
inert = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable inert
33
for k in range(1, 9):
๐Ÿ” Loop LOOP: gives the numbers 1 to 8; for each number, k takes that value and the indented block runs once
34
inert.append(KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_)
๐Ÿ“ฆ Library / Data Adds KMeans(n_clusters=k, n_init=10, random_state=โ€ฆ at the end of list inert
35
print(f"k = {k} : inertia {inert[-1]:7.1f}  " + "#" * int(inert[-1] / 4))
๐Ÿ–ฅ๏ธ Output Displays the value of f"k = {k} : inertia {inert[-1]:7.1f} " + "#" โ€ฆ on the screen
36
state["inertia"] = inert
๐Ÿงฎ Store / Calculate Puts the value of inert into state["inertia"] (item "inertia" of state)
37
print("The curve bends at k = 4 -> choose 4 clusters.")
๐Ÿ–ฅ๏ธ Output Displays the text "The curve bends at k = 4 -> choosโ€ฆ" on the screen
profile() - lines 40โ€“46
LineCodeWhat it does
40
def profile(k):
๐Ÿงฉ Function DEFINES a function profile(k). Python only remembers it here - its body runs later, each time profile() is called.
41
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
๐Ÿ“ฆ Library / Data Trains (fits) the model KMeans(n_clusters=k, n_init=10, random_state=โ€ฆ on the given data; the result is stored in variable km
42
d = df.copy()
๐Ÿ“ฆ Library / Data Makes a copy of df; the result is stored in variable d
43
d["Cluster"] = km.labels_
๐Ÿงฎ Store / Calculate Puts km.labels_ into d["Cluster"] (item "Cluster" of d)
44
prof = d.groupby("Cluster").agg(Customers=("Income_k", "size"), Avg_income=("Income_k", "mean"), Avg_spending=("Spending", "mean")).round(1)
๐Ÿงฎ Store / Calculate Rounds the values of d.groupby("Cluster").agg(Customers=("Income_kโ€ฆ to 1 decimal places; the result is stored in variable prof
45
prof["Segment"] = [seg_name(r.Avg_income, r.Avg_spending) for r in prof.itertuples()]
๐Ÿงฎ Store / Calculate Puts a new list made by a list comprehension [seg_name(r.Avg_income, r.Avg_spending) for rโ€ฆ into prof["Segment"] (item "Segment" of prof)
46
return km, d, prof
๐Ÿงฉ Function Sends back (returns) the tuple km, d, prof to the line that called the function
cluster() - lines 49โ€“52
LineCodeWhat it does
49
def cluster():
๐Ÿงฉ Function DEFINES a function cluster(). Python only remembers it here - its body runs later, each time cluster() is called.
50
km, d, prof = profile(4)
๐Ÿงฎ Store / Calculate Calls our own function profile(4); the result is stored in variables km, d, prof
51
state.update(km=km, d=d, prof=prof)
๐Ÿงฎ Store / Calculate Updates state with
52
print(prof.to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of prof.to_string() on the screen
actions() - lines 55โ€“57
LineCodeWhat it does
55
def actions():
๐Ÿงฉ Function DEFINES a function actions(). Python only remembers it here - its body runs later, each time actions() is called.
56
for s in state["prof"].Segment:
๐Ÿ” Loop LOOP: takes each item of state["prof"].Segment one-by-one into s and runs the indented block for it
57
print(f" - {s:<18} -> {ACTIONS[s]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" - {s:<18} -> {ACTIONS[s]}" with the values filled into { } on the screen
new_customer() - lines 60โ€“64
LineCodeWhat it does
60
def new_customer():
๐Ÿงฉ Function DEFINES a function new_customer(). Python only remembers it here - its body runs later, each time new_customer() is called.
61
inc, sp = float(input("Annual income (thousand Rs): ")), float(input("Spending score (1-100): "))
โŒจ๏ธ Input Stores float(input("Annual income (thousand Rs): ")), float(input("Spending score (1-100): ")) into inc, sp respectively
62
c = state["km"].predict(scaler.transform(pd.DataFrame([[inc, sp]], columns=["Income_k", "Spending"])))[0]
๐Ÿ“ฆ Library / Data Stores the item state["km"].predict(scaler.transform(pd.DataFโ€ฆ in variable c
63
seg = state["prof"].loc[c, "Segment"]
๐Ÿงฎ Store / Calculate Stores the item state["prof"].loc[c, "Segment"] in variable seg
64
print(f"Customer belongs to cluster {c}: {seg} -> {ACTIONS[seg]}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Customer belongs to cluster {c}: {seg} -> {โ€ฆ with the values filled into { } on the screen
try_k() - lines 67โ€“72
LineCodeWhat it does
67
def try_k():
๐Ÿงฉ Function DEFINES a function try_k(). Python only remembers it here - its body runs later, each time try_k() is called.
68
k = int(input("Number of clusters k (2-8): "))
โŒจ๏ธ Input Shows "Number of clusters k (2-8): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable k
69
if not 2 <= k <= 8:
๐Ÿ”€ Decision CHECKS whether NOT 2 <= k <= 8 is True. If True, the indented lines below run; otherwise they are skipped
70
print("k must be 2-8.")
๐Ÿ–ฅ๏ธ Output Displays the text "k must be 2-8." on the screen
71
return
๐Ÿงฉ Function Ends the function and goes back to the caller
72
print(profile(k)[2].to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of profile(k)[2].to_string() on the screen
charts() - lines 75โ€“88
LineCodeWhat it does
75
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
76
d = state["d"]
๐Ÿงฎ Store / Calculate Stores the item state["d"] in variable d
77
plt.scatter(d.Income_k, d.Spending, c=d.Cluster, cmap="tab10", s=40)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of d.Income_k, d.Spending
78
cen = scaler.inverse_transform(state["km"].cluster_centers_)
๐Ÿงฎ Store / Calculate Converts scaled values back; the result is stored in variable cen
79
plt.scatter(cen[:, 0], cen[:, 1], marker="X", s=250, c="black", label="Centres")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of cen[:, 0], cen[:, 1]
80
plt.xlabel("Annual income (thousand Rs)"); plt.ylabel("Spending score (1-100)"); plt.title("Customer segments found by k-Means"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Annual income (thousand Rs)" as the label of the X-axis
80
plt.xlabel("Annual income (thousand Rs)"); plt.ylabel("Spending score (1-100)"); plt.title("Customer segments found by k-Means"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Spending score (1-100)" as the label of the Y-axis
80
plt.xlabel("Annual income (thousand Rs)"); plt.ylabel("Spending score (1-100)"); plt.title("Customer segments found by k-Means"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Customer segments found by k-Means" as the title of the chart
80
plt.xlabel("Annual income (thousand Rs)"); plt.ylabel("Spending score (1-100)"); plt.title("Customer segments found by k-Means"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
81
plt.savefig("kmeans_segments.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "kmeans_segments.png"
81
plt.savefig("kmeans_segments.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
if "inertia" not in state:
๐Ÿ”€ Decision CHECKS whether "inertia" is not present in state. If True, the indented lines below run; otherwise they are skipped
83
state["inertia"] = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_ for k in range(1, 9)]
๐Ÿ“ฆ Library / Data Puts a new list made by a list comprehension [KMeans(n_clusters=k, n_init=10, random_stateโ€ฆ into state["inertia"] (item "inertia" of state)
84
plt.plot(range(1, 9), state["inertia"], "o-"); plt.axvline(4, ls="--", c="red")
๐Ÿ–ฅ๏ธ Output Draws a line chart of range(1, 9), state["inertia"], "o-"
84
plt.plot(range(1, 9), state["inertia"], "o-"); plt.axvline(4, ls="--", c="red")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
85
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "k" as the label of the X-axis
85
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Inertia" as the label of the Y-axis
85
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Elbow method" as the title of the chart
85
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "kmeans_elbow.png"
85
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method"); plt.savefig("kmeans_elbow.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
86
state["prof"].set_index("Segment").Customers.plot(kind="bar", color="#845ef7", title="Customers per segment")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
87
plt.xticks(rotation=15); plt.savefig("segment_sizes.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
87
plt.xticks(rotation=15); plt.savefig("segment_sizes.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "segment_sizes.png"
87
plt.xticks(rotation=15); plt.savefig("segment_sizes.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
88
print("Charts saved: kmeans_segments.png, kmeans_elbow.png, segment_sizes.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: kmeans_segments.pngโ€ฆ" on the screen
Q1. Is k-Means supervised?

No - it is unsupervised; it groups data without labels.

Q2. What is inertia?

Sum of squared distances of points to their cluster centre; lower is tighter.

Q3. What is the elbow method?

Plot inertia vs k and choose k where the decrease slows down (the elbow).

Q4. Why scale features?

So income and spending have equal influence on distance.

Q5. Which SDG?

SDG 8 - Decent Work and Economic Growth (helping businesses).

05

Ice-Cream Ordering Chatbot with Intent Matching

PYTHONSDG 8 - Decent Work and Economic Growth (small business)NLP preprocessingintents and entitiesdictionariesslot fillingorder summary and bill
๐Ÿ“ 94 lines of codeโ˜ฐ 1 menu options๐Ÿ–ฅ๏ธ 53 output lines๐Ÿ“„ 25+ page report

Python version of the CBSE ice-cream ordering chatbot: understands greetings, menu requests, orders with flavour, size and quantity (entities), asks for missing details (slot filling), cancels orders and prints the final bill.

โœจ Features
  • Chatbot with intents (greet, menu, order, cancel, bill, offers, timing, bye)
  • Entity extraction: flavour, size and quantity (digits or words) from a sentence
  • Slot filling: asks for missing size
  • Cart with modify / cancel and GST bill
  • Offer rule: buy 3 or more scoops get 10 % off
  • Conversation log and order summary saved to orders.txt
โ˜ฐ Main menu
-Chat commandshi, menu, order sentence, cancel <flavour>, offers, timing, bill, bye
๐ŸŽฏ Objectives
  • Preprocess user messages (lower case, remove punctuation, tokens)
  • Detect intents and extract entities using dictionaries
  • Implement slot filling and generate an itemised bill
๐Ÿ“š Data dictionary
NameTypePurpose
MENUdictflavour -> price (small)
SIZEdictsize -> price multiplier
NUMdictnumber words -> int
cartlist(flavour, size, qty)
orders.txttext fileSaved bill
Why it matters: Shows how intents, entities and slot filling - the ideas behind Dialogflow - work under the hood.
# =====================================================================
#   ICE-CREAM ORDERING CHATBOT  (intents, entities, slot filling)
# =====================================================================
import string

MENU = {"chocolate": 60, "vanilla": 50, "mango": 55, "butterscotch": 65, "strawberry": 55}
SIZE = {"small": 1.0, "medium": 1.4, "large": 1.8}
NUM = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "a": 1}
INTENTS = {"greet": ["hi", "hello", "hey", "namaste"], "menu": ["menu", "flavours", "price"], "cancel": ["cancel", "remove"],
           "bill": ["bill", "pay", "total"], "offers": ["offer", "offers", "discount"], "timing": ["time", "open", "close"], "bye": ["bye", "exit"]}
cart, log = [], []


def clean(msg):
    return msg.lower().translate(str.maketrans("", "", string.punctuation)).split()


def intent_of(tokens):
    for name, keys in INTENTS.items():
        if any(t in keys for t in tokens):
            return name
    return "order"


def entities(tokens):
    flav = next((t for t in tokens if t in MENU), None)
    size = next((t for t in tokens if t in SIZE), None)
    qty = next((int(t) for t in tokens if t.isdigit()), None) or next((NUM[t] for t in tokens if t in NUM), 1)
    return flav, size, qty


def bill():
    if not cart:
        return "Your cart is empty."
    lines, total, scoops = [], 0, 0
    for f, s, q in cart:
        amt = round(MENU[f] * SIZE[s] * q)
        total += amt; scoops += q
        lines.append(f"     {q} x {s:<6} {f:<13} Rs.{amt}")
    disc = round(total * 0.10) if scoops >= 3 else 0
    gst = round((total - disc) * 0.05, 2)
    lines.append(f"     Sub-total Rs.{total}  Discount Rs.{disc}  GST 5% Rs.{gst}")
    lines.append(f"     TOTAL Rs.{total - disc + gst}")
    with open("orders.txt", "w") as f:
        f.write("\n".join(lines))
    return "----- BILL -----\n" + "\n".join(lines) + "\n     (bill saved to orders.txt)"


print("=" * 60)
print("Bot: Welcome to Cool Scoops! Order in your own words, e.g. '2 large mango'.")
print("     Other commands: menu, cancel <flavour>, offers, bill, bye")
print("=" * 60)
while True:
    msg = input("You: ")
    t = clean(msg)
    if not t:
        continue
    it = intent_of(t)
    log.append((msg, it))
    if it == "bye":
        print("Bot: Thank you for visiting Cool Scoops!")
        break
    elif it == "greet":
        print("Bot: Hello! What would you like today?")
    elif it == "menu":
        print("Bot: " + ", ".join(f"{f.title()} Rs.{p}" for f, p in MENU.items()) + " (small; medium x1.4, large x1.8)")
    elif it == "offers":
        print("Bot: Buy 3 or more scoops and get 10% off the bill!")
    elif it == "timing":
        print("Bot: We are open 11 AM to 11 PM, all days.")
    elif it == "cancel":
        flav = entities(t)[0]
        before = len(cart)
        cart[:] = [c for c in cart if c[0] != flav]
        print("Bot: Removed", flav, "from your order." if len(cart) < before else "- it was not in your order.")
    elif it == "bill":
        print("Bot:", bill())
    else:
        flav, size, qty = entities(t)
        if flav is None:
            print("Bot: Sorry, which flavour? We have", ", ".join(MENU))
            continue
        while size is None:                                   # slot filling
            ans = clean(input("Bot: Which size - small, medium or large?\nYou: "))
            size = next((x for x in ans if x in SIZE), None)
            if size is None:
                print("Bot: Please choose small, medium or large.")
        cart.append((flav, size, qty))
        print(f"Bot: Added {qty} {size} {flav}. Cart has {sum(c[2] for c in cart)} scoop(s). Anything else?")

print("\nConversation summary:")
for m, i in log:
    print(f"  [{i:<7}] {m}")

        
  1. Start
  2. Read user message
  3. Clean and tokenise
  4. Intent bye? → No: detect other intent
  5. Intent order? → No: menu / cancel / bill / offers
  6. Extract flavour, size, quantity
  7. Size missing? → No: add to cart
  8. Ask for size (slot filling)
  9. Reply
  10. Stop
#Test case / inputExpected resultStatus
1'hello'GreetingPASS
2'show me the menu'Menu with pricesPASS
3'2 large chocolate cups please'Added 2 large chocolatePASS
4'I want mango'Asks sizePASS
5'one butterscotch medium'Qty word understoodPASS
6'cancel butterscotch'RemovedPASS
7'any offers'Offer messagePASS
8'bill'Bill with discount and GSTPASS
9'pizza'Asks valid flavourPASS
โš  Limitations
  • Keyword-based intent detection
  • Fixed menu
  • English only
  • No payment
๐Ÿš€ Future scope
  • ML intent classifier
  • Voice ordering
  • WhatsApp integration
  • Recommend flavour by weather

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): string - ready-made sets of characters are loaded.
  2. Global variables / constants are created: MENU, SIZE, NUM, INTENTS.
  3. 4 functions are defined (lines 14โ€“46) - Python stores them but does NOT run them yet.
  4. Main program starts at line 11: cart, log = [], [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
clean(msg)14โ€“15Cleanmain program
intent_of(tokens)18โ€“22Intent ofmain program
entities(tokens)25โ€“29Entitiesmain program
bill()32โ€“46Billmain program
โ‘ข Main program - line by line
LineCodeWhat it does
11
cart, log = [], []
๐Ÿงฎ Store / Calculate Stores [], [] into cart, log respectively
49
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
50
print("Bot: Welcome to Cool Scoops! Order in your own words, e.g. '2 large mango'.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Welcome to Cool Scoops! Ordeโ€ฆ" on the screen
51
print("     Other commands: menu, cancel <flavour>, offers, bill, bye")
๐Ÿ–ฅ๏ธ Output Displays the text "Other commands: menu, cancel <flaโ€ฆ" on the screen
52
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
53
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
54
msg = input("You: ")
โŒจ๏ธ Input Shows the message "You: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable msg
55
t = clean(msg)
๐Ÿงฎ Store / Calculate Calls our own function clean(msg); the result is stored in variable t
56
if not t:
๐Ÿ”€ Decision CHECKS whether t is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
57
continue
๐Ÿ” Loop CONTINUE - skips the rest of this round and goes to the next round of the loop
58
it = intent_of(t)
๐Ÿงฎ Store / Calculate Calls our own function intent_of(t); the result is stored in variable it
59
log.append((msg, it))
๐Ÿงฎ Store / Calculate Adds (msg, it) at the end of list log
60
if it == "bye":
๐Ÿ”€ Decision CHECKS whether it is equal to "bye". If True, the indented lines below run; otherwise Python jumps to the elif/else part
61
print("Bot: Thank you for visiting Cool Scoops!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Thank you for visiting Cool โ€ฆ" on the screen
62
break
๐Ÿ” Loop BREAK - leaves the loop immediately
63
elif it == "greet":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "greet"
64
print("Bot: Hello! What would you like today?")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Hello! What would you like tโ€ฆ" on the screen
65
elif it == "menu":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "menu"
66
print("Bot: " + ", ".join(f"{f.title()} Rs.{p}" for f, p in MENU.items()) + " (small; medium x1.4, large x1.8)")
๐Ÿ–ฅ๏ธ Output Displays the value of "Bot: " + ", ".join(f"{f.title()} Rs.{p}" forโ€ฆ on the screen
67
elif it == "offers":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "offers"
68
print("Bot: Buy 3 or more scoops and get 10% off the bill!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Buy 3 or more scoops and getโ€ฆ" on the screen
69
elif it == "timing":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "timing"
70
print("Bot: We are open 11 AM to 11 PM, all days.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: We are open 11 AM to 11 PM, โ€ฆ" on the screen
71
elif it == "cancel":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "cancel"
72
flav = entities(t)[0]
๐Ÿงฎ Store / Calculate Stores the item entities(t)[0] in variable flav
73
before = len(cart)
๐Ÿงฎ Store / Calculate Counts the number of items / characters in cart; the result is stored in variable before
74
cart[:] = [c for c in cart if c[0] != flav]
๐Ÿงฎ Store / Calculate Puts a new list made by a list comprehension [c for c in cart if c[0] != flav] into cart[:] (item : of cart)
75
print("Bot: Removed", flav, "from your order." if len(cart) < before else "- it was not in your order.")
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Removed", then the value of flav, then the value of "from your order." if len(cart) < before elseโ€ฆ on the screen
76
elif it == "bill":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether it is equal to "bill"
77
print("Bot:", bill())
๐Ÿ–ฅ๏ธ Output Displays the text "Bot:", then the value of bill() on the screen
78
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
79
flav, size, qty = entities(t)
๐Ÿงฎ Store / Calculate Calls our own function entities(t); the result is stored in variables flav, size, qty
80
if flav is None:
๐Ÿ”€ Decision CHECKS whether flav is None. If True, the indented lines below run; otherwise they are skipped
81
print("Bot: Sorry, which flavour? We have", ", ".join(MENU))
๐Ÿ–ฅ๏ธ Output Displays the text "Bot: Sorry, which flavour? We have", then the value of ", ".join(MENU) on the screen
82
continue
๐Ÿ” Loop CONTINUE - skips the rest of this round and goes to the next round of the loop
83
while size is None:                                   # slot filling
๐Ÿ” Loop LOOP: repeats the indented block as long as size is None; checks the condition before every round
84
ans = clean(input("Bot: Which size - small, medium or large?\nYou: "))
โŒจ๏ธ Input Calls our own function clean(input("Bot: Which sโ€ฆ); the result is stored in variable ans
85
size = next((x for x in ans if x in SIZE), None)
๐Ÿงฎ Store / Calculate Takes the next item from (x for x in ans if x in SIZE); the result is stored in variable size
86
if size is None:
๐Ÿ”€ Decision CHECKS whether size is None. If True, the indented lines below run; otherwise they are skipped
88
cart.append((flav, size, qty))
๐Ÿงฎ Store / Calculate Adds (flav, size, qty) at the end of list cart
89
print(f"Bot: Added {qty} {size} {flav}. Cart has {sum(c[2] for c in cart)} scoop(s). Anything else?")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Bot: Added {qty} {size} {flav}. Cart has {sโ€ฆ with the values filled into { } on the screen
91
print("\nConversation summary:")
๐Ÿ–ฅ๏ธ Output Displays the text "Conversation summary:" on the screen
92
for m, i in log:
๐Ÿ” Loop LOOP: takes each item of log one-by-one into m, i and runs the indented block for it
93
print(f"  [{i:<7}] {m}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" [{i:<7}] {m}" with the values filled into { } on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: Bot: Welcome to Cool Scoops! Order in your own words, e.g. '2 large mango'. (+1 more lines)
  2. You type hello at You:
    runs: clean() โ†’ intent_of()
    shows: Bot: Hello! What would you like today?
  3. You type show me the menu at You:
    runs: clean() โ†’ intent_of()
    shows: Bot: Chocolate Rs.60, Vanilla Rs.50, Mango Rs.55, Butterscotch Rs.65, Strawberry Rs.55 (sm
  4. You type 2 large chocolate cups please at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
    shows: Bot: Added 2 large chocolate. Cart has 2 scoop(s). Anything else?
  5. You type I want mango at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
  6. You type tiny at Bot: Which size - small, medium or large? You:
    runs: clean()
    shows: Bot: Please choose small, medium or large.
  7. You type small at Bot: Which size - small, medium or large? You:
    runs: clean()
    shows: Bot: Added 1 small mango. Cart has 3 scoop(s). Anything else?
  8. You type one butterscotch medium at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
    shows: Bot: Added 1 medium butterscotch. Cart has 4 scoop(s). Anything else?
  9. You type any offers today? at You:
    runs: clean() โ†’ intent_of()
    shows: Bot: Buy 3 or more scoops and get 10% off the bill!
  10. You type pizza please at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
    shows: Bot: Sorry, which flavour? We have chocolate, vanilla, mango, butterscotch, strawberry
  11. You type cancel butterscotch at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
    shows: Bot: Removed butterscotch from your order.
  12. You type three vanilla small at You:
    runs: clean() โ†’ intent_of() โ†’ entities()
    shows: Bot: Added 3 small vanilla. Cart has 6 scoop(s). Anything else?
  13. You type what time do you close at You:
    runs: clean() โ†’ intent_of()
    shows: Bot: We are open 11 AM to 11 PM, all days.
  14. You type bill at You:
    runs: clean() โ†’ intent_of() โ†’ bill()
    shows: Bot: ----- BILL ----- (+6 more lines)
  15. You type bye at You:
    runs: clean() โ†’ intent_of()
    shows: Bot: Thank you for visiting Cool Scoops! (+13 more lines)
โ‘ค Inside each function - line by line
clean() - lines 14โ€“15
LineCodeWhat it does
14
def clean(msg):
๐Ÿงฉ Function DEFINES a function clean(msg). Python only remembers it here - its body runs later, each time clean() is called.
15
return msg.lower().translate(str.maketrans("", "", string.punctuation)).split()
๐Ÿงฉ Function Sends back (returns) the result of: breaks msg.lower().translate(str.maketrans("", "", sโ€ฆ into a list of words (at spaces) to the line that called the function
intent_of() - lines 18โ€“22
LineCodeWhat it does
18
def intent_of(tokens):
๐Ÿงฉ Function DEFINES a function intent_of(tokens). Python only remembers it here - its body runs later, each time intent_of() is called.
19
for name, keys in INTENTS.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary INTENTS; name, keys get one pair each round
20
if any(t in keys for t in tokens):
๐Ÿ”€ Decision CHECKS whether any(t in keys for t in tokens) is True. If True, the indented lines below run; otherwise they are skipped
21
return name
๐Ÿงฉ Function Sends back (returns) the value of name to the line that called the function
22
return "order"
๐Ÿงฉ Function Sends back (returns) the text "order" to the line that called the function
entities() - lines 25โ€“29
LineCodeWhat it does
25
def entities(tokens):
๐Ÿงฉ Function DEFINES a function entities(tokens). Python only remembers it here - its body runs later, each time entities() is called.
26
flav = next((t for t in tokens if t in MENU), None)
๐Ÿงฎ Store / Calculate Takes the next item from (t for t in tokens if t in MENU); the result is stored in variable flav
27
size = next((t for t in tokens if t in SIZE), None)
๐Ÿงฎ Store / Calculate Takes the next item from (t for t in tokens if t in SIZE); the result is stored in variable size
28
qty = next((int(t) for t in tokens if t.isdigit()), None) or next((NUM[t] for t in tokens if t in NUM), 1)
๐Ÿงฎ Store / Calculate Stores the value of next((int(t) for t in tokens if t.isdigit()),โ€ฆ, or next((NUM[t] for t in tokens if t in NUM), 1) if the first one is empty / None / 0 in variable qty
29
return flav, size, qty
๐Ÿงฉ Function Sends back (returns) the tuple flav, size, qty to the line that called the function
bill() - lines 32โ€“46
LineCodeWhat it does
32
def bill():
๐Ÿงฉ Function DEFINES a function bill(). Python only remembers it here - its body runs later, each time bill() is called.
33
if not cart:
๐Ÿ”€ Decision CHECKS whether cart is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
34
return "Your cart is empty."
๐Ÿงฉ Function Sends back (returns) the text "Your cart is empty." to the line that called the function
35
lines, total, scoops = [], 0, 0
๐Ÿงฎ Store / Calculate Stores [], 0, 0 into lines, total, scoops respectively
36
for f, s, q in cart:
๐Ÿ” Loop LOOP: takes each item of cart one-by-one into f, s, q and runs the indented block for it
37
amt = round(MENU[f] * SIZE[s] * q)
๐Ÿงฎ Store / Calculate Rounds MENU[f] * SIZE[s] * q to decimal places; the result is stored in variable amt
38
total += amt; scoops += q
๐Ÿงฎ Store / Calculate Adds amt to total (same as total = total + amt)
38
total += amt; scoops += q
๐Ÿงฎ Store / Calculate Adds q to scoops (same as scoops = scoops + q)
39
lines.append(f"     {q} x {s:<6} {f:<13} Rs.{amt}")
๐Ÿงฎ Store / Calculate Adds f" {q} x {s:<6} {f:<13} Rs.{amt}" at the end of list lines
40
disc = round(total * 0.10) if scoops >= 3 else 0
๐Ÿงฎ Store / Calculate Stores either round(total * 0.10) or 0 depending on scoops >= 3 in variable disc
41
gst = round((total - disc) * 0.05, 2)
๐Ÿงฎ Store / Calculate Rounds (total - disc) * 0.05 to 2 decimal places; the result is stored in variable gst
42
lines.append(f"     Sub-total Rs.{total}  Discount Rs.{disc}  GST 5% Rs.{gst}")
๐Ÿงฎ Store / Calculate Adds f" Sub-total Rs.{total} Discount Rs.{disc} GSโ€ฆ at the end of list lines
43
lines.append(f"     TOTAL Rs.{total - disc + gst}")
๐Ÿงฎ Store / Calculate Adds f" TOTAL Rs.{total - disc + gst}" at the end of list lines
44
with open("orders.txt", "w") as f:
๐Ÿ“ File Opens the file "orders.txt" in "w" mode - write (old content is erased / new file is created) and calls it f. "with" closes the file automatically when the block ends
45
f.write("\n".join(lines))
๐Ÿ“ File Writes "\n".join(lines) into file f
46
return "----- BILL -----\n" + "\n".join(lines) + "\n     (bill saved to orders.txt)"
๐Ÿงฉ Function Sends back (returns) the value of "----- BILL -----\n" + "\n".join(lines) + "\nโ€ฆ (calculated using +) to the line that called the function
Q1. What is an intent?

The goal behind the user's message, e.g. ordering or asking the bill.

Q2. What is an entity?

Specific information in the message like flavour, size or quantity.

Q3. What is slot filling?

Asking follow-up questions until all required entities (slots) are filled.

Q4. How are number words handled?

A dictionary maps words like 'one', 'two' to numbers.

Q5. Is this a script bot or smart bot?

Mostly a script bot with simple NLP (tokenising and entity extraction).

06

Student Performance Correlation Study (SDG 4)

PYTHON + PANDASSDG 4 - Quality EducationPearson correlation matrixscatter matrix insightgroupbycorrelation vs causation
๐Ÿ“ 95 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

Studies how study hours, sleep, screen time and attendance relate to marks for 30 students using Pearson's correlation, identifies the strongest positive and negative factors and visualises the correlation matrix as a heat map.

โœจ Features
  • Sample data of 40 students: study hours, sleep, screen time, attendance and marks
  • Pearson correlation matrix and ranking of factors with marks
  • Spearman correlation for comparison
  • Group comparison (screen time > 4 h vs <= 4 h) with mean difference
  • Strength label (weak / moderate / strong) for each r
  • Heat map, scatter plots and group bar chart
โ˜ฐ Main menu
1View Datahead and describe
2Correlation MatrixPearson r
3Factors vs MarksRanked r with strength
4Spearman vs PearsonRank correlation
5Group ComparisonScreen time groups
6Your Habit CheckCompare a student with class
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Calculate Pearson correlation between several variables using Pandas
  • Identify the strongest positive and negative relationships with marks
  • Visualise the correlation matrix as a heat map
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameStudy_hrs, Sleep_hrs, Screen_hrs, Attendance, Marks
corrDataFrameCorrelation matrix
strength()functionLabel for |r|
Why it matters: Extends the Excel CORREL practical to many variables and builds critical thinking about correlation vs causation.
# =====================================================================
#   STUDENT PERFORMANCE CORRELATION STUDY   (SDG 4) - sample data
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
n = 40
study, sleep = rng.uniform(0.5, 6, n), rng.uniform(5, 9, n)
screen, attend = rng.uniform(1, 7, n), rng.uniform(65, 100, n)
marks = 20 + 7 * study + 2 * sleep - 3 * screen + 0.3 * attend + rng.normal(0, 4, n)
df = pd.DataFrame({"Study_hrs": study, "Sleep_hrs": sleep, "Screen_hrs": screen, "Attendance": attend,
                   "Marks": np.clip(marks, 0, 100)}).round(1)
corr = df.corr(method="pearson").round(3)


def strength(r):
    a = abs(r)
    s = "strong" if a >= 0.6 else "moderate" if a >= 0.3 else "weak"
    return s + (" positive" if r > 0 else " negative")


def view():
    print(df.head(8))
    print("\n", df.describe().round(2))


def matrix():
    print(corr)


def factors():
    w = corr["Marks"].drop("Marks").sort_values(ascending=False)
    for f, r in w.items():
        print(f"{f:<11} r = {r:+.3f}  {strength(r)}")
    print("\nStrongest positive factor:", w.idxmax(), "| strongest negative:", w.idxmin())


def spearman():
    p = corr["Marks"].drop("Marks")
    s = df.corr(method="spearman")["Marks"].drop("Marks").round(3)
    print(pd.DataFrame({"Pearson": p, "Spearman": s}))


def groups():
    df["Screen_group"] = np.where(df.Screen_hrs > 4, "High (>4 h)", "Low (<=4 h)")
    g = df.groupby("Screen_group").agg(Students=("Marks", "size"), Avg_marks=("Marks", "mean"), Avg_study=("Study_hrs", "mean")).round(1)
    print(g)
    print(f"Difference in average marks: {g.Avg_marks.max() - g.Avg_marks.min():.1f}")
    print("Note: correlation shows association, not cause.")


def habit():
    s, sl, sc = float(input("Your study hours: ")), float(input("Your sleep hours: ")), float(input("Your screen hours: "))
    for name, v in (("Study_hrs", s), ("Sleep_hrs", sl), ("Screen_hrs", sc)):
        pct = (df[name] < v).mean() * 100
        print(f"{name:<11}: {v} h  (more than {pct:.0f} % of class)")
    if sc > 4:
        print("Tip: reduce screen time - it has a negative relation with marks.")
    if s < df.Study_hrs.mean():
        print("Tip: add", round(df.Study_hrs.mean() - s, 1), "h of study to reach the class average.")


def charts():
    plt.figure(figsize=(6, 5))
    plt.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1); plt.colorbar(label="Pearson r")
    plt.xticks(range(5), corr.columns, rotation=45); plt.yticks(range(5), corr.columns)
    for i in range(5):
        for j in range(5):
            plt.text(j, i, corr.iloc[i, j], ha="center", va="center", fontsize=8)
    plt.title("Correlation heat map"); plt.savefig("corr_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
    fig, ax = plt.subplots(1, 4, figsize=(13, 3.2), sharey=True)
    for a, c in zip(ax, ["Study_hrs", "Sleep_hrs", "Screen_hrs", "Attendance"]):
        a.scatter(df[c], df.Marks, s=15); m, b = np.polyfit(df[c], df.Marks, 1)
        a.plot(sorted(df[c]), m * np.array(sorted(df[c])) + b, "r-"); a.set_xlabel(c); a.set_title(f"r = {corr.loc[c, 'Marks']}")
    ax[0].set_ylabel("Marks"); plt.tight_layout(); plt.savefig("scatter_matrix.png", dpi=80); plt.show()
    g = df.assign(G=np.where(df.Screen_hrs > 4, "High screen", "Low screen")).groupby("G").Marks.mean()
    g.plot(kind="bar", color=["#fa5252", "#40c057"], title="Average marks by screen-time group")
    plt.xticks(rotation=0); plt.savefig("screen_groups.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: corr_heatmap.png, scatter_matrix.png, screen_groups.png")


print("=" * 55)
print("   STUDENT PERFORMANCE CORRELATION STUDY  (SDG 4)")
print("=" * 55)
menu = {"1": view, "2": matrix, "3": factors, "4": spearman, "5": groups, "6": habit, "7": charts}
while True:
    print("\n1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Create data
  3. Show menu and read choice
  4. Valid option? → No: 'Invalid choice'
  5. df.corr() / groupby
  6. Show result / charts
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Correlation matrix5 x 5, diagonal 1PASS
2FactorsStudy hours strongest +PASS
3Screen timeNegative rPASS
4SpearmanSimilar valuesPASS
5Group comparisonLower marks with more screenPASS
6Habit check 2, 6, 5AdvicePASS
7Charts3 PNG filesPASS
โš  Limitations
  • Synthetic data
  • Correlation is not causation
  • Self-reported habits are inaccurate
  • Linear relation only
๐Ÿš€ Future scope
  • Collect a real anonymous class survey
  • Regression to predict marks
  • Track habits over a term
  • Counselling dashboard

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: rng, n, marks, df, corr.
  3. 8 functions are defined (lines 18โ€“81) - Python stores them but does NOT run them yet.
  4. Main program starts at line 10: study, sleep = rng.uniform(0.5, 6, n), rng.uniform(5, 9, n) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
strength(r)18โ€“21Strengthfactors()
view()24โ€“26Viewmain program (menu)
matrix()29โ€“30Matrixmain program (menu)
factors()33โ€“37Factorsmain program (menu)
spearman()40โ€“43Spearmanmain program (menu)
groups()46โ€“51Groupsmain program (menu)
habit()54โ€“62Habitmain program (menu)
charts()65โ€“81Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
10
study, sleep = rng.uniform(0.5, 6, n), rng.uniform(5, 9, n)
๐Ÿงฎ Store / Calculate Stores rng.uniform(0.5, 6, n), rng.uniform(5, 9, n) into study, sleep respectively
11
screen, attend = rng.uniform(1, 7, n), rng.uniform(65, 100, n)
๐Ÿงฎ Store / Calculate Stores rng.uniform(1, 7, n), rng.uniform(65, 100, n) into screen, attend respectively
12
marks = 20 + 7 * study + 2 * sleep - 3 * screen + 0.3 * attend + rng.normal(0, 4, n)
๐Ÿงฎ Store / Calculate Stores the value of 20 + 7 * study + 2 * sleep - 3 * screen + 0.3โ€ฆ (calculated using +) in variable marks
13
df = pd.DataFrame({"Study_hrs": study, "Sleep_hrs": sleep, "Screen_hrs": screen, "Attendance": attend,
                   "Marks": np.clip(marks, 0, 100)}).rโ€ฆ
๐Ÿ“ฆ Library / Data Rounds the values of pd.DataFrame({"Study_hrs": study, "Sleep_hrs"โ€ฆ to 1 decimal places; the result is stored in variable df
15
corr = df.corr(method="pearson").round(3)
๐Ÿ“ฆ Library / Data Rounds the values of df.corr(method="pearson") to 3 decimal places; the result is stored in variable corr
84
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
85
print("   STUDENT PERFORMANCE CORRELATION STUDY  (SDG 4)")
๐Ÿ–ฅ๏ธ Output Displays the text "STUDENT PERFORMANCE CORRELATION Sโ€ฆ" on the screen
86
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
87
menu = {"1": view, "2": matrix, "3": factors, "4": spearman, "5": groups, "6": habit, "7": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": view, "2": matrix, "3": factors, "4": sโ€ฆ in variable menu
88
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
89
print("\n1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.View 2.Matrix 3.Factors 4.Spearโ€ฆ" on the screen
90
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
91
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
92
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
93
break
๐Ÿ” Loop BREAK - leaves the loop immediately
94
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: STUDENT PERFORMANCE CORRELATION STUDY (SDG 4) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: view()
    shows: Study_hrs Sleep_hrs Screen_hrs Attendance Marks (+18 more lines)
  3. You type 2 at Enter choice:
    runs: matrix()
    shows: Study_hrs Sleep_hrs Screen_hrs Attendance Marks (+6 more lines)
  4. You type 3 at Enter choice:
    runs: factors() โ†’ strength() ร—4
    shows: Study_hrs r = +0.869 strong positive (+5 more lines)
  5. You type 4 at Enter choice:
    runs: spearman()
    shows: Pearson Spearman (+5 more lines)
  6. You type 5 at Enter choice:
    runs: groups()
    shows: Students Avg_marks Avg_study (+6 more lines)
  7. You type 6 at Enter choice:
    runs: habit()
  8. You type 2 at Your study hours:
  9. You type 6 at Your sleep hours:
  10. You type 5 at Your screen hours:
    shows: Study_hrs : 2.0 h (more than 25 % of class) (+5 more lines)
  11. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  12. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
strength() - lines 18โ€“21
LineCodeWhat it does
18
def strength(r):
๐Ÿงฉ Function DEFINES a function strength(r). Python only remembers it here - its body runs later, each time strength() is called.
19
a = abs(r)
๐Ÿงฎ Store / Calculate Gives the absolute (positive) value of r; the result is stored in variable a
20
s = "strong" if a >= 0.6 else "moderate" if a >= 0.3 else "weak"
๐Ÿงฎ Store / Calculate Stores either "strong" or "moderate" if a >= 0.3 else "weak" depending on a >= 0.6 in variable s
21
return s + (" positive" if r > 0 else " negative")
๐Ÿงฉ Function Sends back (returns) the value of s + (" positive" if r > 0 else " negative") (calculated using +) to the line that called the function
view() - lines 24โ€“26
LineCodeWhat it does
24
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
25
print(df.head(8))
๐Ÿ–ฅ๏ธ Output Displays the value of df.head(8) on the screen
26
print("\n", df.describe().round(2))
๐Ÿ–ฅ๏ธ Output Displays a blank, then the value of df.describe().round(2) on the screen
matrix() - lines 29โ€“30
LineCodeWhat it does
29
def matrix():
๐Ÿงฉ Function DEFINES a function matrix(). Python only remembers it here - its body runs later, each time matrix() is called.
30
print(corr)
๐Ÿ–ฅ๏ธ Output Displays the value of corr on the screen
factors() - lines 33โ€“37
LineCodeWhat it does
33
def factors():
๐Ÿงฉ Function DEFINES a function factors(). Python only remembers it here - its body runs later, each time factors() is called.
34
w = corr["Marks"].drop("Marks").sort_values(ascending=False)
๐Ÿงฎ Store / Calculate Sorts corr["Marks"].drop("Marks") by in descending order; the result is stored in variable w
35
for f, r in w.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary w; f, r get one pair each round
36
print(f"{f:<11} r = {r:+.3f}  {strength(r)}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{f:<11} r = {r:+.3f} {strength(r)}" with the values filled into { } on the screen
37
print("\nStrongest positive factor:", w.idxmax(), "| strongest negative:", w.idxmin())
๐Ÿ–ฅ๏ธ Output Displays the text "Strongest positive factor:", then the value of w.idxmax(), then the text "| strongest negative:", then the value of w.idxmin() on the screen
spearman() - lines 40โ€“43
LineCodeWhat it does
40
def spearman():
๐Ÿงฉ Function DEFINES a function spearman(). Python only remembers it here - its body runs later, each time spearman() is called.
41
p = corr["Marks"].drop("Marks")
๐Ÿงฎ Store / Calculate Removes "Marks" from corr["Marks"]; the result is stored in variable p
42
s = df.corr(method="spearman")["Marks"].drop("Marks").round(3)
๐Ÿ“ฆ Library / Data Rounds the values of df.corr(method="spearman")["Marks"].drop("Marโ€ฆ to 3 decimal places; the result is stored in variable s
43
print(pd.DataFrame({"Pearson": p, "Spearman": s}))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.DataFrame({"Pearson": p, "Spearman": s}) on the screen
groups() - lines 46โ€“51
LineCodeWhat it does
46
def groups():
๐Ÿงฉ Function DEFINES a function groups(). Python only remembers it here - its body runs later, each time groups() is called.
47
df["Screen_group"] = np.where(df.Screen_hrs > 4, "High (>4 h)", "Low (<=4 h)")
๐Ÿ“ฆ Library / Data Chooses values depending on condition df.Screen_hrs > 4; the result is put into df["Screen_group"] (item "Screen_group" of df)
48
g = df.groupby("Screen_group").agg(Students=("Marks", "size"), Avg_marks=("Marks", "mean"), Avg_study=("Study_hrs", "mean")).round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby("Screen_group").agg(Students=("Marโ€ฆ to 1 decimal places; the result is stored in variable g
49
print(g)
๐Ÿ–ฅ๏ธ Output Displays the value of g on the screen
50
print(f"Difference in average marks: {g.Avg_marks.max() - g.Avg_marks.min():.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Difference in average marks: {g.Avg_marks.mโ€ฆ with the values filled into { } on the screen
51
print("Note: correlation shows association, not cause.")
๐Ÿ–ฅ๏ธ Output Displays the text "Note: correlation shows associatiโ€ฆ" on the screen
habit() - lines 54โ€“62
LineCodeWhat it does
54
def habit():
๐Ÿงฉ Function DEFINES a function habit(). Python only remembers it here - its body runs later, each time habit() is called.
55
s, sl, sc = float(input("Your study hours: ")), float(input("Your sleep hours: ")), float(input("Your screen hours: "))
โŒจ๏ธ Input Stores float(input("Your study hours: ")), float(input("Your sleep hours: ")), float(input("Your screen hours: ")) into s, sl, sc respectively
56
for name, v in (("Study_hrs", s), ("Sleep_hrs", sl), ("Screen_hrs", sc)):
๐Ÿ” Loop LOOP: takes each item of (("Study_hrs", s), ("Sleep_hrs", sl), ("Screeโ€ฆ one-by-one into name, v and runs the indented block for it
57
pct = (df[name] < v).mean() * 100
๐Ÿงฎ Store / Calculate Stores the value of (df[name] < v).mean() * 100 (calculated using ร—) in variable pct
58
print(f"{name:<11}: {v} h  (more than {pct:.0f} % of class)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name:<11}: {v} h (more than {pct:.0f} % ofโ€ฆ with the values filled into { } on the screen
59
if sc > 4:
๐Ÿ”€ Decision CHECKS whether sc is greater than 4. If True, the indented lines below run; otherwise they are skipped
60
print("Tip: reduce screen time - it has a negative relation with marks.")
๐Ÿ–ฅ๏ธ Output Displays the text "Tip: reduce screen time - it has โ€ฆ" on the screen
61
if s < df.Study_hrs.mean():
๐Ÿ”€ Decision CHECKS whether s is less than df.Study_hrs.mean(). If True, the indented lines below run; otherwise they are skipped
62
print("Tip: add", round(df.Study_hrs.mean() - s, 1), "h of study to reach the class average.")
๐Ÿ–ฅ๏ธ Output Displays the text "Tip: add", then the value of round(df.Study_hrs.mean() - s, 1), then the text "h of study to reach the class aveโ€ฆ" on the screen
charts() - lines 65โ€“81
LineCodeWhat it does
65
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
66
plt.figure(figsize=(6, 5))
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
67
plt.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1); plt.colorbar(label="Pearson r")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
67
plt.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1); plt.colorbar(label="Pearson r")
๐Ÿ–ฅ๏ธ Output Shows a colour scale bar
68
plt.xticks(range(5), corr.columns, rotation=45); plt.yticks(range(5), corr.columns)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
68
plt.xticks(range(5), corr.columns, rotation=45); plt.yticks(range(5), corr.columns)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
69
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
70
for j in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, j takes that value and the indented block runs once
71
plt.text(j, i, corr.iloc[i, j], ha="center", va="center", fontsize=8)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
72
plt.title("Correlation heat map"); plt.savefig("corr_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Correlation heat map" as the title of the chart
72
plt.title("Correlation heat map"); plt.savefig("corr_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "corr_heatmap.png"
72
plt.title("Correlation heat map"); plt.savefig("corr_heatmap.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
73
fig, ax = plt.subplots(1, 4, figsize=(13, 3.2), sharey=True)
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax
74
for a, c in zip(ax, ["Study_hrs", "Sleep_hrs", "Screen_hrs", "Attendance"]):
๐Ÿ” Loop LOOP that walks through ax, ["Study_hrs", "Sleep_hrs", "Screen_hrs", "Attโ€ฆ together; a, c get one item from each
75
a.scatter(df[c], df.Marks, s=15); m, b = np.polyfit(df[c], df.Marks, 1)
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of df[c], df.Marks
75
a.scatter(df[c], df.Marks, s=15); m, b = np.polyfit(df[c], df.Marks, 1)
๐Ÿ–ฅ๏ธ Output Fits a straight line / curve through the points; the result is stored in variables m, b
76
a.plot(sorted(df[c]), m * np.array(sorted(df[c])) + b, "r-"); a.set_xlabel(c); a.set_title(f"r = {corr.loc[c, 'Marks']}")
๐Ÿ–ฅ๏ธ Output Draws a line chart of sorted(df[c]), m * np.array(sorted(df[c])) + b, "r-"
76
a.plot(sorted(df[c]), m * np.array(sorted(df[c])) + b, "r-"); a.set_xlabel(c); a.set_title(f"r = {corr.loc[c, 'Marks']}")
๐Ÿ–ฅ๏ธ Output Sets the X-axis label
76
a.plot(sorted(df[c]), m * np.array(sorted(df[c])) + b, "r-"); a.set_xlabel(c); a.set_title(f"r = {corr.loc[c, 'Marks']}")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
77
ax[0].set_ylabel("Marks"); plt.tight_layout(); plt.savefig("scatter_matrix.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the Y-axis label
77
ax[0].set_ylabel("Marks"); plt.tight_layout(); plt.savefig("scatter_matrix.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
77
ax[0].set_ylabel("Marks"); plt.tight_layout(); plt.savefig("scatter_matrix.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "scatter_matrix.png"
77
ax[0].set_ylabel("Marks"); plt.tight_layout(); plt.savefig("scatter_matrix.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
78
g = df.assign(G=np.where(df.Screen_hrs > 4, "High screen", "Low screen")).groupby("G").Marks.mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of df.assign(G=np.where(df.Screen_hrs > 4, "Highโ€ฆ; the result is stored in variable g
79
g.plot(kind="bar", color=["#fa5252", "#40c057"], title="Average marks by screen-time group")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
80
plt.xticks(rotation=0); plt.savefig("screen_groups.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
80
plt.xticks(rotation=0); plt.savefig("screen_groups.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "screen_groups.png"
80
plt.xticks(rotation=0); plt.savefig("screen_groups.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
print("Charts saved: corr_heatmap.png, scatter_matrix.png, screen_groups.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: corr_heatmap.png, sโ€ฆ" on the screen
Q1. What is Pearson correlation?

A measure from -1 to +1 of linear relationship between two variables.

Q2. Does high correlation prove cause?

No - correlation shows association; a third factor may cause both.

Q3. Spearman vs Pearson?

Spearman uses ranks and captures monotonic (not only linear) relations.

Q4. What does r = -0.5 mean?

Moderate negative relation: as one rises, the other tends to fall.

Q5. Why a heat map?

Colours make it easy to see strong positive / negative pairs.

07

SMS Spam Detector using Naive Bayes (SDG 16)

PYTHON + SKLEARNSDG 16 - Peace, Justice and Strong Institutions (cyber safety)Text classificationCountVectorizer (Bag of Words)Multinomial Naive Bayesprecision / recalleffect of stop-word removal
๐Ÿ“ 141 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 87 output lines๐Ÿ“„ 25+ page report

Trains a text classifier on 52 labelled SMS messages (fraud/spam vs genuine) using Bag of Words and Naive Bayes, evaluates it with a confusion matrix, precision and recall, and checks new messages typed by the user.

โœจ Features
  • 52 labelled SMS (26 spam / fraud, 26 genuine) typical of Indian phone scams
  • Bag-of-Words with CountVectorizer and Multinomial Naive Bayes classifier
  • Evaluation: confusion matrix, accuracy, precision, recall, F1
  • Top spam-indicating words from learnt probabilities
  • Check any new SMS with spam probability and the words that influenced it
  • Threshold experiment (0.3 / 0.5 / 0.7) and cyber-safety tips
โ˜ฐ Main menu
1Dataset SummaryCounts and sample messages
2Train & EvaluateFit NB and show metrics
3Top Spam WordsMost spam-like words
4Check an SMSType message -> verdict
5Threshold ExperimentEffect on precision / recall
6Cyber Safety TipsHow to stay safe
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Convert text to numeric features using a Bag of Words
  • Train and evaluate a Naive Bayes classifier
  • Test the model on new messages and discuss errors
๐Ÿ“š Data dictionary
NameTypePurpose
spam / hamlistsTraining messages
vecCountVectorizerVocabulary and word counts
modelMultinomialNBClassifier
X_tr, X_te, y_tr, y_telistsTrain-test split (75:25)
Why it matters: Combines NLP and classification to tackle a real cyber-safety problem - fraud SMS and phishing.
# =====================================================================
#   SMS SPAM DETECTOR USING NAIVE BAYES   (SDG 16 - cyber safety)
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, precision_score, recall_score, accuracy_score, f1_score

spam = ["Congratulations you won a lottery of 25 lakh claim now",
        "Your KYC is pending click this link to update or account blocked",
        "Win a free iPhone send your details today", "Urgent your bank account is suspended verify now",
        "You have won cash prize call now to claim", "Get instant loan without documents click link",
        "Free recharge offer share OTP to activate", "Your parcel is held pay customs fee via link",
        "Claim your reward points before they expire click here", "Earn 5000 daily work from home register now",
        "Your electricity bill unpaid connection will be cut call officer now", "Lucky draw winner send bank details",
        "Limited offer buy now get 90 percent discount click", "Your SIM will be blocked update KYC immediately",
        "Investment scheme doubles your money in 10 days join now", "Congratulations selected for job pay registration fee",
        "Free gift card waiting claim now", "Urgent: share OTP to stop unauthorised transaction",
        "You won a scholarship send fee to confirm", "Click link to get free data for 1 year",
        "Your power will be disconnected tonight call this number now", "Account blocked call customer care now to unblock",
        "Final notice pay pending bill now or service disconnected", "Congratulations claim free voucher click link now",
        "Dear customer your card is blocked share OTP now", "Win cash prize daily just click and register"]
ham = ["Mom I will reach home by 6", "Class test of AI is on Monday", "Please bring your lab coat tomorrow",
       "Happy birthday beta have a great day", "Meeting with parents at 10 am in the school",
       "Your OTP for login is 4521 do not share it with anyone", "Can you send me the physics notes",
       "Dinner is ready come downstairs", "The bus will be late by 15 minutes today", "Library books are due on Friday",
       "Congratulations on your result proud of you", "Call me when you are free", "Practice match at 4 pm on the ground",
       "Your order has been delivered thank you for shopping", "Electricity bill of 1200 paid successfully",
       "School will remain closed tomorrow due to rain", "Let us study together for the exam",
       "Uncle is coming home this evening", "Please submit the project file by Thursday", "Good night see you tomorrow",
       "Bring your geometry box for the maths class", "Your tuition class is shifted to 5 pm",
       "Sports day practice will start next week", "Please call me after you reach school",
       "The doctor appointment is at 11 tomorrow", "Grandma liked the photos you sent"]
texts = spam + ham
labels = [1] * len(spam) + [0] * len(ham)               # 1 = spam, 0 = ham
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.25, random_state=7, stratify=labels)
vec = CountVectorizer()
model = None


def summary():
    print("Messages:", len(texts), "| spam:", len(spam), "| ham:", len(ham))
    print("Train:", len(X_tr), "| Test:", len(X_te))
    print("Sample spam:", spam[0]); print("Sample ham :", ham[0])


def train():
    global model
    model = MultinomialNB().fit(vec.fit_transform(X_tr), y_tr)
    pred = model.predict(vec.transform(X_te))
    print("Vocabulary size:", len(vec.vocabulary_))
    print("Confusion matrix [[TN FP] [FN TP]]:\n", confusion_matrix(y_te, pred))
    print(f"Accuracy {accuracy_score(y_te, pred):.3f} | Precision {precision_score(y_te, pred):.3f} | "
          f"Recall {recall_score(y_te, pred):.3f} | F1 {f1_score(y_te, pred):.3f}")


def spam_words(n=10):
    logp = model.feature_log_prob_
    ratio = logp[1] - logp[0]
    words = np.array(vec.get_feature_names_out())
    top = np.argsort(ratio)[::-1][:n]
    for w, r in zip(words[top], ratio[top]):
        print(f"  {w:<12} spam/ham likelihood ratio {np.exp(r):5.2f}")
    return words[top], np.exp(ratio[top])


def check():
    msg = input("Type an SMS to check: ")
    x = vec.transform([msg])
    p = model.predict_proba(x)[0][1]
    print("Prediction:", "SPAM / FRAUD" if p >= 0.5 else "HAM (genuine)", f"(spam probability {p:.2f})")
    words = [w for w in vec.build_analyzer()(msg) if w in vec.vocabulary_]
    ratio = model.feature_log_prob_[1] - model.feature_log_prob_[0]
    infl = sorted(words, key=lambda w: -ratio[vec.vocabulary_[w]])[:4]
    print("Most spam-like words in it:", infl)


def thresholds():
    p = model.predict_proba(vec.transform(X_te))[:, 1]
    res = []
    for t in (0.3, 0.5, 0.7):
        pr = (p >= t).astype(int)
        res.append((t, precision_score(y_te, pr, zero_division=0), recall_score(y_te, pr)))
        print(f"threshold {t}: precision {res[-1][1]:.2f}  recall {res[-1][2]:.2f}")
    return res


def tips():
    for t in ["Never share OTP, PIN or CVV - banks never ask for them.", "Do not click unknown links; check the sender.",
              "Electricity / KYC 'disconnection tonight' messages are common scams.", "Report fraud at 1930 or cybercrime.gov.in."]:
        print(" *", t)


def charts():
    cm = confusion_matrix(y_te, model.predict(vec.transform(X_te)))
    plt.imshow(cm, cmap="Oranges")
    for (i, j), v in np.ndenumerate(cm):
        plt.text(j, i, v, ha="center", va="center", fontsize=16)
    plt.xticks([0, 1], ["Ham", "Spam"]); plt.yticks([0, 1], ["Ham", "Spam"]); plt.xlabel("Predicted"); plt.ylabel("Actual")
    plt.title("Confusion matrix (test SMS)"); plt.savefig("spam_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
    w, r = spam_words(10)
    plt.barh(w[::-1], r[::-1], color="#e8590c"); plt.title("Top spam-indicating words"); plt.xlabel("Likelihood ratio")
    plt.savefig("spam_words.png", dpi=90, bbox_inches="tight"); plt.show()
    res = thresholds()
    x = np.arange(3)
    plt.bar(x - 0.2, [r[1] for r in res], 0.4, label="Precision"); plt.bar(x + 0.2, [r[2] for r in res], 0.4, label="Recall")
    plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
    plt.savefig("spam_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: spam_confusion.png, spam_words.png, spam_threshold.png")


print("=" * 55)
print("   SMS SPAM DETECTOR  (Naive Bayes)")
print("=" * 55)
while True:
    print("\n1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Stay alert, stay safe!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        train()
    elif ch == "6":
        tips()
    elif model is None and ch in "3457":
        print("Train the model first (option 2).")
    elif ch == "3":
        spam_words()
    elif ch == "4":
        check()
    elif ch == "5":
        thresholds()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Build dataset and split
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. Vectorise message
  6. predict_proba
  7. Probability >= 0.5? → No: HAM
  8. SPAM warning
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1TrainAccuracy shownPASS
2Top wordsnow, click, claim...PASS
3'Your electricity will be disconnected tonight, call now'SPAMPASS
4'Please bring your AI practical file tomorrow'HAMPASS
5'Your OTP is 1234 do not share'HAMPASS
6Threshold 0.3Higher recallPASS
7Check before training'Train first'PASS
8Charts3 PNG filesPASS
โš  Limitations
  • Small hand-made dataset
  • English only
  • New scam styles may be missed
  • Word order ignored
๐Ÿš€ Future scope
  • Train on the public SMS Spam Collection
  • Hindi / Hinglish support
  • Mobile app that warns in real time
  • Report to cybercrime.gov.in

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, CountVectorizer, MultinomialNB, train_test_split, confusion_matrix, precision_score, recall_score, accuracy_score, f1_score are loaded.
  2. Global variables / constants are created: spam, ham, texts, labels, vec, model.
  3. 7 functions are defined (lines 43โ€“111) - Python stores them but does NOT run them yet.
  4. Main program starts at line 38: X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.2 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()43โ€“46Summarymain program
train()49โ€“56Trainmain program
spam_words(n)59โ€“66Spam wordscharts(), main program
check()69โ€“77Checkmain program
thresholds()80โ€“87Thresholdscharts(), main program
tips()90โ€“93Tipsmain program
charts()96โ€“111Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
38
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.25, random_state=7, stratify=labels)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te
39
vec = CountVectorizer()
๐Ÿงฎ Store / Calculate Calls CountVectorizer(); the result is stored in variable vec
40
model = None
๐Ÿงฎ Store / Calculate Stores None (nothing) in variable model
114
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
115
print("   SMS SPAM DETECTOR  (Naive Bayes)")
๐Ÿ–ฅ๏ธ Output Displays the text "SMS SPAM DETECTOR (Naive Bayes)" on the screen
116
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
117
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
118
print("\n1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Train 3.Spam Words 4.โ€ฆ" on the screen
119
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
120
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
121
print("Stay alert, stay safe!")
๐Ÿ–ฅ๏ธ Output Displays the text "Stay alert, stay safe!" on the screen
122
break
๐Ÿ” Loop BREAK - leaves the loop immediately
123
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
124
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
125
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
126
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
127
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
128
tips()
๐Ÿงฎ Store / Calculate Calls our own function tips()
129
elif model is None and ch in "3457":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (model is None AND ch is present in "3457")
130
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
131
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
132
spam_words()
๐Ÿงฎ Store / Calculate Calls our own function spam_words()
133
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
134
check()
๐Ÿงฎ Store / Calculate Calls our own function check()
135
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
136
thresholds()
๐Ÿงฎ Store / Calculate Calls our own function thresholds()
137
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
138
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
139
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
140
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: SMS SPAM DETECTOR (Naive Bayes) (+1 more lines)
  2. You type 4 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Messages: 52 | spam: 26 | ham: 26 (+4 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Vocabulary size: 173 (+5 more lines)
  5. You type 3 at Enter choice:
    runs: spam_words()
    shows: now spam/ham likelihood ratio 8.67 (+10 more lines)
  6. You type 4 at Enter choice:
    runs: check()
  7. You type Your electricity will be disconnected tonight, call this number now at Type an SMS to check:
    shows: Prediction: SPAM / FRAUD (spam probability 1.00) (+2 more lines)
  8. You type 4 at Enter choice:
    runs: check()
  9. You type Please bring your AI practical file tomorrow at Type an SMS to check:
    shows: Prediction: HAM (genuine) (spam probability 0.01) (+2 more lines)
  10. You type 4 at Enter choice:
    runs: check()
  11. You type Your OTP is 1234 do not share it with anyone at Type an SMS to check:
    shows: Prediction: HAM (genuine) (spam probability 0.05) (+2 more lines)
  12. You type 5 at Enter choice:
    runs: thresholds()
    shows: threshold 0.3: precision 0.64 recall 1.00 (+3 more lines)
  13. You type 6 at Enter choice:
    runs: tips()
    shows: * Never share OTP, PIN or CVV - banks never ask for them. (+4 more lines)
  14. You type 7 at Enter choice:
    runs: charts() โ†’ spam_words() โ†’ thresholds()
    shows: [chart is drawn] (+17 more lines)
  15. You type 0 at Enter choice:
    shows: Stay alert, stay safe!
โ‘ค Inside each function - line by line
summary() - lines 43โ€“46
LineCodeWhat it does
43
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
44
print("Messages:", len(texts), "| spam:", len(spam), "| ham:", len(ham))
๐Ÿ–ฅ๏ธ Output Displays the text "Messages:", then the value of len(texts), then the text "| spam:", then the value of len(spam), then the text "| ham:", then the value of len(ham) on the screen
45
print("Train:", len(X_tr), "| Test:", len(X_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Train:", then the value of len(X_tr), then the text "| Test:", then the value of len(X_te) on the screen
46
print("Sample spam:", spam[0]); print("Sample ham :", ham[0])
๐Ÿ–ฅ๏ธ Output Displays the text "Sample spam:", then the value of spam[0] on the screen
46
print("Sample spam:", spam[0]); print("Sample ham :", ham[0])
๐Ÿ–ฅ๏ธ Output Displays the text "Sample ham :", then the value of ham[0] on the screen
train() - lines 49โ€“56
LineCodeWhat it does
49
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
50
global model
๐Ÿงฉ Function Tells Python that model means the GLOBAL variable (outside the function)
51
model = MultinomialNB().fit(vec.fit_transform(X_tr), y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model MultinomialNB() on the given data; the result is stored in variable model
52
pred = model.predict(vec.transform(X_te))
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for vec.transform(X_te); the result is stored in variable pred
53
print("Vocabulary size:", len(vec.vocabulary_))
๐Ÿ–ฅ๏ธ Output Displays the text "Vocabulary size:", then the value of len(vec.vocabulary_) on the screen
54
print("Confusion matrix [[TN FP] [FN TP]]:\n", confusion_matrix(y_te, pred))
๐Ÿ–ฅ๏ธ Output Displays the text "Confusion matrix [[TN FP] [FN TP]โ€ฆ", then the value of confusion_matrix(y_te, pred) on the screen
55
print(f"Accuracy {accuracy_score(y_te, pred):.3f} | Precision {precision_score(y_te, pred):.3f} | "
      f"Recall {recall_score(y_te, pred):.3f} | F1 {f1_scโ€ฆ
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Accuracy {accuracy_score(y_te, pred):.3f} |โ€ฆ with the values filled into { } on the screen
spam_words() - lines 59โ€“66
LineCodeWhat it does
59
def spam_words(n=10):
๐Ÿงฉ Function DEFINES a function spam_words(n). Python only remembers it here - its body runs later, each time spam_words() is called.
60
logp = model.feature_log_prob_
๐Ÿงฎ Store / Calculate Stores model.feature_log_prob_ in variable logp
61
ratio = logp[1] - logp[0]
๐Ÿงฎ Store / Calculate Stores the value of logp[1] - logp[0] (calculated using -) in variable ratio
62
words = np.array(vec.get_feature_names_out())
๐Ÿ“ฆ Library / Data Makes a NumPy array from vec.get_feature_names_out(); the result is stored in variable words
63
top = np.argsort(ratio)[::-1][:n]
๐Ÿ“ฆ Library / Data Stores a slice np.argsort(ratio)[::-1][:n] (part of np.argsort(ratio)[::-1]) in variable top
64
for w, r in zip(words[top], ratio[top]):
๐Ÿ” Loop LOOP that walks through words[top], ratio[top] together; w, r get one item from each
65
print(f"  {w:<12} spam/ham likelihood ratio {np.exp(r):5.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {w:<12} spam/ham likelihood ratio {np.exp(โ€ฆ with the values filled into { } on the screen
66
return words[top], np.exp(ratio[top])
๐Ÿงฉ Function Sends back (returns) the tuple words[top], np.exp(ratio[top]) to the line that called the function
check() - lines 69โ€“77
LineCodeWhat it does
69
def check():
๐Ÿงฉ Function DEFINES a function check(). Python only remembers it here - its body runs later, each time check() is called.
70
msg = input("Type an SMS to check: ")
โŒจ๏ธ Input Shows the message "Type an SMS to check: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable msg
71
x = vec.transform([msg])
๐Ÿงฎ Store / Calculate Converts (scales / changes) [msg] using what was learnt; the result is stored in variable x
72
p = model.predict_proba(x)[0][1]
๐Ÿงฎ Store / Calculate Stores the item model.predict_proba(x)[0][1] in variable p
73
print("Prediction:", "SPAM / FRAUD" if p >= 0.5 else "HAM (genuine)", f"(spam probability {p:.2f})")
๐Ÿ–ฅ๏ธ Output Displays the text "Prediction:", then the value of "SPAM / FRAUD" if p >= 0.5 else "HAM (genuineโ€ฆ, then the f-string f"(spam probability {p:.2f})" with the values filled into { } on the screen
74
words = [w for w in vec.build_analyzer()(msg) if w in vec.vocabulary_]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [w for w in vec.build_analyzer()(msg) if w inโ€ฆ in variable words
75
ratio = model.feature_log_prob_[1] - model.feature_log_prob_[0]
๐Ÿงฎ Store / Calculate Stores the value of model.feature_log_prob_[1] - model.feature_loโ€ฆ (calculated using -) in variable ratio
76
infl = sorted(words, key=lambda w: -ratio[vec.vocabulary_[w]])[:4]
๐Ÿงฎ Store / Calculate Stores a slice sorted(words, key=lambda w: -ratio[vec.vocabuโ€ฆ (part of sorted(words, key=lambda w: -ratio[vec.vocabuโ€ฆ) in variable infl
77
print("Most spam-like words in it:", infl)
๐Ÿ–ฅ๏ธ Output Displays the text "Most spam-like words in it:", then the value of infl on the screen
thresholds() - lines 80โ€“87
LineCodeWhat it does
80
def thresholds():
๐Ÿงฉ Function DEFINES a function thresholds(). Python only remembers it here - its body runs later, each time thresholds() is called.
81
p = model.predict_proba(vec.transform(X_te))[:, 1]
๐Ÿงฎ Store / Calculate Stores a slice model.predict_proba(vec.transform(X_te))[:, 1] (part of model.predict_proba(vec.transform(X_te))) in variable p
82
res = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable res
83
for t in (0.3, 0.5, 0.7):
๐Ÿ” Loop LOOP: takes each item of (0.3, 0.5, 0.7) one-by-one into t and runs the indented block for it
84
pr = (p >= t).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of p >= t to int; the result is stored in variable pr
85
res.append((t, precision_score(y_te, pr, zero_division=0), recall_score(y_te, pr)))
๐Ÿงฎ Store / Calculate Adds (t, precision_score(y_te, pr, zero_division=0โ€ฆ at the end of list res
86
print(f"threshold {t}: precision {res[-1][1]:.2f}  recall {res[-1][2]:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"threshold {t}: precision {res[-1][1]:.2f} rโ€ฆ with the values filled into { } on the screen
87
return res
๐Ÿงฉ Function Sends back (returns) the value of res to the line that called the function
tips() - lines 90โ€“93
LineCodeWhat it does
90
def tips():
๐Ÿงฉ Function DEFINES a function tips(). Python only remembers it here - its body runs later, each time tips() is called.
91
for t in ["Never share OTP, PIN or CVV - banks never ask for them.", "Do not click unknown links; check the sender.",
          "Electricity / KYC 'disconnecโ€ฆ
๐Ÿ” Loop LOOP: takes each item of ["Never share OTP, PIN or CVV - banks never aโ€ฆ one-by-one into t and runs the indented block for it
93
print(" *", t)
๐Ÿ–ฅ๏ธ Output Displays the text "*", then the value of t on the screen
charts() - lines 96โ€“111
LineCodeWhat it does
96
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
97
cm = confusion_matrix(y_te, model.predict(vec.transform(X_te)))
๐Ÿ“ฆ Library / Data Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
98
plt.imshow(cm, cmap="Oranges")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
99
for (i, j), v in np.ndenumerate(cm):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(cm) one-by-one into (i, j), v and runs the indented block for it
100
plt.text(j, i, v, ha="center", va="center", fontsize=16)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
101
plt.xticks([0, 1], ["Ham", "Spam"]); plt.yticks([0, 1], ["Ham", "Spam"]); plt.xlabel("Predicted"); plt.ylabel("Actual")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
101
plt.xticks([0, 1], ["Ham", "Spam"]); plt.yticks([0, 1], ["Ham", "Spam"]); plt.xlabel("Predicted"); plt.ylabel("Actual")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
101
plt.xticks([0, 1], ["Ham", "Spam"]); plt.yticks([0, 1], ["Ham", "Spam"]); plt.xlabel("Predicted"); plt.ylabel("Actual")
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the X-axis
101
plt.xticks([0, 1], ["Ham", "Spam"]); plt.yticks([0, 1], ["Ham", "Spam"]); plt.xlabel("Predicted"); plt.ylabel("Actual")
๐Ÿ–ฅ๏ธ Output Writes "Actual" as the label of the Y-axis
102
plt.title("Confusion matrix (test SMS)"); plt.savefig("spam_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix (test SMS)" as the title of the chart
102
plt.title("Confusion matrix (test SMS)"); plt.savefig("spam_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "spam_confusion.png"
102
plt.title("Confusion matrix (test SMS)"); plt.savefig("spam_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
103
w, r = spam_words(10)
๐Ÿงฎ Store / Calculate Calls our own function spam_words(10); the result is stored in variables w, r
104
plt.barh(w[::-1], r[::-1], color="#e8590c"); plt.title("Top spam-indicating words"); plt.xlabel("Likelihood ratio")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
104
plt.barh(w[::-1], r[::-1], color="#e8590c"); plt.title("Top spam-indicating words"); plt.xlabel("Likelihood ratio")
๐Ÿ–ฅ๏ธ Output Writes "Top spam-indicating words" as the title of the chart
104
plt.barh(w[::-1], r[::-1], color="#e8590c"); plt.title("Top spam-indicating words"); plt.xlabel("Likelihood ratio")
๐Ÿ–ฅ๏ธ Output Writes "Likelihood ratio" as the label of the X-axis
105
plt.savefig("spam_words.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "spam_words.png"
105
plt.savefig("spam_words.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
106
res = thresholds()
๐Ÿงฎ Store / Calculate Calls our own function thresholds(); the result is stored in variable res
107
x = np.arange(3)
๐Ÿ“ฆ Library / Data Makes a NumPy array of numbers from range(3); the result is stored in variable x
108
plt.bar(x - 0.2, [r[1] for r in res], 0.4, label="Precision"); plt.bar(x + 0.2, [r[2] for r in res], 0.4, label="Recall")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x - 0.2, [r[1] for r in res], 0.4
108
plt.bar(x - 0.2, [r[1] for r in res], 0.4, label="Precision"); plt.bar(x + 0.2, [r[2] for r in res], 0.4, label="Recall")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x + 0.2, [r[2] for r in res], 0.4
109
plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
109
plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
๐Ÿ–ฅ๏ธ Output Writes "Threshold" as the label of the X-axis
109
plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
๐Ÿ–ฅ๏ธ Output Sets the range of the Y-axis
109
plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
109
plt.xticks(x, ["0.3", "0.5", "0.7"]); plt.xlabel("Threshold"); plt.ylim(0, 1.1); plt.legend(); plt.title("Threshold vs precision / recall")
๐Ÿ–ฅ๏ธ Output Writes "Threshold vs precision / recall" as the title of the chart
110
plt.savefig("spam_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "spam_threshold.png"
110
plt.savefig("spam_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
111
print("Charts saved: spam_confusion.png, spam_words.png, spam_threshold.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: spam_confusion.png,โ€ฆ" on the screen
Q1. Why Naive Bayes for text?

It is fast, works well with word counts and small data; it assumes words are independent given the class.

Q2. What does CountVectorizer do?

Converts text into a matrix of word counts (Bag of Words).

Q3. Precision vs recall for spam?

High precision avoids marking genuine SMS as spam; high recall catches more scams.

Q4. What is predict_proba?

Gives probability of each class; we compare spam probability with a threshold.

Q5. Which SDG?

SDG 16 - Peace, Justice and Strong Institutions (fighting fraud).

08

Crop Recommendation System using KNN (SDG 2)

PYTHON + SKLEARNSDG 2 - Zero HungerFeature scaling (MinMaxScaler)KNN classifierpipelinecross-validationprediction with probabilities
๐Ÿ“ 110 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 86 output lines๐Ÿ“„ 25+ page report

Recommends the most suitable crop (rice, wheat, maize, cotton, chickpea) from soil nitrogen, phosphorus, potassium, temperature, humidity, pH and rainfall using a scaled KNN model, evaluated with 5-fold cross-validation.

โœจ Features
  • 200 sample soil reports (N, P, K, temperature, humidity, pH, rainfall) for 5 crops
  • Pipeline: MinMaxScaler + KNeighborsClassifier
  • 5-fold cross-validation and choice of k (3, 5, 7, 9)
  • Top-3 crop recommendation with probability for a new soil report
  • Input validation (pH 0-14, humidity 0-100)
  • Crop nutrient profile table and 3 charts
โ˜ฐ Main menu
1Dataset SummaryRecords, crops, average profile
2Choose k (CV)Cross-validation for k = 3..9
3Train Final ModelFit pipeline with best k
4Recommend CropSoil report -> top 3 crops
5Test ReportConfusion matrix on hold-out data
6Chartsk chart, profile, confusion
0ExitEnds program
๐ŸŽฏ Objectives
  • Prepare multi-feature agricultural data and scale it
  • Train a KNN model inside a Pipeline and validate with 5-fold cross-validation
  • Recommend crops with confidence for new soil reports
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameN, P, K, Temp, Humidity, pH, Rainfall, Crop
colslist7 feature names
modelPipelineMinMaxScaler + KNN
cv_scoresdictk -> mean CV accuracy
Why it matters: A learning-based upgrade of the Class IX rule-based crop advisor - shows why ML adapts better to complex data.
# =====================================================================
#   CROP RECOMMENDATION SYSTEM USING KNN   (SDG 2) - sample agronomy data
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score

rng = np.random.default_rng(8)
#              N    P    K   temp  humid  pH   rain
profile = {"rice": (80, 45, 40, 24, 82, 6.4, 220), "wheat": (60, 50, 40, 20, 55, 6.8, 75),
           "maize": (78, 48, 20, 23, 65, 6.3, 85), "cotton": (118, 46, 20, 24, 80, 6.9, 80),
           "chickpea": (40, 67, 80, 18, 17, 7.3, 80)}
spread = (10, 8, 6, 2.5, 5, 0.4, 20)
rows = [list(np.round(rng.normal(m, spread), 1)) + [c] for c, m in profile.items() for _ in range(40)]
cols = ["N", "P", "K", "Temp", "Humidity", "pH", "Rainfall"]
df = pd.DataFrame(rows, columns=cols + ["Crop"])
cv_scores, state = {}, {}


def summary():
    print("Records:", len(df), "| Crops:", df.Crop.unique().tolist())
    print(df.groupby("Crop")[cols].mean().round(1))


def choose_k():
    for k in (3, 5, 7, 9):
        m = make_pipeline(MinMaxScaler(), KNeighborsClassifier(n_neighbors=k))
        s = cross_val_score(m, df[cols], df.Crop, cv=5)
        cv_scores[k] = s.mean()
        print(f"k = {k}: folds {np.round(s, 3)} -> mean {s.mean() * 100:.2f} %")
    print("Best k:", max(cv_scores, key=cv_scores.get))


def train():
    k = max(cv_scores, key=cv_scores.get) if cv_scores else 5
    X_tr, X_te, y_tr, y_te = train_test_split(df[cols], df.Crop, test_size=0.25, random_state=3, stratify=df.Crop)
    state["model"] = make_pipeline(MinMaxScaler(), KNeighborsClassifier(n_neighbors=k)).fit(X_tr, y_tr)
    state["test"] = (X_te, y_te)
    print(f"Model trained with k = {k}. Hold-out accuracy: {accuracy_score(y_te, state['model'].predict(X_te)) * 100:.2f} %")


def recommend():
    vals = [float(input(f"  {c:<9}: ")) for c in cols]
    if not 0 <= vals[5] <= 14 or not 0 <= vals[4] <= 100:
        print("pH must be 0-14 and humidity 0-100.")
        return
    m = state["model"]
    proba = m.predict_proba(pd.DataFrame([vals], columns=cols))[0]
    order = np.argsort(proba)[::-1][:3]
    print("Recommended crop:", m.classes_[order[0]].upper())
    for i in order:
        print(f"   {m.classes_[i]:<9} {proba[i] * 100:5.1f} %  " + "#" * int(proba[i] * 20))


def test_report():
    X_te, y_te = state["test"]
    p = state["model"].predict(X_te)
    labels = sorted(profile)
    print(pd.DataFrame(confusion_matrix(y_te, p, labels=labels), index=labels, columns=labels))


def charts():
    plt.plot(list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"); plt.xlabel("k"); plt.ylabel("CV accuracy %"); plt.title("Choosing k (5-fold CV)")
    plt.savefig("crop_k.png", dpi=90, bbox_inches="tight"); plt.show()
    norm = df.groupby("Crop")[cols].mean()
    norm = (norm - norm.min()) / (norm.max() - norm.min())
    norm.T.plot(kind="bar", figsize=(9, 4), title="Normalised nutrient & climate profile of crops")
    plt.xticks(rotation=0); plt.savefig("crop_profile.png", dpi=90, bbox_inches="tight"); plt.show()
    X_te, y_te = state["test"]
    labels = sorted(profile)
    cm = confusion_matrix(y_te, state["model"].predict(X_te), labels=labels)
    plt.imshow(cm, cmap="Greens")
    for (i, j), v in np.ndenumerate(cm):
        plt.text(j, i, v, ha="center", va="center")
    plt.xticks(range(5), labels, rotation=30); plt.yticks(range(5), labels); plt.title("Confusion matrix (hold-out)")
    plt.savefig("crop_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: crop_k.png, crop_profile.png, crop_confusion.png")


print("=" * 55)
print("   CROP RECOMMENDATION SYSTEM  (KNN)")
print("=" * 55)
while True:
    print("\n1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Jai Kisan!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        choose_k()
    elif ch == "3":
        train()
    elif "model" not in state and ch in "456":
        print("Train the model first (option 3).")
    elif ch == "4":
        recommend()
    elif ch == "5":
        test_report()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create dataset
  3. Show menu and read choice
  4. Model trained? → No: train with best k
  5. Read soil report
  6. Values valid? → No: show error
  7. predict_proba and sort
  8. Top 3 crops
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Summary200 records, 5 cropsPASS
2CVAccuracy for k = 3..9PASS
3Report 85, 45, 40, 25, 82, 6.4, 210RICEPASS
4Report 25, 65, 80, 19, 17, 7.2, 80CHICKPEAPASS
5pH 15'pH must be 0-14'PASS
6Test reportConfusion matrixPASS
7Charts3 PNG filesPASS
โš  Limitations
  • Synthetic data around typical values
  • Only 5 crops
  • Market price and water availability ignored
  • Soil test needed
๐Ÿš€ Future scope
  • Kaggle Crop Recommendation dataset (22 crops)
  • Soil Health Card integration
  • Hindi voice interface
  • Fertiliser suggestion module

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, make_pipeline, MinMaxScaler, KNeighborsClassifier, cross_val_score, train_test_split, confusion_matrix, accuracy_score are loaded.
  2. Global variables / constants are created: rng, profile, spread, rows, cols, df.
  3. 6 functions are defined (lines 25โ€“82) - Python stores them but does NOT run them yet.
  4. Main program starts at line 22: cv_scores, state = {}, {} - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()25โ€“27Summarymain program
choose_k()30โ€“36Choose kmain program
train()39โ€“44Trainmain program
recommend()47โ€“57Recommendmain program
test_report()60โ€“64Test reportmain program
charts()67โ€“82Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
22
cv_scores, state = {}, {}
๐Ÿงฎ Store / Calculate Stores {}, {} into cv_scores, state respectively
85
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
86
print("   CROP RECOMMENDATION SYSTEM  (KNN)")
๐Ÿ–ฅ๏ธ Output Displays the text "CROP RECOMMENDATION SYSTEM (KNN)" on the screen
87
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
88
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
89
print("\n1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Choose k 3.Train 4.Reโ€ฆ" on the screen
90
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
91
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
print("Jai Kisan!")
๐Ÿ–ฅ๏ธ Output Displays the text "Jai Kisan!" on the screen
93
break
๐Ÿ” Loop BREAK - leaves the loop immediately
94
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
95
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
96
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
97
choose_k()
๐Ÿงฎ Store / Calculate Calls our own function choose_k()
98
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
99
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
100
elif "model" not in state and ch in "456":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "456")
101
print("Train the model first (option 3).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 3)." on the screen
102
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
103
recommend()
๐Ÿงฎ Store / Calculate Calls our own function recommend()
104
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
105
test_report()
๐Ÿงฎ Store / Calculate Calls our own function test_report()
106
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
107
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
108
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
109
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CROP RECOMMENDATION SYSTEM (KNN) (+1 more lines)
  2. You type 4 at Enter choice:
    shows: Train the model first (option 3). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Records: 200 | Crops: ['rice', 'wheat', 'maize', 'cotton', 'chickpea'] (+8 more lines)
  4. You type 2 at Enter choice:
    runs: choose_k()
    shows: k = 3: folds [0.975 0.95 0.975 0.975 0.975] -> mean 97.00 % (+5 more lines)
  5. You type 3 at Enter choice:
    runs: train()
    shows: Model trained with k = 7. Hold-out accuracy: 100.00 % (+1 more lines)
  6. You type 4 at Enter choice:
    runs: recommend()
  7. You type 85 at N :
  8. You type 45 at P :
  9. You type 40 at K :
  10. You type 25 at Temp :
  11. You type 82 at Humidity :
  12. You type 6.4 at pH :
  13. You type 210 at Rainfall :
    shows: Recommended crop: RICE (+4 more lines)
  14. You type 4 at Enter choice:
    runs: recommend()
  15. You type 25 at N :
  16. You type 65 at P :
  17. You type 80 at K :
  18. You type 19 at Temp :
  19. You type 17 at Humidity :
  20. You type 7.2 at pH :
  21. You type 80 at Rainfall :
    shows: Recommended crop: CHICKPEA (+4 more lines)
  22. You type 4 at Enter choice:
    runs: recommend()
  23. You type 60 at N :
  24. You type 50 at P :
  25. You type 40 at K :
  26. You type 20 at Temp :
  27. You type 55 at Humidity :
  28. You type 15 at pH :
  29. You type 75 at Rainfall :
    shows: pH must be 0-14 and humidity 0-100. (+1 more lines)
  30. You type 5 at Enter choice:
    runs: test_report()
    shows: chickpea cotton maize rice wheat (+6 more lines)
  31. You type 6 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  32. You type 0 at Enter choice:
    shows: Jai Kisan!
โ‘ค Inside each function - line by line
summary() - lines 25โ€“27
LineCodeWhat it does
25
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
26
print("Records:", len(df), "| Crops:", df.Crop.unique().tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Records:", then the value of len(df), then the text "| Crops:", then the value of df.Crop.unique().tolist() on the screen
27
print(df.groupby("Crop")[cols].mean().round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of df.groupby("Crop")[cols].mean().round(1) on the screen
choose_k() - lines 30โ€“36
LineCodeWhat it does
30
def choose_k():
๐Ÿงฉ Function DEFINES a function choose_k(). Python only remembers it here - its body runs later, each time choose_k() is called.
31
for k in (3, 5, 7, 9):
๐Ÿ” Loop LOOP: takes each item of (3, 5, 7, 9) one-by-one into k and runs the indented block for it
32
m = make_pipeline(MinMaxScaler(), KNeighborsClassifier(n_neighbors=k))
๐Ÿงฎ Store / Calculate Joins steps (scaling + model) into one pipeline; the result is stored in variable m
33
s = cross_val_score(m, df[cols], df.Crop, cv=5)
๐Ÿ“ฆ Library / Data Trains and tests the model on several folds (cross-validation); the result is stored in variable s
34
cv_scores[k] = s.mean()
๐Ÿงฎ Store / Calculate Finds the average (mean) of s; the result is put into cv_scores[k] (item k of cv_scores)
35
print(f"k = {k}: folds {np.round(s, 3)} -> mean {s.mean() * 100:.2f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"k = {k}: folds {np.round(s, 3)} -> mean {s.โ€ฆ with the values filled into { } on the screen
36
print("Best k:", max(cv_scores, key=cv_scores.get))
๐Ÿ–ฅ๏ธ Output Displays the text "Best k:", then the value of max(cv_scores, key=cv_scores.get) on the screen
train() - lines 39โ€“44
LineCodeWhat it does
39
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
40
k = max(cv_scores, key=cv_scores.get) if cv_scores else 5
๐Ÿงฎ Store / Calculate Stores either max(cv_scores, key=cv_scores.get) or 5 depending on cv_scores in variable k
41
X_tr, X_te, y_tr, y_te = train_test_split(df[cols], df.Crop, test_size=0.25, random_state=3, stratify=df.Crop)
๐Ÿ“ฆ Library / Data Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te
42
state["model"] = make_pipeline(MinMaxScaler(), KNeighborsClassifier(n_neighbors=k)).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model make_pipeline(MinMaxScaler(), KNeighborsClassโ€ฆ on the given data; the result is put into state["model"] (item "model" of state)
43
state["test"] = (X_te, y_te)
๐Ÿงฎ Store / Calculate Puts the tuple (X_te, y_te) into state["test"] (item "test" of state)
44
print(f"Model trained with k = {k}. Hold-out accuracy: {accuracy_score(y_te, state['model'].predict(X_te)) * 100:.2f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Model trained with k = {k}. Hold-out accuraโ€ฆ with the values filled into { } on the screen
recommend() - lines 47โ€“57
LineCodeWhat it does
47
def recommend():
๐Ÿงฉ Function DEFINES a function recommend(). Python only remembers it here - its body runs later, each time recommend() is called.
48
vals = [float(input(f"  {c:<9}: ")) for c in cols]
โŒจ๏ธ Input Stores a new list made by a list comprehension [float(input(f" {c:<9}: ")) for c in cols] in variable vals
49
if not 0 <= vals[5] <= 14 or not 0 <= vals[4] <= 100:
๐Ÿ”€ Decision CHECKS whether (NOT 0 <= vals[5] <= 14 is True OR NOT 0 <= vals[4] <= 100 is True). If True, the indented lines below run; otherwise they are skipped
50
print("pH must be 0-14 and humidity 0-100.")
๐Ÿ–ฅ๏ธ Output Displays the text "pH must be 0-14 and humidity 0-10โ€ฆ" on the screen
51
return
๐Ÿงฉ Function Ends the function and goes back to the caller
52
m = state["model"]
๐Ÿงฎ Store / Calculate Stores the item state["model"] in variable m
53
proba = m.predict_proba(pd.DataFrame([vals], columns=cols))[0]
๐Ÿ“ฆ Library / Data Stores the item m.predict_proba(pd.DataFrame([vals], columns=โ€ฆ in variable proba
54
order = np.argsort(proba)[::-1][:3]
๐Ÿ“ฆ Library / Data Stores a slice np.argsort(proba)[::-1][:3] (part of np.argsort(proba)[::-1]) in variable order
55
print("Recommended crop:", m.classes_[order[0]].upper())
๐Ÿ–ฅ๏ธ Output Displays the text "Recommended crop:", then the value of m.classes_[order[0]].upper() on the screen
56
for i in order:
๐Ÿ” Loop LOOP: takes each item of order one-by-one into i and runs the indented block for it
57
print(f"   {m.classes_[i]:<9} {proba[i] * 100:5.1f} %  " + "#" * int(proba[i] * 20))
๐Ÿ–ฅ๏ธ Output Displays the value of f" {m.classes_[i]:<9} {proba[i] * 100:5.1f} %โ€ฆ on the screen
test_report() - lines 60โ€“64
LineCodeWhat it does
60
def test_report():
๐Ÿงฉ Function DEFINES a function test_report(). Python only remembers it here - its body runs later, each time test_report() is called.
61
X_te, y_te = state["test"]
๐Ÿงฎ Store / Calculate Stores the item state["test"] in variables X_te, y_te
62
p = state["model"].predict(X_te)
๐Ÿ“ฆ Library / Data Uses the trained model state["model"] to predict answers for X_te; the result is stored in variable p
63
labels = sorted(profile)
๐Ÿงฎ Store / Calculate Makes a new sorted list from profile; the result is stored in variable labels
64
print(pd.DataFrame(confusion_matrix(y_te, p, labels=labels), index=labels, columns=labels))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.DataFrame(confusion_matrix(y_te, p, labelsโ€ฆ on the screen
charts() - lines 67โ€“82
LineCodeWhat it does
67
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
68
plt.plot(list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"); plt.xlabel("k"); plt.ylabel("CV accuracy %"); plt.title("Choosing k (5-fold CV)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"
68
plt.plot(list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"); plt.xlabel("k"); plt.ylabel("CV accuracy %"); plt.title("Choosing k (5-fold CV)")
๐Ÿ–ฅ๏ธ Output Writes "k" as the label of the X-axis
68
plt.plot(list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"); plt.xlabel("k"); plt.ylabel("CV accuracy %"); plt.title("Choosing k (5-fold CV)")
๐Ÿ–ฅ๏ธ Output Writes "CV accuracy %" as the label of the Y-axis
68
plt.plot(list(cv_scores), [v * 100 for v in cv_scores.values()], "o-"); plt.xlabel("k"); plt.ylabel("CV accuracy %"); plt.title("Choosing k (5-fold CV)")
๐Ÿ–ฅ๏ธ Output Writes "Choosing k (5-fold CV)" as the title of the chart
69
plt.savefig("crop_k.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "crop_k.png"
69
plt.savefig("crop_k.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
70
norm = df.groupby("Crop")[cols].mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of df.groupby("Crop")[cols]; the result is stored in variable norm
71
norm = (norm - norm.min()) / (norm.max() - norm.min())
๐Ÿงฎ Store / Calculate Stores the value of (norm - norm.min()) / (norm.max() - norm.min(โ€ฆ (calculated using รท) in variable norm
72
norm.T.plot(kind="bar", figsize=(9, 4), title="Normalised nutrient & climate profile of crops")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
73
plt.xticks(rotation=0); plt.savefig("crop_profile.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
73
plt.xticks(rotation=0); plt.savefig("crop_profile.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "crop_profile.png"
73
plt.xticks(rotation=0); plt.savefig("crop_profile.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
74
X_te, y_te = state["test"]
๐Ÿงฎ Store / Calculate Stores the item state["test"] in variables X_te, y_te
75
labels = sorted(profile)
๐Ÿงฎ Store / Calculate Makes a new sorted list from profile; the result is stored in variable labels
76
cm = confusion_matrix(y_te, state["model"].predict(X_te), labels=labels)
๐Ÿ“ฆ Library / Data Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
77
plt.imshow(cm, cmap="Greens")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
78
for (i, j), v in np.ndenumerate(cm):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(cm) one-by-one into (i, j), v and runs the indented block for it
79
plt.text(j, i, v, ha="center", va="center")
๐Ÿ–ฅ๏ธ Output Writes text on the chart
80
plt.xticks(range(5), labels, rotation=30); plt.yticks(range(5), labels); plt.title("Confusion matrix (hold-out)")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
80
plt.xticks(range(5), labels, rotation=30); plt.yticks(range(5), labels); plt.title("Confusion matrix (hold-out)")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
80
plt.xticks(range(5), labels, rotation=30); plt.yticks(range(5), labels); plt.title("Confusion matrix (hold-out)")
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix (hold-out)" as the title of the chart
81
plt.savefig("crop_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "crop_confusion.png"
81
plt.savefig("crop_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
print("Charts saved: crop_k.png, crop_profile.png, crop_confusion.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: crop_k.png, crop_prโ€ฆ" on the screen
Q1. Why use a pipeline?

It joins scaling and the model so the same scaling is applied during training and prediction.

Q2. What is cross-validation?

Splitting data into k folds, training on k-1 and testing on 1, repeated k times; gives a reliable accuracy.

Q3. Why MinMax scaling for KNN?

Rainfall (hundreds) would dominate pH (single digits) in distance without scaling.

Q4. What is predict_proba in KNN?

Fraction of the k neighbours belonging to each crop.

Q5. Which SDG?

SDG 2 - Zero Hunger.

09

Household Energy Consumption Forecaster (SDG 7)

PYTHON + SKLEARNSDG 7 - Affordable and Clean EnergyTime-series features (month numbertemperature)linear regressiontrain on past / test on recentforecasting
๐Ÿ“ 110 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 75 output lines๐Ÿ“„ 25+ page report

Forecasts the monthly electricity units of a household from the month index and average temperature using linear regression trained on two years of sample bills, evaluates the forecast on the latest months and predicts the next three months' bills.

โœจ Features
  • 24 months of electricity units with month number and average temperature (sample bills)
  • Linear Regression with two features (trend + temperature)
  • Train on first 20 months, test on last 4; MAE and MAPE
  • Forecast next 3 months and bill with slab tariff
  • What-if: 1 degree hotter summer / AC set 2 degrees higher
  • Charts: forecast line, temperature scatter, bill bar
โ˜ฐ Main menu
1View Data24 months
2Train & TestFit model and errors
3ForecastNext 3 months units and bill
4What-ifTemperature change effect
5Seasonal SummaryAverage units by season
6Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Engineer features (trend and temperature) from time-series data
  • Use a time-ordered train-test split and evaluate with MAE
  • Forecast future units and bills with the trained model
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameMonth_no, Temp, Units
train / testDataFramesMonths 1-20 / 21-24
modelLinearRegressionUnits = a + b*Month + c*Temp
bill()functionSlab-wise bill
Why it matters: Introduces forecasting and the importance of a time-based train-test split.
# =====================================================================
#   HOUSEHOLD ENERGY CONSUMPTION FORECASTER   (SDG 7) - sample bills
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temps = [14, 17, 23, 29, 33, 34, 31, 30, 29, 26, 20, 15] * 2
rng = np.random.default_rng(1)
month_no = np.arange(1, 25)
units = 120 + 2.0 * month_no + 9 * (np.array(temps) - 14) + rng.normal(0, 12, 24)
df = pd.DataFrame({"Month_no": month_no, "Month": MONTHS * 2, "Temp": temps, "Units": units.round()})
train, test = df[df.Month_no <= 20], df[df.Month_no > 20]
F = ["Month_no", "Temp"]
model = None


def bill(u):
    slabs, amt, left = [(200, 4.0), (200, 6.0), (10000, 7.5)], 0, u
    for size, rate in slabs:
        part = min(left, size); amt += part * rate; left -= part
        if left <= 0:
            break
    return amt


def view():
    print(df.to_string(index=False))


def train_test():
    global model
    model = LinearRegression().fit(train[F], train.Units)
    pred = model.predict(test[F])
    print("Units = %.1f + %.2f x Month_no + %.2f x Temp" % (model.intercept_, *model.coef_))
    for m, a, p in zip(test.Month, test.Units, pred):
        print(f"  {m}: actual {a:.0f}, predicted {p:.0f}, error {a - p:+.0f}")
    mape = np.mean(np.abs((test.Units - pred) / test.Units)) * 100
    print(f"MAE {mean_absolute_error(test.Units, pred):.1f} units | MAPE {mape:.1f} %")


def forecast():
    fut = pd.DataFrame({"Month_no": [25, 26, 27], "Temp": [14, 17, 23]})
    fc = model.predict(fut)
    print(f"{'Month':<6}{'Units':>7}{'Bill (Rs.)':>12}")
    for m, u in zip(["Jan", "Feb", "Mar"], fc):
        print(f"{m:<6}{u:>7.0f}{bill(u):>12.0f}")
    print("Total for the quarter: Rs.", round(sum(bill(u) for u in fc)))


def what_if():
    d = float(input("Temperature change (degrees C): "))
    extra = model.coef_[1] * d
    print(f"Each month uses about {extra:+.1f} units -> Rs. {extra * 7.5:+.0f} per month at top slab")
    print("Tip: setting the AC 2 degrees higher saves roughly the same as a 2-degree cooler month.")


def seasonal():
    season = {"Jan": "Winter", "Feb": "Winter", "Dec": "Winter", "Mar": "Spring", "Apr": "Summer", "May": "Summer", "Jun": "Summer",
              "Jul": "Monsoon", "Aug": "Monsoon", "Sep": "Monsoon", "Oct": "Autumn", "Nov": "Autumn"}
    s = df.assign(Season=df.Month.map(season)).groupby("Season").Units.mean().round(1).sort_values(ascending=False)
    print(s.to_string())


def charts():
    pred = model.predict(test[F])
    fut = pd.DataFrame({"Month_no": [25, 26, 27], "Temp": [14, 17, 23]})
    fc = model.predict(fut)
    plt.plot(df.Month_no, df.Units, marker="o", label="Actual")
    plt.plot(test.Month_no, pred, "rs--", label="Predicted (test)")
    plt.plot(fut.Month_no, fc, "g^--", label="Forecast")
    plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
    plt.savefig("energy_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.scatter(df.Temp, df.Units, c=df.Month_no, cmap="viridis"); plt.colorbar(label="Month no.")
    plt.xlabel("Average temperature (C)"); plt.ylabel("Units"); plt.title("Units vs temperature")
    plt.savefig("energy_temp.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.bar(df.Month_no, [bill(u) for u in df.Units], color="#fab005"); plt.xlabel("Month no."); plt.ylabel("Rs.")
    plt.title("Monthly bill (slab tariff)"); plt.savefig("energy_bill.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: energy_forecast.png, energy_temp.png, energy_bill.png")


print("=" * 55)
print("   HOUSEHOLD ENERGY FORECASTER  (SDG 7)")
print("=" * 55)
while True:
    print("\n1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Save energy!")
        break
    elif ch == "1":
        view()
    elif ch == "2":
        train_test()
    elif ch == "5":
        seasonal()
    elif model is None and ch in "346":
        print("Train the model first (option 2).")
    elif ch == "3":
        forecast()
    elif ch == "4":
        what_if()
    elif ch == "6":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create 24-month data
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. Predict future units
  6. Compute bill with slabs
  7. Show forecast
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Train & testMAE and MAPEPASS
2ForecastJan-Mar units and billPASS
3What-if +2 CExtra unitsPASS
4Seasonal summarySummer highestPASS
5Forecast before train'Train first'PASS
6Charts3 PNG filesPASS
โš  Limitations
  • Synthetic bills
  • Only temperature and trend used
  • Linear model
  • Tariff slabs assumed
๐Ÿš€ Future scope
  • Use real 3-year bills
  • Add holidays and family size
  • Smart-meter hourly data
  • Solar savings calculator

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, LinearRegression, mean_absolute_error are loaded.
  2. Global variables / constants are created: MONTHS, temps, rng, month_no, units, df, F, model.
  3. 7 functions are defined (lines 21โ€“82) - Python stores them but does NOT run them yet.
  4. Main program starts at line 16: train, test = df[df.Month_no <= 20], df[df.Month_no > 20] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
bill(u)21โ€“27Billforecast(), charts()
view()30โ€“31Viewmain program
train_test()34โ€“42Train testmain program
forecast()45โ€“51Forecastmain program
what_if()54โ€“58What ifmain program
seasonal()61โ€“65Seasonalmain program
charts()68โ€“82Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
16
train, test = df[df.Month_no <= 20], df[df.Month_no > 20]
๐Ÿ“ฆ Library / Data Stores df[df.Month_no <= 20], df[df.Month_no > 20] into train, test respectively
17
F = ["Month_no", "Temp"]
๐Ÿงฎ Store / Calculate Stores a list ["Month_no", "Temp"] in variable F
18
model = None
๐Ÿงฎ Store / Calculate Stores None (nothing) in variable model
85
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
86
print("   HOUSEHOLD ENERGY FORECASTER  (SDG 7)")
๐Ÿ–ฅ๏ธ Output Displays the text "HOUSEHOLD ENERGY FORECASTER (SDG โ€ฆ" on the screen
87
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
88
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
89
print("\n1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Train & Test 3.Forecast โ€ฆ" on the screen
90
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
91
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
print("Save energy!")
๐Ÿ–ฅ๏ธ Output Displays the text "Save energy!" on the screen
93
break
๐Ÿ” Loop BREAK - leaves the loop immediately
94
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
95
view()
๐Ÿงฎ Store / Calculate Calls our own function view()
96
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
97
train_test()
๐Ÿงฎ Store / Calculate Calls our own function train_test()
98
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
99
seasonal()
๐Ÿงฎ Store / Calculate Calls our own function seasonal()
100
elif model is None and ch in "346":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether (model is None AND ch is present in "346")
101
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
102
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
103
forecast()
๐Ÿงฎ Store / Calculate Calls our own function forecast()
104
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
105
what_if()
๐Ÿงฎ Store / Calculate Calls our own function what_if()
106
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
107
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
108
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
109
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HOUSEHOLD ENERGY FORECASTER (SDG 7) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: view()
    shows: Month_no Month Temp Units (+25 more lines)
  4. You type 2 at Enter choice:
    runs: train_test()
    shows: Units = -1.5 + 1.58 x Month_no + 9.01 x Temp (+6 more lines)
  5. You type 3 at Enter choice:
    runs: forecast() โ†’ bill() ร—6
    shows: Month Units Bill (Rs.) (+5 more lines)
  6. You type 4 at Enter choice:
    runs: what_if()
  7. You type 2 at Temperature change (degrees C):
    shows: Each month uses about +18.0 units -> Rs. +135 per month at top slab (+2 more lines)
  8. You type 5 at Enter choice:
    runs: seasonal()
    shows: Season (+6 more lines)
  9. You type 6 at Enter choice:
    runs: charts() โ†’ bill() ร—24
    shows: [chart is drawn] (+4 more lines)
  10. You type 0 at Enter choice:
    shows: Save energy!
โ‘ค Inside each function - line by line
bill() - lines 21โ€“27
LineCodeWhat it does
21
def bill(u):
๐Ÿงฉ Function DEFINES a function bill(u). Python only remembers it here - its body runs later, each time bill() is called.
22
slabs, amt, left = [(200, 4.0), (200, 6.0), (10000, 7.5)], 0, u
๐Ÿงฎ Store / Calculate Stores [(200, 4.0), (200, 6.0), (10000, 7.5)], 0, u into slabs, amt, left respectively
23
for size, rate in slabs:
๐Ÿ” Loop LOOP: takes each item of slabs one-by-one into size, rate and runs the indented block for it
24
part = min(left, size); amt += part * rate; left -= part
๐Ÿงฎ Store / Calculate Finds the smallest value among left, size; the result is stored in variable part
24
part = min(left, size); amt += part * rate; left -= part
๐Ÿงฎ Store / Calculate Adds part * rate to amt (same as amt = amt + part * rate)
24
part = min(left, size); amt += part * rate; left -= part
๐Ÿงฎ Store / Calculate Subtracts part from left (same as left = left - part)
25
if left <= 0:
๐Ÿ”€ Decision CHECKS whether left is less than or equal to 0. If True, the indented lines below run; otherwise they are skipped
26
break
๐Ÿ” Loop BREAK - leaves the loop immediately
27
return amt
๐Ÿงฉ Function Sends back (returns) the value of amt to the line that called the function
view() - lines 30โ€“31
LineCodeWhat it does
30
def view():
๐Ÿงฉ Function DEFINES a function view(). Python only remembers it here - its body runs later, each time view() is called.
31
print(df.to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.to_string(index=False) on the screen
train_test() - lines 34โ€“42
LineCodeWhat it does
34
def train_test():
๐Ÿงฉ Function DEFINES a function train_test(). Python only remembers it here - its body runs later, each time train_test() is called.
35
global model
๐Ÿงฉ Function Tells Python that model means the GLOBAL variable (outside the function)
36
model = LinearRegression().fit(train[F], train.Units)
๐Ÿ“ฆ Library / Data Trains (fits) the model LinearRegression() on the given data; the result is stored in variable model
37
pred = model.predict(test[F])
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for test[F]; the result is stored in variable pred
38
print("Units = %.1f + %.2f x Month_no + %.2f x Temp" % (model.intercept_, *model.coef_))
๐Ÿ–ฅ๏ธ Output Displays the value of "Units = %.1f + %.2f x Month_no + %.2f x Tempโ€ฆ on the screen
39
for m, a, p in zip(test.Month, test.Units, pred):
๐Ÿ” Loop LOOP that walks through test.Month, test.Units, pred together; m, a, p get one item from each
40
print(f"  {m}: actual {a:.0f}, predicted {p:.0f}, error {a - p:+.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {m}: actual {a:.0f}, predicted {p:.0f}, erโ€ฆ with the values filled into { } on the screen
41
mape = np.mean(np.abs((test.Units - pred) / test.Units)) * 100
๐Ÿ“ฆ Library / Data Stores the value of np.mean(np.abs((test.Units - pred) / test.Uniโ€ฆ (calculated using ร—) in variable mape
42
print(f"MAE {mean_absolute_error(test.Units, pred):.1f} units | MAPE {mape:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"MAE {mean_absolute_error(test.Units, pred):โ€ฆ with the values filled into { } on the screen
forecast() - lines 45โ€“51
LineCodeWhat it does
45
def forecast():
๐Ÿงฉ Function DEFINES a function forecast(). Python only remembers it here - its body runs later, each time forecast() is called.
46
fut = pd.DataFrame({"Month_no": [25, 26, 27], "Temp": [14, 17, 23]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Month_no": [25, 26, 27], "Temp": [14, 17, 2โ€ฆ; the result is stored in variable fut
47
fc = model.predict(fut)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for fut; the result is stored in variable fc
48
print(f"{'Month':<6}{'Units':>7}{'Bill (Rs.)':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Month':<6}{'Units':>7}{'Bill (Rs.)':>12}" with the values filled into { } on the screen
49
for m, u in zip(["Jan", "Feb", "Mar"], fc):
๐Ÿ” Loop LOOP that walks through ["Jan", "Feb", "Mar"], fc together; m, u get one item from each
50
print(f"{m:<6}{u:>7.0f}{bill(u):>12.0f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{m:<6}{u:>7.0f}{bill(u):>12.0f}" with the values filled into { } on the screen
51
print("Total for the quarter: Rs.", round(sum(bill(u) for u in fc)))
๐Ÿ–ฅ๏ธ Output Displays the text "Total for the quarter: Rs.", then the value of round(sum(bill(u) for u in fc)) on the screen
what_if() - lines 54โ€“58
LineCodeWhat it does
54
def what_if():
๐Ÿงฉ Function DEFINES a function what_if(). Python only remembers it here - its body runs later, each time what_if() is called.
55
d = float(input("Temperature change (degrees C): "))
โŒจ๏ธ Input Shows "Temperature change (degrees C): ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable d
56
extra = model.coef_[1] * d
๐Ÿงฎ Store / Calculate Stores the value of model.coef_[1] * d (calculated using ร—) in variable extra
57
print(f"Each month uses about {extra:+.1f} units -> Rs. {extra * 7.5:+.0f} per month at top slab")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Each month uses about {extra:+.1f} units ->โ€ฆ with the values filled into { } on the screen
58
print("Tip: setting the AC 2 degrees higher saves roughly the same as a 2-degree cooler month.")
๐Ÿ–ฅ๏ธ Output Displays the text "Tip: setting the AC 2 degrees higโ€ฆ" on the screen
seasonal() - lines 61โ€“65
LineCodeWhat it does
61
def seasonal():
๐Ÿงฉ Function DEFINES a function seasonal(). Python only remembers it here - its body runs later, each time seasonal() is called.
62
season = {"Jan": "Winter", "Feb": "Winter", "Dec": "Winter", "Mar": "Spring", "Apr": "Summer", "May": "Summer", "Jun": "Summer",
          "Jul": "Monsoon", โ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Jan": "Winter", "Feb": "Winter", "Dec": "Wiโ€ฆ in variable season
64
s = df.assign(Season=df.Month.map(season)).groupby("Season").Units.mean().round(1).sort_values(ascending=False)
๐Ÿ“ฆ Library / Data Sorts df.assign(Season=df.Month.map(season)).groupbโ€ฆ by in descending order; the result is stored in variable s
65
print(s.to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of s.to_string() on the screen
charts() - lines 68โ€“82
LineCodeWhat it does
68
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
69
pred = model.predict(test[F])
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for test[F]; the result is stored in variable pred
70
fut = pd.DataFrame({"Month_no": [25, 26, 27], "Temp": [14, 17, 23]})
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from {"Month_no": [25, 26, 27], "Temp": [14, 17, 2โ€ฆ; the result is stored in variable fut
71
fc = model.predict(fut)
๐Ÿ“ฆ Library / Data Uses the trained model model to predict answers for fut; the result is stored in variable fc
72
plt.plot(df.Month_no, df.Units, marker="o", label="Actual")
๐Ÿ–ฅ๏ธ Output Draws a line chart of df.Month_no, df.Units
73
plt.plot(test.Month_no, pred, "rs--", label="Predicted (test)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of test.Month_no, pred, "rs--"
74
plt.plot(fut.Month_no, fc, "g^--", label="Forecast")
๐Ÿ–ฅ๏ธ Output Draws a line chart of fut.Month_no, fc, "g^--"
75
plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Month number" as the label of the X-axis
75
plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Units (kWh)" as the label of the Y-axis
75
plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Writes "Electricity units forecast" as the title of the chart
75
plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
75
plt.xlabel("Month number"); plt.ylabel("Units (kWh)"); plt.title("Electricity units forecast"); plt.legend(); plt.grid(alpha=0.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
76
plt.savefig("energy_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "energy_forecast.png"
76
plt.savefig("energy_forecast.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
77
plt.scatter(df.Temp, df.Units, c=df.Month_no, cmap="viridis"); plt.colorbar(label="Month no.")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of df.Temp, df.Units
77
plt.scatter(df.Temp, df.Units, c=df.Month_no, cmap="viridis"); plt.colorbar(label="Month no.")
๐Ÿ–ฅ๏ธ Output Shows a colour scale bar
78
plt.xlabel("Average temperature (C)"); plt.ylabel("Units"); plt.title("Units vs temperature")
๐Ÿ–ฅ๏ธ Output Writes "Average temperature (C)" as the label of the X-axis
78
plt.xlabel("Average temperature (C)"); plt.ylabel("Units"); plt.title("Units vs temperature")
๐Ÿ–ฅ๏ธ Output Writes "Units" as the label of the Y-axis
78
plt.xlabel("Average temperature (C)"); plt.ylabel("Units"); plt.title("Units vs temperature")
๐Ÿ–ฅ๏ธ Output Writes "Units vs temperature" as the title of the chart
79
plt.savefig("energy_temp.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "energy_temp.png"
79
plt.savefig("energy_temp.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
80
plt.bar(df.Month_no, [bill(u) for u in df.Units], color="#fab005"); plt.xlabel("Month no."); plt.ylabel("Rs.")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of df.Month_no, [bill(u) for u in df.Units]
80
plt.bar(df.Month_no, [bill(u) for u in df.Units], color="#fab005"); plt.xlabel("Month no."); plt.ylabel("Rs.")
๐Ÿ–ฅ๏ธ Output Writes "Month no." as the label of the X-axis
80
plt.bar(df.Month_no, [bill(u) for u in df.Units], color="#fab005"); plt.xlabel("Month no."); plt.ylabel("Rs.")
๐Ÿ–ฅ๏ธ Output Writes "Rs." as the label of the Y-axis
81
plt.title("Monthly bill (slab tariff)"); plt.savefig("energy_bill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Monthly bill (slab tariff)" as the title of the chart
81
plt.title("Monthly bill (slab tariff)"); plt.savefig("energy_bill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "energy_bill.png"
81
plt.title("Monthly bill (slab tariff)"); plt.savefig("energy_bill.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
print("Charts saved: energy_forecast.png, energy_temp.png, energy_bill.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: energy_forecast.pngโ€ฆ" on the screen
Q1. What is time-series forecasting?

Predicting future values from past data ordered in time.

Q2. Why not split randomly?

For time data, train on earlier months and test on later months to mimic real forecasting.

Q3. What is MAPE?

Mean absolute percentage error - average error as a % of actual values.

Q4. What does the temperature coefficient mean?

Extra units consumed per 1 degree rise in temperature.

Q5. Which SDG?

SDG 7 - Affordable and Clean Energy.

10

AI Bias Audit of a Loan-Approval Model (SDG 10)

PYTHON + SKLEARNSDG 10 - Reduced InequalitiesBias in dataDecision Treeapproval rate by groupdisparate impact ratiomitigation by removing proxy feature
๐Ÿ“ 109 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 72 output lines๐Ÿ“„ 25+ page report

Unit 8 (AI Ethics) in code: trains a model on biased historical loan decisions, measures approval rates for urban and rural applicants, calculates the disparate-impact ratio (four-fifths rule) and shows how removing the biased feature changes fairness.

โœจ Features
  • 400 simulated loan applications with income, repayment history and rural / urban location
  • Historical decisions contain bias against rural applicants
  • Decision Tree models trained with and without the location feature
  • Fairness metrics: approval rate by group, disparate impact ratio (80 % rule), equal-opportunity gap
  • Proxy check: PIN-code-like feature correlated with location
  • Applicant check with both models; ethics recommendations
โ˜ฐ Main menu
1Historical DataApproval rates by group
2Audit Model AWith location feature
3Audit Model BWithout location
4Proxy Feature TestModel C with PIN-zone proxy
5Check ApplicantCompare decisions of A and B
6Ethics ChecklistResponsible AI steps
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Detect bias by comparing outcomes for different groups
  • Measure fairness with the disparate-impact ratio (should be at least 0.8)
  • Mitigate bias and discuss the trade-off with accuracy
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameIncome, Good_history, Rural, Pin_zone, Approved
audit()functionTrains a tree and returns fairness metrics
modelsdictTrained models A, B, C
Why it matters: Turns the abstract idea of AI bias into numbers students can measure and fix.
# =====================================================================
#   AI BIAS AUDIT OF A LOAN-APPROVAL MODEL   (SDG 10) - simulated data
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(10)
n = 400
income = rng.normal(40, 12, n).clip(10)
history = rng.integers(0, 2, n)
rural = rng.integers(0, 2, n)
pin_zone = np.where(rng.random(n) < 0.9, rural, 1 - rural)          # 90 % matches location -> proxy
biased = 0.05 * income + 1.5 * history - 1.2 * rural
approved = (biased + rng.normal(0, 0.5, n) > 2.8).astype(int)
df = pd.DataFrame({"Income": income.round(1), "Good_history": history, "Rural": rural, "Pin_zone": pin_zone, "Approved": approved})
models, results = {}, {}


def historical():
    g = df.groupby("Rural").Approved.mean().rename({0: "Urban", 1: "Rural"})
    print("Historical approval rate:\n" + g.round(3).to_string())
    print(f"Disparate impact in history: {g['Rural'] / g['Urban']:.2f}")
    print("Same income & history, yet rural applicants were approved less -> biased data.")


def audit(features, name):
    X_tr, X_te, y_tr, y_te = train_test_split(df[features], df.Approved, test_size=0.3, random_state=0)
    m = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr)
    pred = m.predict(df[features])
    acc = (m.predict(X_te) == y_te).mean()
    u, r = pred[df.Rural == 0].mean(), pred[df.Rural == 1].mean()
    good = df.Good_history == 1
    tpr_u = pred[(df.Rural == 0) & good & (df.Income > 40)].mean()
    tpr_r = pred[(df.Rural == 1) & good & (df.Income > 40)].mean()
    models[name], results[name] = (m, features), (u, r)
    print(f"{name}: features {features}")
    print(f"  Test accuracy       : {acc:.3f}")
    print(f"  Approval urban/rural: {u:.3f} / {r:.3f}")
    print(f"  Disparate impact    : {r / u:.2f} ->", "FAIR" if r / u >= 0.8 else "BIASED (below 0.8)")
    print(f"  Equal-opportunity gap (qualified applicants): {tpr_u - tpr_r:.2f}")
    imp = {f: round(float(v), 3) for f, v in zip(features, m.feature_importances_)}
    print("  Feature importance  :", imp)


def check():
    inc, h, r = float(input("Income (thousand Rs/month): ")), int(input("Good history 1/0: ")), int(input("Rural 1/0: "))
    for name in ("Model A", "Model B"):
        if name in models:
            m, f = models[name]
            row = pd.DataFrame([{"Income": inc, "Good_history": h, "Rural": r, "Pin_zone": r}])[f]
            print(f"  {name}: {'APPROVED' if m.predict(row)[0] else 'REJECTED'}")


def ethics():
    for s in ["Check training data for historical bias", "Remove sensitive features AND their proxies", "Measure fairness metrics for every group",
              "Explain decisions to applicants", "Keep a human in the loop for rejections", "Re-audit the model regularly"]:
        print(" [ ]", s)


def charts():
    names = list(results)
    x = np.arange(len(names))
    plt.bar(x - 0.2, [results[k][0] for k in names], 0.4, label="Urban")
    plt.bar(x + 0.2, [results[k][1] for k in names], 0.4, label="Rural")
    plt.xticks(x, names); plt.ylabel("Approval rate"); plt.title("Fairness audit of models"); plt.legend()
    plt.savefig("bias_audit.png", dpi=90, bbox_inches="tight"); plt.show()
    for g, c in ((0, "tab:blue"), (1, "tab:orange")):
        d = df[df.Rural == g]
        plt.scatter(d.Income, d.Approved + (0.05 if g else -0.05), s=8, c=c, label=["Urban", "Rural"][g])
    plt.yticks([0, 1], ["Rejected", "Approved"]); plt.xlabel("Income"); plt.title("Historical decisions by income and group"); plt.legend()
    plt.savefig("bias_history.png", dpi=90, bbox_inches="tight"); plt.show()
    m, f = models["Model C"]
    plt.barh(f, m.feature_importances_, color="#7048e8"); plt.title("Model C importance - proxy carries bias")
    plt.savefig("bias_tree_importance.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: bias_audit.png, bias_history.png, bias_tree_importance.png")


print("=" * 55)
print("   AI BIAS AUDIT - LOAN APPROVAL  (SDG 10)")
print("=" * 55)
while True:
    print("\n1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Fair AI for all!")
        break
    elif ch == "1":
        historical()
    elif ch == "2":
        audit(["Income", "Good_history", "Rural"], "Model A")
    elif ch == "3":
        audit(["Income", "Good_history"], "Model B")
    elif ch == "4":
        audit(["Income", "Good_history", "Pin_zone"], "Model C")
    elif ch == "5":
        check()
    elif ch == "6":
        ethics()
    elif ch == "7":
        if len(results) < 3:
            print("Run options 2, 3 and 4 first.")
        else:
            charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Simulate biased historical data
  3. Show menu and read choice
  4. Train decision tree on chosen features
  5. Approval rate urban vs rural
  6. Ratio >= 0.8? → No: 'BIASED'
  7. 'FAIR'
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1HistoricalRural approval much lowerPASS
2Model ADisparate impact < 0.8 -> BIASEDPASS
3Model BRatio improvesPASS
4Model C (proxy)Bias returnsPASS
5Same applicant (36, good history) rural vs urbanModel A changes decision with location; Model B does notPASS
6Charts3 PNG filesPASS
โš  Limitations
  • Simulated data
  • Only one protected attribute
  • Simple fairness metrics
  • Decision tree only
๐Ÿš€ Future scope
  • Use fairness libraries (Fairlearn)
  • Explain decisions with SHAP
  • Real anonymised bank data
  • Human review workflow

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, DecisionTreeClassifier, train_test_split are loaded.
  2. Global variables / constants are created: rng, n, income, history, rural, pin_zone, biased, approved, df.
  3. 5 functions are defined (lines 22โ€“78) - Python stores them but does NOT run them yet.
  4. Main program starts at line 19: models, results = {}, {} - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
historical()22โ€“26Historicalmain program
audit(features, name)29โ€“45Auditmain program
check()48โ€“54Checkmain program
ethics()57โ€“60Ethicsmain program
charts()63โ€“78Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
19
models, results = {}, {}
๐Ÿงฎ Store / Calculate Stores {}, {} into models, results respectively
81
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
82
print("   AI BIAS AUDIT - LOAN APPROVAL  (SDG 10)")
๐Ÿ–ฅ๏ธ Output Displays the text "AI BIAS AUDIT - LOAN APPROVAL (SDโ€ฆ" on the screen
83
print("=" * 55)
๐Ÿ–ฅ๏ธ Output Displays a line of 55 "=" signs on the screen
84
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
85
print("\n1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.History 2.Model A 3.Model B 4.Pโ€ฆ" on the screen
86
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
87
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
88
print("Fair AI for all!")
๐Ÿ–ฅ๏ธ Output Displays the text "Fair AI for all!" on the screen
89
break
๐Ÿ” Loop BREAK - leaves the loop immediately
90
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
91
historical()
๐Ÿงฎ Store / Calculate Calls our own function historical()
92
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
93
audit(["Income", "Good_history", "Rural"], "Model A")
๐Ÿงฎ Store / Calculate Calls our own function audit(["Income", "Good_hiโ€ฆ, "Model A")
94
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
95
audit(["Income", "Good_history"], "Model B")
๐Ÿงฎ Store / Calculate Calls our own function audit(["Income", "Good_hiโ€ฆ, "Model B")
96
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
97
audit(["Income", "Good_history", "Pin_zone"], "Model C")
๐Ÿงฎ Store / Calculate Calls our own function audit(["Income", "Good_hiโ€ฆ, "Model C")
98
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
99
check()
๐Ÿงฎ Store / Calculate Calls our own function check()
100
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
101
ethics()
๐Ÿงฎ Store / Calculate Calls our own function ethics()
102
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
103
if len(results) < 3:
๐Ÿ”€ Decision CHECKS whether len(results) is less than 3. If True, the indented lines below run; otherwise Python jumps to the elif/else part
104
print("Run options 2, 3 and 4 first.")
๐Ÿ–ฅ๏ธ Output Displays the text "Run options 2, 3 and 4 first." on the screen
105
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
106
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
107
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
108
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: AI BIAS AUDIT - LOAN APPROVAL (SDG 10) (+1 more lines)
  2. You type 1 at Enter choice:
    runs: historical()
    shows: Historical approval rate: (+6 more lines)
  3. You type 2 at Enter choice:
    runs: audit()
    shows: Model A: features ['Income', 'Good_history', 'Rural'] (+6 more lines)
  4. You type 3 at Enter choice:
    runs: audit()
    shows: Model B: features ['Income', 'Good_history'] (+6 more lines)
  5. You type 4 at Enter choice:
    runs: audit()
    shows: Model C: features ['Income', 'Good_history', 'Pin_zone'] (+6 more lines)
  6. You type 5 at Enter choice:
    runs: check()
  7. You type 36 at Income (thousand Rs/month):
  8. You type 1 at Good history 1/0:
  9. You type 1 at Rural 1/0:
    shows: Model A: REJECTED (+2 more lines)
  10. You type 5 at Enter choice:
    runs: check()
  11. You type 36 at Income (thousand Rs/month):
  12. You type 1 at Good history 1/0:
  13. You type 0 at Rural 1/0:
    shows: Model A: APPROVED (+2 more lines)
  14. You type 6 at Enter choice:
    runs: ethics()
    shows: [ ] Check training data for historical bias (+6 more lines)
  15. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  16. You type 0 at Enter choice:
    shows: Fair AI for all!
โ‘ค Inside each function - line by line
historical() - lines 22โ€“26
LineCodeWhat it does
22
def historical():
๐Ÿงฉ Function DEFINES a function historical(). Python only remembers it here - its body runs later, each time historical() is called.
23
g = df.groupby("Rural").Approved.mean().rename({0: "Urban", 1: "Rural"})
๐Ÿ“ฆ Library / Data Renames columns/labels of df.groupby("Rural").Approved.mean(); the result is stored in variable g
24
print("Historical approval rate:\n" + g.round(3).to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "Historical approval rate:\n" + g.round(3).toโ€ฆ on the screen
25
print(f"Disparate impact in history: {g['Rural'] / g['Urban']:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Disparate impact in history: {g['Rural'] / โ€ฆ with the values filled into { } on the screen
26
print("Same income & history, yet rural applicants were approved less -> biased data.")
๐Ÿ–ฅ๏ธ Output Displays the text "Same income & history, yet rural โ€ฆ" on the screen
audit() - lines 29โ€“45
LineCodeWhat it does
29
def audit(features, name):
๐Ÿงฉ Function DEFINES a function audit(features, name). Python only remembers it here - its body runs later, each time audit() is called.
30
X_tr, X_te, y_tr, y_te = train_test_split(df[features], df.Approved, test_size=0.3, random_state=0)
๐Ÿ“ฆ Library / Data Splits the data into training and testing parts (30% for testing) and stores them in X_tr, X_te, y_tr, y_te
31
m = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model DecisionTreeClassifier(max_depth=4, random_stโ€ฆ on the given data; the result is stored in variable m
32
pred = m.predict(df[features])
๐Ÿ“ฆ Library / Data Uses the trained model m to predict answers for df[features]; the result is stored in variable pred
33
acc = (m.predict(X_te) == y_te).mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of m.predict(X_te) == y_te; the result is stored in variable acc
34
u, r = pred[df.Rural == 0].mean(), pred[df.Rural == 1].mean()
๐Ÿ“ฆ Library / Data Stores pred[df.Rural == 0].mean(), pred[df.Rural == 1].mean() into u, r respectively
35
good = df.Good_history == 1
๐Ÿ“ฆ Library / Data Stores True/False for df.Good_history is equal to 1 in variable good
36
tpr_u = pred[(df.Rural == 0) & good & (df.Income > 40)].mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of pred[(df.Rural == 0) & good & (df.Income > 40โ€ฆ; the result is stored in variable tpr_u
37
tpr_r = pred[(df.Rural == 1) & good & (df.Income > 40)].mean()
๐Ÿ“ฆ Library / Data Finds the average (mean) of pred[(df.Rural == 1) & good & (df.Income > 40โ€ฆ; the result is stored in variable tpr_r
38
models[name], results[name] = (m, features), (u, r)
๐Ÿงฎ Store / Calculate Stores the tuple (m, features), (u, r) in variables models[name], results[name]
39
print(f"{name}: features {features}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{name}: features {features}" with the values filled into { } on the screen
40
print(f"  Test accuracy       : {acc:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Test accuracy : {acc:.3f}" with the values filled into { } on the screen
41
print(f"  Approval urban/rural: {u:.3f} / {r:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Approval urban/rural: {u:.3f} / {r:.3f}" with the values filled into { } on the screen
42
print(f"  Disparate impact    : {r / u:.2f} ->", "FAIR" if r / u >= 0.8 else "BIASED (below 0.8)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Disparate impact : {r / u:.2f} ->" with the values filled into { }, then the value of "FAIR" if r / u >= 0.8 else "BIASED (below 0.โ€ฆ on the screen
43
print(f"  Equal-opportunity gap (qualified applicants): {tpr_u - tpr_r:.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" Equal-opportunity gap (qualified applicantโ€ฆ with the values filled into { } on the screen
44
imp = {f: round(float(v), 3) for f, v in zip(features, m.feature_importances_)}
๐Ÿงฎ Store / Calculate Stores a new dictionary made by a comprehension in variable imp
45
print("  Feature importance  :", imp)
๐Ÿ–ฅ๏ธ Output Displays the text "Feature importance :", then the value of imp on the screen
check() - lines 48โ€“54
LineCodeWhat it does
48
def check():
๐Ÿงฉ Function DEFINES a function check(). Python only remembers it here - its body runs later, each time check() is called.
49
inc, h, r = float(input("Income (thousand Rs/month): ")), int(input("Good history 1/0: ")), int(input("Rural 1/0: "))
โŒจ๏ธ Input Stores float(input("Income (thousand Rs/month): ")), int(input("Good history 1/0: ")), int(input("Rural 1/0: ")) into inc, h, r respectively
50
for name in ("Model A", "Model B"):
๐Ÿ” Loop LOOP: takes each item of ("Model A", "Model B") one-by-one into name and runs the indented block for it
51
if name in models:
๐Ÿ”€ Decision CHECKS whether name is present in models. If True, the indented lines below run; otherwise they are skipped
52
m, f = models[name]
๐Ÿงฎ Store / Calculate Stores the item models[name] in variables m, f
53
row = pd.DataFrame([{"Income": inc, "Good_history": h, "Rural": r, "Pin_zone": r}])[f]
๐Ÿ“ฆ Library / Data Stores the item pd.DataFrame([{"Income": inc, "Good_history":โ€ฆ in variable row
54
print(f"  {name}: {'APPROVED' if m.predict(row)[0] else 'REJECTED'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {name}: {'APPROVED' if m.predict(row)[0] eโ€ฆ with the values filled into { } on the screen
ethics() - lines 57โ€“60
LineCodeWhat it does
57
def ethics():
๐Ÿงฉ Function DEFINES a function ethics(). Python only remembers it here - its body runs later, each time ethics() is called.
58
for s in ["Check training data for historical bias", "Remove sensitive features AND their proxies", "Measure fairness metrics for every group",
          "Exโ€ฆ
๐Ÿ” Loop LOOP: takes each item of ["Check training data for historical bias", "โ€ฆ one-by-one into s and runs the indented block for it
60
print(" [ ]", s)
๐Ÿ–ฅ๏ธ Output Displays the text "[ ]", then the value of s on the screen
charts() - lines 63โ€“78
LineCodeWhat it does
63
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
64
names = list(results)
๐Ÿงฎ Store / Calculate Makes a list from results; the result is stored in variable names
65
x = np.arange(len(names))
๐Ÿ“ฆ Library / Data Makes a NumPy array of numbers from range(len(names)); the result is stored in variable x
66
plt.bar(x - 0.2, [results[k][0] for k in names], 0.4, label="Urban")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x - 0.2, [results[k][0] for k in names], 0.4
67
plt.bar(x + 0.2, [results[k][1] for k in names], 0.4, label="Rural")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of x + 0.2, [results[k][1] for k in names], 0.4
68
plt.xticks(x, names); plt.ylabel("Approval rate"); plt.title("Fairness audit of models"); plt.legend()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
68
plt.xticks(x, names); plt.ylabel("Approval rate"); plt.title("Fairness audit of models"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Approval rate" as the label of the Y-axis
68
plt.xticks(x, names); plt.ylabel("Approval rate"); plt.title("Fairness audit of models"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Fairness audit of models" as the title of the chart
68
plt.xticks(x, names); plt.ylabel("Approval rate"); plt.title("Fairness audit of models"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
69
plt.savefig("bias_audit.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "bias_audit.png"
69
plt.savefig("bias_audit.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
70
for g, c in ((0, "tab:blue"), (1, "tab:orange")):
๐Ÿ” Loop LOOP: takes each item of ((0, "tab:blue"), (1, "tab:orange")) one-by-one into g, c and runs the indented block for it
71
d = df[df.Rural == g]
๐Ÿ“ฆ Library / Data Stores the item df[df.Rural == g] in variable d
72
plt.scatter(d.Income, d.Approved + (0.05 if g else -0.05), s=8, c=c, label=["Urban", "Rural"][g])
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of d.Income, d.Approved + (0.05 if g else -0.05)
73
plt.yticks([0, 1], ["Rejected", "Approved"]); plt.xlabel("Income"); plt.title("Historical decisions by income and group"); plt.legend()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
73
plt.yticks([0, 1], ["Rejected", "Approved"]); plt.xlabel("Income"); plt.title("Historical decisions by income and group"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Income" as the label of the X-axis
73
plt.yticks([0, 1], ["Rejected", "Approved"]); plt.xlabel("Income"); plt.title("Historical decisions by income and group"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Historical decisions by income and group" as the title of the chart
73
plt.yticks([0, 1], ["Rejected", "Approved"]); plt.xlabel("Income"); plt.title("Historical decisions by income and group"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
74
plt.savefig("bias_history.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "bias_history.png"
74
plt.savefig("bias_history.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
75
m, f = models["Model C"]
๐Ÿงฎ Store / Calculate Stores the item models["Model C"] in variables m, f
76
plt.barh(f, m.feature_importances_, color="#7048e8"); plt.title("Model C importance - proxy carries bias")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
76
plt.barh(f, m.feature_importances_, color="#7048e8"); plt.title("Model C importance - proxy carries bias")
๐Ÿ–ฅ๏ธ Output Writes "Model C importance - proxy carries bias" as the title of the chart
77
plt.savefig("bias_tree_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "bias_tree_importance.png"
77
plt.savefig("bias_tree_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
78
print("Charts saved: bias_audit.png, bias_history.png, bias_tree_importance.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: bias_audit.png, biaโ€ฆ" on the screen
Q1. What is AI bias?

Systematic unfair outcomes for a group, often learnt from biased historical data.

Q2. What is the 80 % rule?

If a group's approval rate is less than 80 % of another's, the model may be discriminating.

Q3. Does removing the sensitive feature always fix bias?

No - proxies like PIN code can carry the same information.

Q4. What is a proxy feature?

A feature strongly correlated with a sensitive attribute.

Q5. Which SDG?

SDG 10 - Reduced Inequalities.

๐ŸŽ“ Class XII Artificial Intelligence (843) โ€” 10 Capstone Projects 10 projects

01

Breast Cancer Diagnosis Assistant - Classification & Evaluation (SDG 3)

PYTHON + SKLEARNSDG 3 - Good Health and Well-beingLogistic RegressionStandardScaler pipelinetrain-test splitconfusion matrixaccuracy
๐Ÿ“ 134 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 78 output lines๐Ÿ“„ 25+ page report

Builds a diagnostic-support model on the Breast Cancer Wisconsin dataset (569 tumour samples, 30 features) that classifies tumours as malignant or benign, and evaluates it with every metric of Unit 2 - explaining why recall for malignant cases matters most.

โœจ Features
  • Wisconsin Breast Cancer dataset (569 samples, 30 features) from scikit-learn
  • Pipeline: StandardScaler + Logistic Regression, stratified 75:25 split
  • Full evaluation: confusion matrix, accuracy, precision, recall, F1, ROC-AUC
  • Threshold tuning to reduce missed cancers (false negatives)
  • Comparison with Decision Tree and KNN models
  • Top influential features and patient-wise risk report
โ˜ฐ Main menu
1Dataset SummarySamples, classes, sample features
2Train ModelLogistic regression pipeline
3EvaluateConfusion matrix + metrics
4Threshold TuningRecall vs precision at 0.2-0.7
5Compare ModelsLogReg vs Tree vs KNN
6Top FeaturesLargest coefficients
7Patient Risk ReportProbability for 5 test patients
8ChartsCM, ROC, threshold
0ExitEnds program
๐ŸŽฏ Objectives
  • Apply the Data Science Methodology to a medical classification problem
  • Train a scaled Logistic Regression model with a stratified train-test split
  • Evaluate with confusion matrix, precision, recall, F1 and ROC-AUC and interpret them
๐Ÿ“š Data dictionary
NameTypePurpose
X, yarrays30 features; 1 = malignant
modelPipelineScaler + LogisticRegression
probarrayPredicted malignant probability
THRESHfloatDecision threshold
Why it matters: A complete, evaluation-focused capstone that mirrors how AI is validated before use in hospitals.
# =====================================================================
#   BREAST CANCER DIAGNOSIS ASSISTANT  (Classification & Evaluation, SDG 3)
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, roc_curve)

data = load_breast_cancer()
X, y = data.data, 1 - data.target                      # 1 = malignant (positive class)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
state = {}


def summary():
    print("Samples:", X.shape[0], "| Features:", X.shape[1])
    print("Malignant:", int(y.sum()), "| Benign:", int(len(y) - y.sum()))
    print("First 6 features:", [str(f) for f in data.feature_names[:6]])
    print("Train:", len(y_tr), "| Test:", len(y_te))


def train():
    m = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
    state["model"], state["prob"] = m, m.predict_proba(X_te)[:, 1]
    print("Logistic Regression trained on", len(y_tr), "patients.")


def metrics(pred):
    return (accuracy_score(y_te, pred), precision_score(y_te, pred), recall_score(y_te, pred), f1_score(y_te, pred))


def evaluate():
    pred = (state["prob"] >= 0.5).astype(int)
    tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel()
    print(f"Confusion matrix (positive = malignant)\n  TP = {tp}  FN = {fn}\n  FP = {fp}  TN = {tn}")
    a, p, r, f = metrics(pred)
    print(f"Accuracy {a:.4f} | Precision {p:.4f} | Recall {r:.4f} | F1 {f:.4f} | ROC-AUC {roc_auc_score(y_te, state['prob']):.4f}")
    print("Missed malignant cases (FN):", fn, "| False alarms (FP):", fp)


def thresholds():
    res = []
    print(f"{'Threshold':>9}{'FN':>5}{'FP':>5}{'Recall':>9}{'Precision':>11}")
    for t in (0.2, 0.3, 0.4, 0.5, 0.6, 0.7):
        pred = (state["prob"] >= t).astype(int)
        tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel()
        res.append((t, recall_score(y_te, pred), precision_score(y_te, pred)))
        print(f"{t:>9}{fn:>5}{fp:>5}{res[-1][1]:>9.3f}{res[-1][2]:>11.3f}")
    print("For screening choose a lower threshold (e.g. 0.3) so fewer cancers are missed.")
    return res


def compare():
    models = {"Logistic Regression": state["model"],
              "Decision Tree": DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr),
              "KNN (k=5)": make_pipeline(StandardScaler(), KNeighborsClassifier()).fit(X_tr, y_tr)}
    print(f"{'Model':<21}{'Accuracy':>9}{'Recall':>8}{'AUC':>8}")
    for n, m in models.items():
        pr = m.predict(X_te)
        print(f"{n:<21}{accuracy_score(y_te, pr):>9.3f}{recall_score(y_te, pr):>8.3f}{roc_auc_score(y_te, m.predict_proba(X_te)[:, 1]):>8.3f}")


def top_features():
    coef = state["model"][-1].coef_[0]
    order = np.argsort(np.abs(coef))[::-1][:6]
    for i in order:
        print(f"  {data.feature_names[i]:<24} {coef[i]:+.3f}  ({'raises' if coef[i] > 0 else 'lowers'} malignant risk)")


def risk_report():
    for i in range(5):
        p = state["prob"][i]
        band = "HIGH" if p >= 0.7 else "MEDIUM" if p >= 0.3 else "LOW"
        print(f"Patient T{i + 1:02d}: malignant probability {p * 100:5.1f} % -> {band:<6} | actual: {'Malignant' if y_te[i] else 'Benign'}")
    print("Note: AI assists doctors; final diagnosis needs biopsy.")


def charts():
    cm = confusion_matrix(y_te, (state["prob"] >= 0.5).astype(int))
    plt.imshow(cm, cmap="Blues")
    for i in range(2):
        for j in range(2):
            plt.text(j, i, cm[i, j], ha="center", va="center", fontsize=16)
    plt.xticks([0, 1], ["Benign", "Malignant"]); plt.yticks([0, 1], ["Benign", "Malignant"])
    plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix - test data")
    plt.savefig("cancer_cm.png", dpi=90, bbox_inches="tight"); plt.show()
    fpr, tpr, _ = roc_curve(y_te, state["prob"])
    plt.plot(fpr, tpr, label=f"AUC = {roc_auc_score(y_te, state['prob']):.3f}"); plt.plot([0, 1], [0, 1], "k--")
    plt.xlabel("False positive rate"); plt.ylabel("True positive rate (recall)"); plt.title("ROC curve"); plt.legend()
    plt.savefig("cancer_roc.png", dpi=90, bbox_inches="tight"); plt.show()
    res = thresholds()
    plt.plot([r[0] for r in res], [r[1] for r in res], "o-", label="Recall")
    plt.plot([r[0] for r in res], [r[2] for r in res], "s-", label="Precision")
    plt.xlabel("Threshold"); plt.title("Threshold tuning"); plt.legend(); plt.grid(alpha=.3)
    plt.savefig("cancer_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: cancer_cm.png, cancer_roc.png, cancer_threshold.png")


print("=" * 60)
print("   BREAST CANCER DIAGNOSIS ASSISTANT  (SDG 3)")
print("=" * 60)
while True:
    print("\n1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        train()
    elif "model" not in state and ch in "345678":
        print("Train the model first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        thresholds()
    elif ch == "5":
        compare()
    elif ch == "6":
        top_features()
    elif ch == "7":
        risk_report()
    elif ch == "8":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Load dataset and split
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. prob = predict_proba
  6. prob >= threshold? → No: Benign
  7. Malignant - refer to doctor
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Summary569 x 30PASS
2EvaluateAccuracy ~ 98 %PASS
3Threshold 0.3FN reducedPASS
4CompareLogReg best AUCPASS
5Top featuresTexture / radius worstPASS
6Risk report5 patients with %PASS
7Evaluate before train'Train first'PASS
โš  Limitations
  • Dataset from one hospital in the 1990s
  • Model is a decision-support tool only
  • No images used (features pre-computed)
  • Threshold choice needs doctors
๐Ÿš€ Future scope
  • Use mammogram images with CNN
  • Explainable AI (SHAP) for doctors
  • Larger Indian datasets
  • Integrate with hospital records

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, load_breast_cancer, train_test_split, make_pipeline, StandardScaler, LogisticRegression, DecisionTreeClassifier, KNeighborsClassifier, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, roc_curve are loaded.
  2. Global variables / constants are created: data, state.
  3. 9 functions are defined (lines 21โ€“102) - Python stores them but does NOT run them yet.
  4. Main program starts at line 16: X, y = data.data, 1 - data.target # 1 = malignant - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()21โ€“25Summarymain program
train()28โ€“31Trainmain program
metrics(pred)34โ€“35Metricsevaluate()
evaluate()38โ€“44Evaluatemain program
thresholds()47โ€“56Thresholdscharts(), main program
compare()59โ€“66Comparemain program
top_features()69โ€“73Top featuresmain program
risk_report()76โ€“81Risk reportmain program
charts()84โ€“102Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
16
X, y = data.data, 1 - data.target                      # 1 = malignant (positive class)
๐Ÿงฎ Store / Calculate Stores data.data, 1 - data.target into X, y respectively
17
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te
18
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
105
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
106
print("   BREAST CANCER DIAGNOSIS ASSISTANT  (SDG 3)")
๐Ÿ–ฅ๏ธ Output Displays the text "BREAST CANCER DIAGNOSIS ASSISTANTโ€ฆ" on the screen
107
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
108
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
109
print("\n1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Train 3.Evaluate 4.Thโ€ฆ" on the screen
110
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
111
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
112
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
113
break
๐Ÿ” Loop BREAK - leaves the loop immediately
114
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
115
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
116
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
117
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
118
elif "model" not in state and ch in "345678":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "345678")
119
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
120
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
121
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
122
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
123
thresholds()
๐Ÿงฎ Store / Calculate Calls our own function thresholds()
124
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
125
compare()
๐Ÿงฎ Store / Calculate Calls our own function compare()
126
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
127
top_features()
๐Ÿงฎ Store / Calculate Calls our own function top_features()
128
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
129
risk_report()
๐Ÿงฎ Store / Calculate Calls our own function risk_report()
130
elif ch == "8":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "8"
131
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
132
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
133
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: BREAST CANCER DIAGNOSIS ASSISTANT (SDG 3) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Samples: 569 | Features: 30 (+4 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Logistic Regression trained on 426 patients. (+1 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate() โ†’ metrics()
    shows: Confusion matrix (positive = malignant) (+5 more lines)
  6. You type 4 at Enter choice:
    runs: thresholds()
    shows: Threshold FN FP Recall Precision (+8 more lines)
  7. You type 5 at Enter choice:
    runs: compare()
    shows: Model Accuracy Recall AUC (+4 more lines)
  8. You type 6 at Enter choice:
    runs: top_features()
    shows: worst texture +1.366 (raises malignant risk) (+6 more lines)
  9. You type 7 at Enter choice:
    runs: risk_report()
    shows: Patient T01: malignant probability 99.9 % -> HIGH | actual: Malignant (+6 more lines)
  10. You type 8 at Enter choice:
    runs: charts() โ†’ thresholds()
    shows: [chart is drawn] (+12 more lines)
  11. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
summary() - lines 21โ€“25
LineCodeWhat it does
21
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
22
print("Samples:", X.shape[0], "| Features:", X.shape[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Samples:", then the value of X.shape[0], then the text "| Features:", then the value of X.shape[1] on the screen
23
print("Malignant:", int(y.sum()), "| Benign:", int(len(y) - y.sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Malignant:", then the value of int(y.sum()), then the text "| Benign:", then the value of int(len(y) - y.sum()) on the screen
24
print("First 6 features:", [str(f) for f in data.feature_names[:6]])
๐Ÿ–ฅ๏ธ Output Displays the text "First 6 features:", then the value of [str(f) for f in data.feature_names[:6]] on the screen
25
print("Train:", len(y_tr), "| Test:", len(y_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Train:", then the value of len(y_tr), then the text "| Test:", then the value of len(y_te) on the screen
train() - lines 28โ€“31
LineCodeWhat it does
28
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
29
m = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model make_pipeline(StandardScaler(), LogisticRegreโ€ฆ on the given data; the result is stored in variable m
30
state["model"], state["prob"] = m, m.predict_proba(X_te)[:, 1]
๐Ÿงฎ Store / Calculate Stores the tuple m, m.predict_proba(X_te)[:, 1] in variables state["model"], state["prob"]
31
print("Logistic Regression trained on", len(y_tr), "patients.")
๐Ÿ–ฅ๏ธ Output Displays the text "Logistic Regression trained on", then the value of len(y_tr), then the text "patients." on the screen
metrics() - lines 34โ€“35
LineCodeWhat it does
34
def metrics(pred):
๐Ÿงฉ Function DEFINES a function metrics(pred). Python only remembers it here - its body runs later, each time metrics() is called.
35
return (accuracy_score(y_te, pred), precision_score(y_te, pred), recall_score(y_te, pred), f1_score(y_te, pred))
๐Ÿงฉ Function Sends back (returns) the tuple (accuracy_score(y_te, pred), precision_score(โ€ฆ to the line that called the function
evaluate() - lines 38โ€“44
LineCodeWhat it does
38
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
39
pred = (state["prob"] >= 0.5).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of state["prob"] >= 0.5 to int; the result is stored in variable pred
40
tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel()
๐Ÿงฎ Store / Calculate Flattens confusion_matrix(y_te, pred) into 1-D; the result is stored in variables tn, fp, fn, tp
41
print(f"Confusion matrix (positive = malignant)\n  TP = {tp}  FN = {fn}\n  FP = {fp}  TN = {tn}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Confusion matrix (positive = malignant)\n Tโ€ฆ with the values filled into { } on the screen
42
a, p, r, f = metrics(pred)
๐Ÿงฎ Store / Calculate Calls our own function metrics(pred); the result is stored in variables a, p, r, f
43
print(f"Accuracy {a:.4f} | Precision {p:.4f} | Recall {r:.4f} | F1 {f:.4f} | ROC-AUC {roc_auc_score(y_te, state['prob']):.4f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Accuracy {a:.4f} | Precision {p:.4f} | Recaโ€ฆ with the values filled into { } on the screen
44
print("Missed malignant cases (FN):", fn, "| False alarms (FP):", fp)
๐Ÿ–ฅ๏ธ Output Displays the text "Missed malignant cases (FN):", then the value of fn, then the text "| False alarms (FP):", then the value of fp on the screen
thresholds() - lines 47โ€“56
LineCodeWhat it does
47
def thresholds():
๐Ÿงฉ Function DEFINES a function thresholds(). Python only remembers it here - its body runs later, each time thresholds() is called.
48
res = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable res
49
print(f"{'Threshold':>9}{'FN':>5}{'FP':>5}{'Recall':>9}{'Precision':>11}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Threshold':>9}{'FN':>5}{'FP':>5}{'Recall'โ€ฆ with the values filled into { } on the screen
50
for t in (0.2, 0.3, 0.4, 0.5, 0.6, 0.7):
๐Ÿ” Loop LOOP: takes each item of (0.2, 0.3, 0.4, 0.5, 0.6, 0.7) one-by-one into t and runs the indented block for it
51
pred = (state["prob"] >= t).astype(int)
๐Ÿงฎ Store / Calculate Changes the data type of state["prob"] >= t to int; the result is stored in variable pred
52
tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel()
๐Ÿงฎ Store / Calculate Flattens confusion_matrix(y_te, pred) into 1-D; the result is stored in variables tn, fp, fn, tp
53
res.append((t, recall_score(y_te, pred), precision_score(y_te, pred)))
๐Ÿงฎ Store / Calculate Adds (t, recall_score(y_te, pred), precision_scoreโ€ฆ at the end of list res
54
print(f"{t:>9}{fn:>5}{fp:>5}{res[-1][1]:>9.3f}{res[-1][2]:>11.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{t:>9}{fn:>5}{fp:>5}{res[-1][1]:>9.3f}{res[โ€ฆ with the values filled into { } on the screen
55
print("For screening choose a lower threshold (e.g. 0.3) so fewer cancers are missed.")
๐Ÿ–ฅ๏ธ Output Displays the text "For screening choose a lower threโ€ฆ" on the screen
56
return res
๐Ÿงฉ Function Sends back (returns) the value of res to the line that called the function
compare() - lines 59โ€“66
LineCodeWhat it does
59
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
60
models = {"Logistic Regression": state["model"],
          "Decision Tree": DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr),
          "Kโ€ฆ
๐Ÿ“ฆ Library / Data Stores a dictionary {"Logistic Regression": state["model"], "Deciโ€ฆ in variable models
63
print(f"{'Model':<21}{'Accuracy':>9}{'Recall':>8}{'AUC':>8}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Model':<21}{'Accuracy':>9}{'Recall':>8}{'โ€ฆ with the values filled into { } on the screen
64
for n, m in models.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary models; n, m get one pair each round
65
pr = m.predict(X_te)
๐Ÿ“ฆ Library / Data Uses the trained model m to predict answers for X_te; the result is stored in variable pr
66
print(f"{n:<21}{accuracy_score(y_te, pr):>9.3f}{recall_score(y_te, pr):>8.3f}{roc_auc_score(y_te, m.predict_proba(X_te)[:, 1]):>8.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{n:<21}{accuracy_score(y_te, pr):>9.3f}{recโ€ฆ with the values filled into { } on the screen
top_features() - lines 69โ€“73
LineCodeWhat it does
69
def top_features():
๐Ÿงฉ Function DEFINES a function top_features(). Python only remembers it here - its body runs later, each time top_features() is called.
70
coef = state["model"][-1].coef_[0]
๐Ÿงฎ Store / Calculate Stores the item state["model"][-1].coef_[0] in variable coef
71
order = np.argsort(np.abs(coef))[::-1][:6]
๐Ÿ“ฆ Library / Data Stores a slice np.argsort(np.abs(coef))[::-1][:6] (part of np.argsort(np.abs(coef))[::-1]) in variable order
72
for i in order:
๐Ÿ” Loop LOOP: takes each item of order one-by-one into i and runs the indented block for it
73
print(f"  {data.feature_names[i]:<24} {coef[i]:+.3f}  ({'raises' if coef[i] > 0 else 'lowers'} malignant risk)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {data.feature_names[i]:<24} {coef[i]:+.3f}โ€ฆ with the values filled into { } on the screen
risk_report() - lines 76โ€“81
LineCodeWhat it does
76
def risk_report():
๐Ÿงฉ Function DEFINES a function risk_report(). Python only remembers it here - its body runs later, each time risk_report() is called.
77
for i in range(5):
๐Ÿ” Loop LOOP: gives the numbers 0 to 4 (5 numbers); for each number, i takes that value and the indented block runs once
78
p = state["prob"][i]
๐Ÿงฎ Store / Calculate Stores the item state["prob"][i] in variable p
79
band = "HIGH" if p >= 0.7 else "MEDIUM" if p >= 0.3 else "LOW"
๐Ÿงฎ Store / Calculate Stores either "HIGH" or "MEDIUM" if p >= 0.3 else "LOW" depending on p >= 0.7 in variable band
80
print(f"Patient T{i + 1:02d}: malignant probability {p * 100:5.1f} % -> {band:<6} | actual: {'Malignant' if y_te[i] else 'Benign'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Patient T{i + 1:02d}: malignant probabilityโ€ฆ with the values filled into { } on the screen
81
print("Note: AI assists doctors; final diagnosis needs biopsy.")
๐Ÿ–ฅ๏ธ Output Displays the text "Note: AI assists doctors; final dโ€ฆ" on the screen
charts() - lines 84โ€“102
LineCodeWhat it does
84
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
85
cm = confusion_matrix(y_te, (state["prob"] >= 0.5).astype(int))
๐Ÿงฎ Store / Calculate Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
86
plt.imshow(cm, cmap="Blues")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
87
for i in range(2):
๐Ÿ” Loop LOOP: gives the numbers 0 to 1 (2 numbers); for each number, i takes that value and the indented block runs once
88
for j in range(2):
๐Ÿ” Loop LOOP: gives the numbers 0 to 1 (2 numbers); for each number, j takes that value and the indented block runs once
89
plt.text(j, i, cm[i, j], ha="center", va="center", fontsize=16)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
90
plt.xticks([0, 1], ["Benign", "Malignant"]); plt.yticks([0, 1], ["Benign", "Malignant"])
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
90
plt.xticks([0, 1], ["Benign", "Malignant"]); plt.yticks([0, 1], ["Benign", "Malignant"])
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
91
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix - test data")
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the X-axis
91
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix - test data")
๐Ÿ–ฅ๏ธ Output Writes "Actual" as the label of the Y-axis
91
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix - test data")
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix - test data" as the title of the chart
92
plt.savefig("cancer_cm.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "cancer_cm.png"
92
plt.savefig("cancer_cm.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
93
fpr, tpr, _ = roc_curve(y_te, state["prob"])
๐Ÿงฎ Store / Calculate Calls roc_curve(y_te, state["prob"]); the result is stored in variables fpr, tpr, _
94
plt.plot(fpr, tpr, label=f"AUC = {roc_auc_score(y_te, state['prob']):.3f}"); plt.plot([0, 1], [0, 1], "k--")
๐Ÿ–ฅ๏ธ Output Draws a line chart of fpr, tpr
94
plt.plot(fpr, tpr, label=f"AUC = {roc_auc_score(y_te, state['prob']):.3f}"); plt.plot([0, 1], [0, 1], "k--")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [0, 1], [0, 1], "k--"
95
plt.xlabel("False positive rate"); plt.ylabel("True positive rate (recall)"); plt.title("ROC curve"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "False positive rate" as the label of the X-axis
95
plt.xlabel("False positive rate"); plt.ylabel("True positive rate (recall)"); plt.title("ROC curve"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "True positive rate (recall)" as the label of the Y-axis
95
plt.xlabel("False positive rate"); plt.ylabel("True positive rate (recall)"); plt.title("ROC curve"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "ROC curve" as the title of the chart
95
plt.xlabel("False positive rate"); plt.ylabel("True positive rate (recall)"); plt.title("ROC curve"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
96
plt.savefig("cancer_roc.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "cancer_roc.png"
96
plt.savefig("cancer_roc.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
97
res = thresholds()
๐Ÿงฎ Store / Calculate Calls our own function thresholds(); the result is stored in variable res
98
plt.plot([r[0] for r in res], [r[1] for r in res], "o-", label="Recall")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [r[0] for r in res], [r[1] for r in res], "o-"
99
plt.plot([r[0] for r in res], [r[2] for r in res], "s-", label="Precision")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [r[0] for r in res], [r[2] for r in res], "s-"
100
plt.xlabel("Threshold"); plt.title("Threshold tuning"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Threshold" as the label of the X-axis
100
plt.xlabel("Threshold"); plt.title("Threshold tuning"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Writes "Threshold tuning" as the title of the chart
100
plt.xlabel("Threshold"); plt.title("Threshold tuning"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
100
plt.xlabel("Threshold"); plt.title("Threshold tuning"); plt.legend(); plt.grid(alpha=.3)
๐Ÿ–ฅ๏ธ Output Draws grid lines on the chart
101
plt.savefig("cancer_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "cancer_threshold.png"
101
plt.savefig("cancer_threshold.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
102
print("Charts saved: cancer_cm.png, cancer_roc.png, cancer_threshold.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: cancer_cm.png, cancโ€ฆ" on the screen
Q1. Why is recall most important here?

A false negative is a missed cancer patient; high recall reduces such misses.

Q2. What is ROC-AUC?

Area under the ROC curve; probability the model ranks a random malignant case above a benign one.

Q3. Why scale features for logistic regression?

Features have very different ranges; scaling helps the optimiser and fair coefficients.

Q4. What is the effect of lowering the threshold?

More cases predicted malignant: recall rises, precision falls.

Q5. Which SDG?

SDG 3 - Good Health and Well-being.

02

Diabetes Progression Predictor - Regression with Cross-Validation (SDG 3)

PYTHON + SKLEARNSDG 3 - Good Health and Well-beingRegression models comparisonk-fold cross-validationMAE / MSE / RMSE / R2feature importance
๐Ÿ“ 111 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 64 output lines๐Ÿ“„ 25+ page report

Predicts a quantitative measure of diabetes progression one year later from 10 baseline health variables (sklearn diabetes dataset, 442 patients), compares Linear Regression, Decision Tree and Random Forest using 5-fold cross-validation and reports MSE, RMSE and R2.

โœจ Features
  • Diabetes dataset (442 patients, 10 baseline features) from scikit-learn
  • Three regressors: Linear Regression, Decision Tree, Random Forest
  • 5-fold cross-validation RMSE with mean and standard deviation
  • Best model chosen automatically and tested on 20 % hold-out data
  • MAE, MSE, RMSE, R2 and feature importance
  • Predict progression for a test patient; 3 charts
โ˜ฐ Main menu
1Dataset SummaryShape and features
2Cross-Validate Models5-fold RMSE
3Train Best ModelFit on training data
4Test MetricsMAE, MSE, RMSE, R2
5Feature ImportanceMost influential features
6Predict a PatientChoose test patient no.
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Compare multiple regression algorithms fairly with 5-fold cross-validation
  • Evaluate with MAE, MSE, RMSE and R2 on hold-out data
  • Identify the most influential features
๐Ÿ“š Data dictionary
NameTypePurpose
X, yarrays10 features, target = disease progression after 1 year
modelsdictThree regressors
cv_rmsedictMean CV RMSE per model
beststrName of best model
Why it matters: Covers the model-validation and evaluation-metrics topics of Unit 2 on a real medical dataset.
# =====================================================================
#   DIABETES PROGRESSION PREDICTOR - REGRESSION WITH CROSS-VALIDATION
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

d = load_diabetes()
X, y = d.data, d.target
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
models = {"Linear Regression": LinearRegression(), "Decision Tree": DecisionTreeRegressor(max_depth=4, random_state=0),
          "Random Forest": RandomForestRegressor(n_estimators=200, max_depth=6, random_state=0)}
cv_rmse, cv_all, state = {}, {}, {}


def summary():
    print("Patients:", X.shape[0], "| Features:", list(d.feature_names))
    print("Target range:", y.min(), "to", y.max(), "| mean", round(y.mean(), 1))
    print("Train:", len(y_tr), "| Test:", len(y_te))


def cross_validate():
    kf = KFold(n_splits=5, shuffle=True, random_state=1)
    for name, m in models.items():
        s = -cross_val_score(m, X_tr, y_tr, cv=kf, scoring="neg_root_mean_squared_error")
        cv_rmse[name], cv_all[name] = s.mean(), s
        print(f"  {name:<18}: folds {np.round(s, 1)} -> {s.mean():.2f} (+/- {s.std():.2f})")
    print("Best model (lowest RMSE):", min(cv_rmse, key=cv_rmse.get))


def train_best():
    if not cv_rmse:
        cross_validate()
    best = min(cv_rmse, key=cv_rmse.get)
    state["best"], state["model"] = best, models[best].fit(X_tr, y_tr)
    state["pred"] = state["model"].predict(X_te)
    print(best, "trained on", len(y_tr), "patients.")


def test_metrics():
    p = state["pred"]
    mse = mean_squared_error(y_te, p)
    print(f"MAE {mean_absolute_error(y_te, p):.2f} | MSE {mse:.2f} | RMSE {np.sqrt(mse):.2f} | R2 {r2_score(y_te, p):.4f}")


def importance():
    m = state["model"]
    imp = m.feature_importances_ if hasattr(m, "feature_importances_") else np.abs(m.coef_) / np.abs(m.coef_).sum()
    state["imp"] = imp
    for i in np.argsort(imp)[::-1]:
        print(f"  {d.feature_names[i]:<4} {imp[i]:.3f}  " + "#" * int(imp[i] * 60))


def predict_patient():
    i = int(input(f"Test patient number (1-{len(y_te)}): "))
    if not 1 <= i <= len(y_te):
        print(f"Choose 1-{len(y_te)}.")
        return
    p = state["model"].predict(X_te[i - 1:i])[0]
    print(f"Patient {i}: predicted progression {p:.1f}, actual {y_te[i - 1]:.0f}, error {y_te[i - 1] - p:+.1f}")
    print("Risk:", "HIGH" if p > 200 else "MODERATE" if p > 120 else "LOW")


def charts():
    plt.scatter(y_te, state["pred"], alpha=0.7); plt.plot([y.min(), y.max()], [y.min(), y.max()], "r--")
    plt.xlabel("Actual progression"); plt.ylabel("Predicted progression"); plt.title(f"{state['best']}: actual vs predicted")
    plt.savefig("diabetes_pred.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.boxplot(list(cv_all.values())); plt.xticks([1, 2, 3], ["Linear", "Tree", "Forest"])
    plt.ylabel("RMSE"); plt.title("Cross-validation RMSE (5 folds)")
    plt.savefig("diabetes_cv.png", dpi=90, bbox_inches="tight"); plt.show()
    if "imp" not in state:
        importance()
    o = np.argsort(state["imp"])
    plt.barh(np.array(d.feature_names)[o], state["imp"][o], color="#12b886"); plt.title("Feature importance")
    plt.savefig("diabetes_importance.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: diabetes_pred.png, diabetes_cv.png, diabetes_importance.png")


print("=" * 60)
print("   DIABETES PROGRESSION PREDICTOR  (SDG 3)")
print("=" * 60)
while True:
    print("\n1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        cross_validate()
    elif ch == "3":
        train_best()
    elif "model" not in state and ch in "4567":
        print("Train the best model first (option 3).")
    elif ch == "4":
        test_metrics()
    elif ch == "5":
        importance()
    elif ch == "6":
        predict_patient()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Load data, split 80:20
  3. Show menu and read choice
  4. Cross-validate each model
  5. Choose lowest RMSE
  6. Fit best model and test
  7. Show metrics / prediction
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Summary442 x 10PASS
2CV3 RMSE valuesPASS
3Best modelLowest RMSEPASS
4Test metricsRMSE 58.5, R2 0.33PASS
5Importances5, s1, bmi topPASS
6Patient 5Predicted vs actualPASS
7Patient 500'Choose 1-89'PASS
โš  Limitations
  • Small dataset
  • Features already normalised
  • R2 is moderate - progression is hard to predict
  • No time-series follow-up
๐Ÿš€ Future scope
  • Gradient boosting / XGBoost
  • Hyper-parameter tuning with GridSearchCV
  • Indian clinical data
  • Explainable predictions for doctors

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, load_diabetes, train_test_split, cross_val_score, KFold, LinearRegression, DecisionTreeRegressor, RandomForestRegressor, mean_absolute_error, mean_squared_error, r2_score are loaded.
  2. Global variables / constants are created: d, models.
  3. 7 functions are defined (lines 21โ€“81) - Python stores them but does NOT run them yet.
  4. Main program starts at line 14: X, y = d.data, d.target - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()21โ€“24Summarymain program
cross_validate()27โ€“33Cross validatetrain_best(), main program
train_best()36โ€“42Train bestmain program
test_metrics()45โ€“48Test metricsmain program
importance()51โ€“56Importancecharts(), main program
predict_patient()59โ€“66Predict patientmain program
charts()69โ€“81Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
14
X, y = d.data, d.target
๐Ÿงฎ Store / Calculate Stores d.data, d.target into X, y respectively
15
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (20% for testing) and stores them in X_tr, X_te, y_tr, y_te
16
models = {"Linear Regression": LinearRegression(), "Decision Tree": DecisionTreeRegressor(max_depth=4, random_state=0),
          "Random Forest": RandomForeโ€ฆ
๐Ÿงฎ Store / Calculate Stores a dictionary {"Linear Regression": LinearRegression(), "Deโ€ฆ in variable models
18
cv_rmse, cv_all, state = {}, {}, {}
๐Ÿงฎ Store / Calculate Stores {}, {}, {} into cv_rmse, cv_all, state respectively
84
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
85
print("   DIABETES PROGRESSION PREDICTOR  (SDG 3)")
๐Ÿ–ฅ๏ธ Output Displays the text "DIABETES PROGRESSION PREDICTOR (Sโ€ฆ" on the screen
86
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
87
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
88
print("\n1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Cross-Validate 3.Traiโ€ฆ" on the screen
89
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
90
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
91
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
92
break
๐Ÿ” Loop BREAK - leaves the loop immediately
93
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
94
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
95
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
96
cross_validate()
๐Ÿงฎ Store / Calculate Calls our own function cross_validate()
97
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
98
train_best()
๐Ÿงฎ Store / Calculate Calls our own function train_best()
99
elif "model" not in state and ch in "4567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "4567")
100
print("Train the best model first (option 3).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the best model first (optioโ€ฆ" on the screen
101
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
102
test_metrics()
๐Ÿงฎ Store / Calculate Calls our own function test_metrics()
103
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
104
importance()
๐Ÿงฎ Store / Calculate Calls our own function importance()
105
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
106
predict_patient()
๐Ÿงฎ Store / Calculate Calls our own function predict_patient()
107
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
108
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
109
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
110
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: DIABETES PROGRESSION PREDICTOR (SDG 3) (+1 more lines)
  2. You type 3 at Enter choice:
    runs: train_best() โ†’ cross_validate()
    shows: Linear Regression : folds [54. 56. 50.8 53.5 56.2] -> 54.10 (+/- 1.94) (+5 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Patients: 442 | Features: ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6'] (+3 more lines)
  4. You type 2 at Enter choice:
    runs: cross_validate()
    shows: Linear Regression : folds [54. 56. 50.8 53.5 56.2] -> 54.10 (+/- 1.94) (+4 more lines)
  5. You type 3 at Enter choice:
    runs: train_best()
    shows: Linear Regression trained on 353 patients. (+1 more lines)
  6. You type 4 at Enter choice:
    runs: test_metrics()
    shows: MAE 46.17 | MSE 3424.26 | RMSE 58.52 | R2 0.3322 (+1 more lines)
  7. You type 5 at Enter choice:
    runs: importance()
    shows: s5 0.236 ############## (+10 more lines)
  8. You type 6 at Enter choice:
    runs: predict_patient()
  9. You type 5 at Test patient number (1-89):
    shows: Patient 5: predicted progression 187.4, actual 175, error -12.4 (+2 more lines)
  10. You type 6 at Enter choice:
    runs: predict_patient()
  11. You type 500 at Test patient number (1-89):
    shows: Choose 1-89. (+1 more lines)
  12. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  13. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
summary() - lines 21โ€“24
LineCodeWhat it does
21
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
22
print("Patients:", X.shape[0], "| Features:", list(d.feature_names))
๐Ÿ–ฅ๏ธ Output Displays the text "Patients:", then the value of X.shape[0], then the text "| Features:", then the value of list(d.feature_names) on the screen
23
print("Target range:", y.min(), "to", y.max(), "| mean", round(y.mean(), 1))
๐Ÿ–ฅ๏ธ Output Displays the text "Target range:", then the value of y.min(), then the text "to", then the value of y.max(), then the text "| mean", then the value of round(y.mean(), 1) on the screen
24
print("Train:", len(y_tr), "| Test:", len(y_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Train:", then the value of len(y_tr), then the text "| Test:", then the value of len(y_te) on the screen
cross_validate() - lines 27โ€“33
LineCodeWhat it does
27
def cross_validate():
๐Ÿงฉ Function DEFINES a function cross_validate(). Python only remembers it here - its body runs later, each time cross_validate() is called.
28
kf = KFold(n_splits=5, shuffle=True, random_state=1)
๐Ÿงฎ Store / Calculate Calls KFold(); the result is stored in variable kf
29
for name, m in models.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary models; name, m get one pair each round
30
s = -cross_val_score(m, X_tr, y_tr, cv=kf, scoring="neg_root_mean_squared_error")
๐Ÿงฎ Store / Calculate Stores -cross_val_score(m, X_tr, y_tr, cv=kf, scorinโ€ฆ in variable s
31
cv_rmse[name], cv_all[name] = s.mean(), s
๐Ÿงฎ Store / Calculate Stores the tuple s.mean(), s in variables cv_rmse[name], cv_all[name]
32
print(f"  {name:<18}: folds {np.round(s, 1)} -> {s.mean():.2f} (+/- {s.std():.2f})")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {name:<18}: folds {np.round(s, 1)} -> {s.mโ€ฆ with the values filled into { } on the screen
33
print("Best model (lowest RMSE):", min(cv_rmse, key=cv_rmse.get))
๐Ÿ–ฅ๏ธ Output Displays the text "Best model (lowest RMSE):", then the value of min(cv_rmse, key=cv_rmse.get) on the screen
train_best() - lines 36โ€“42
LineCodeWhat it does
36
def train_best():
๐Ÿงฉ Function DEFINES a function train_best(). Python only remembers it here - its body runs later, each time train_best() is called.
37
if not cv_rmse:
๐Ÿ”€ Decision CHECKS whether cv_rmse is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
38
cross_validate()
๐Ÿงฎ Store / Calculate Calls our own function cross_validate()
39
best = min(cv_rmse, key=cv_rmse.get)
๐Ÿงฎ Store / Calculate Finds the smallest value among cv_rmse; the result is stored in variable best
40
state["best"], state["model"] = best, models[best].fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Stores the tuple best, models[best].fit(X_tr, y_tr) in variables state["best"], state["model"]
41
state["pred"] = state["model"].predict(X_te)
๐Ÿ“ฆ Library / Data Uses the trained model state["model"] to predict answers for X_te; the result is put into state["pred"] (item "pred" of state)
42
print(best, "trained on", len(y_tr), "patients.")
๐Ÿ–ฅ๏ธ Output Displays the value of best, then the text "trained on", then the value of len(y_tr), then the text "patients." on the screen
test_metrics() - lines 45โ€“48
LineCodeWhat it does
45
def test_metrics():
๐Ÿงฉ Function DEFINES a function test_metrics(). Python only remembers it here - its body runs later, each time test_metrics() is called.
46
p = state["pred"]
๐Ÿงฎ Store / Calculate Stores the item state["pred"] in variable p
47
mse = mean_squared_error(y_te, p)
๐Ÿงฎ Store / Calculate Finds MSE = average of squared errors; the result is stored in variable mse
48
print(f"MAE {mean_absolute_error(y_te, p):.2f} | MSE {mse:.2f} | RMSE {np.sqrt(mse):.2f} | R2 {r2_score(y_te, p):.4f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"MAE {mean_absolute_error(y_te, p):.2f} | MSโ€ฆ with the values filled into { } on the screen
importance() - lines 51โ€“56
LineCodeWhat it does
51
def importance():
๐Ÿงฉ Function DEFINES a function importance(). Python only remembers it here - its body runs later, each time importance() is called.
52
m = state["model"]
๐Ÿงฎ Store / Calculate Stores the item state["model"] in variable m
53
imp = m.feature_importances_ if hasattr(m, "feature_importances_") else np.abs(m.coef_) / np.abs(m.coef_).sum()
๐Ÿ“ฆ Library / Data Stores either m.feature_importances_ or np.abs(m.coef_) / np.abs(m.coef_).sum() depending on hasattr(m, "feature_importances_") in variable imp
54
state["imp"] = imp
๐Ÿงฎ Store / Calculate Puts the value of imp into state["imp"] (item "imp" of state)
55
for i in np.argsort(imp)[::-1]:
๐Ÿ” Loop LOOP: takes each item of np.argsort(imp)[::-1] one-by-one into i and runs the indented block for it
56
print(f"  {d.feature_names[i]:<4} {imp[i]:.3f}  " + "#" * int(imp[i] * 60))
๐Ÿ–ฅ๏ธ Output Displays the value of f" {d.feature_names[i]:<4} {imp[i]:.3f} " + "โ€ฆ on the screen
predict_patient() - lines 59โ€“66
LineCodeWhat it does
59
def predict_patient():
๐Ÿงฉ Function DEFINES a function predict_patient(). Python only remembers it here - its body runs later, each time predict_patient() is called.
60
i = int(input(f"Test patient number (1-{len(y_te)}): "))
โŒจ๏ธ Input Shows f"Test patient number (1-{len(y_te)}): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable i
61
if not 1 <= i <= len(y_te):
๐Ÿ”€ Decision CHECKS whether NOT 1 <= i <= len(y_te) is True. If True, the indented lines below run; otherwise they are skipped
62
print(f"Choose 1-{len(y_te)}.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Choose 1-{len(y_te)}." with the values filled into { } on the screen
63
return
๐Ÿงฉ Function Ends the function and goes back to the caller
64
p = state["model"].predict(X_te[i - 1:i])[0]
๐Ÿ“ฆ Library / Data Stores the item state["model"].predict(X_te[i - 1:i])[0] in variable p
65
print(f"Patient {i}: predicted progression {p:.1f}, actual {y_te[i - 1]:.0f}, error {y_te[i - 1] - p:+.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Patient {i}: predicted progression {p:.1f},โ€ฆ with the values filled into { } on the screen
66
print("Risk:", "HIGH" if p > 200 else "MODERATE" if p > 120 else "LOW")
๐Ÿ–ฅ๏ธ Output Displays the text "Risk:", then the value of "HIGH" if p > 200 else "MODERATE" if p > 120 โ€ฆ on the screen
charts() - lines 69โ€“81
LineCodeWhat it does
69
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
70
plt.scatter(y_te, state["pred"], alpha=0.7); plt.plot([y.min(), y.max()], [y.min(), y.max()], "r--")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of y_te, state["pred"]
70
plt.scatter(y_te, state["pred"], alpha=0.7); plt.plot([y.min(), y.max()], [y.min(), y.max()], "r--")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [y.min(), y.max()], [y.min(), y.max()], "r--"
71
plt.xlabel("Actual progression"); plt.ylabel("Predicted progression"); plt.title(f"{state['best']}: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes "Actual progression" as the label of the X-axis
71
plt.xlabel("Actual progression"); plt.ylabel("Predicted progression"); plt.title(f"{state['best']}: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes "Predicted progression" as the label of the Y-axis
71
plt.xlabel("Actual progression"); plt.ylabel("Predicted progression"); plt.title(f"{state['best']}: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes f"{state['best']}: actual vs predicted" as the title of the chart
72
plt.savefig("diabetes_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "diabetes_pred.png"
72
plt.savefig("diabetes_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
73
plt.boxplot(list(cv_all.values())); plt.xticks([1, 2, 3], ["Linear", "Tree", "Forest"])
๐Ÿ–ฅ๏ธ Output Draws a box plot of list(cv_all.values())
73
plt.boxplot(list(cv_all.values())); plt.xticks([1, 2, 3], ["Linear", "Tree", "Forest"])
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
74
plt.ylabel("RMSE"); plt.title("Cross-validation RMSE (5 folds)")
๐Ÿ–ฅ๏ธ Output Writes "RMSE" as the label of the Y-axis
74
plt.ylabel("RMSE"); plt.title("Cross-validation RMSE (5 folds)")
๐Ÿ–ฅ๏ธ Output Writes "Cross-validation RMSE (5 folds)" as the title of the chart
75
plt.savefig("diabetes_cv.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "diabetes_cv.png"
75
plt.savefig("diabetes_cv.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
76
if "imp" not in state:
๐Ÿ”€ Decision CHECKS whether "imp" is not present in state. If True, the indented lines below run; otherwise they are skipped
77
importance()
๐Ÿงฎ Store / Calculate Calls our own function importance()
78
o = np.argsort(state["imp"])
๐Ÿ“ฆ Library / Data Gives the positions that would sort np; the result is stored in variable o
79
plt.barh(np.array(d.feature_names)[o], state["imp"][o], color="#12b886"); plt.title("Feature importance")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
79
plt.barh(np.array(d.feature_names)[o], state["imp"][o], color="#12b886"); plt.title("Feature importance")
๐Ÿ–ฅ๏ธ Output Writes "Feature importance" as the title of the chart
80
plt.savefig("diabetes_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "diabetes_importance.png"
80
plt.savefig("diabetes_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
81
print("Charts saved: diabetes_pred.png, diabetes_cv.png, diabetes_importance.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: diabetes_pred.png, โ€ฆ" on the screen
Q1. What is cross-validation?

The training data is split into k folds; each fold is used once for validation; results are averaged.

Q2. Why RMSE?

It is in the same unit as the target and penalises large errors.

Q3. Why does Random Forest often do better than one tree?

It averages many trees trained on random samples, reducing overfitting (variance).

Q4. What does R2 = 0.45 mean?

The model explains about 45 % of the variation in disease progression.

Q5. Why keep a separate test set?

To check final performance on data never used in model selection.

03

Handwritten Digit Recogniser using a Neural Network

PYTHON + SKLEARNSDG 4 - Quality Education (digitising records)Images as pixel arraysMulti-Layer Perceptron (inputhiddenoutput layers)activation ReLU
๐Ÿ“ 109 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 69 output lines๐Ÿ“„ 25+ page report

Trains a multi-layer neural network (MLPClassifier) on 1,797 handwritten digit images (8 x 8 pixels) to recognise digits 0-9, reports test accuracy and the most confused digits, and displays sample predictions.

โœจ Features
  • 8x8 handwritten digit images (1797) from scikit-learn, pixels scaled 0-1
  • Multi-layer perceptron (64 -> 64 -> 32 -> 10) with ReLU activation
  • Training loss curve and number of iterations
  • Accuracy, per-digit accuracy and most confused pairs
  • Experiment with hidden layer sizes (16, 64, (64,32))
  • View any test image as ASCII art with prediction; 3 charts
โ˜ฐ Main menu
1Dataset SummaryImages, shape, class counts
2Train NetworkFit MLPClassifier
3EvaluateAccuracy and confusion
4Per-digit AccuracyAccuracy for 0-9
5Architecture ExperimentDifferent hidden layers
6Show Test ImageASCII view + prediction
7ChartsSamples, loss, confusion
0ExitEnds program
๐ŸŽฏ Objectives
  • Represent images as feature vectors of pixel intensities
  • Train a neural network with two hidden layers and monitor its loss
  • Evaluate accuracy and analyse misclassified digits
๐Ÿ“š Data dictionary
NameTypePurpose
Xarray1797 x 64 pixel values / 16
netMLPClassifierNeural network
img_tearray8x8 test images
predarrayPredicted digits
Why it matters: Brings together Unit 3 (images as numbers) and Unit 6 (neural networks) in a classic computer-vision task.
# =====================================================================
#   HANDWRITTEN DIGIT RECOGNISER USING A NEURAL NETWORK
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

digits = load_digits()
X, y = digits.data / 16.0, digits.target
X_tr, X_te, y_tr, y_te, img_tr, img_te = train_test_split(X, y, digits.images, test_size=0.25, random_state=0, stratify=y)
state = {}


def summary():
    print("Images:", len(X), "| each", digits.images[0].shape, "=", X.shape[1], "inputs")
    print("Class counts:", dict(Counter(int(v) for v in y)))
    print("Train:", len(y_tr), "| Test:", len(y_te))


def train():
    net = MLPClassifier(hidden_layer_sizes=(64, 32), activation="relu", max_iter=400, random_state=1).fit(X_tr, y_tr)
    state["net"], state["pred"] = net, net.predict(X_te)
    print("Network: 64 inputs -> 64 -> 32 -> 10 outputs | weights:", sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_))
    print("Iterations:", net.n_iter_, "| loss first", round(net.loss_curve_[0], 3), "-> final", round(net.loss_, 4))


def evaluate():
    p = state["pred"]
    print("Test accuracy:", round(accuracy_score(y_te, p) * 100, 2), "%")
    wrong = [(int(a), int(b)) for a, b in zip(y_te, p) if a != b]
    print("Wrong predictions:", len(wrong), "of", len(y_te))
    print("Most confused (actual -> predicted):", Counter(wrong).most_common(3))


def per_digit():
    p = state["pred"]
    for dgt in range(10):
        m = y_te == dgt
        acc = (p[m] == dgt).mean() * 100
        print(f"  digit {dgt}: {acc:6.2f} %  " + "#" * int(acc / 5))


def experiment():
    for h in [(16,), (64,), (64, 32)]:
        n = MLPClassifier(hidden_layer_sizes=h, max_iter=400, random_state=1).fit(X_tr, y_tr)
        print(f"  hidden {str(h):<9} accuracy {accuracy_score(y_te, n.predict(X_te)) * 100:6.2f} %  iterations {n.n_iter_}")


def show_image():
    i = int(input(f"Test image number (1-{len(y_te)}): "))
    if not 1 <= i <= len(y_te):
        print(f"Choose 1-{len(y_te)}.")
        return
    img = img_te[i - 1]
    for row in img:
        print("   " + "".join("##" if v > 10 else "++" if v > 4 else ".." for v in row))
    pr = state["net"].predict_proba(X_te[i - 1:i])[0]
    print(f"Actual {y_te[i - 1]} | Predicted {pr.argmax()} with confidence {pr.max() * 100:.1f} %")


def charts():
    fig, axes = plt.subplots(2, 6, figsize=(9, 3.6))
    for ax, img, a, p in zip(axes.ravel(), img_te, y_te, state["pred"]):
        ax.imshow(img, cmap="gray_r"); ax.set_title(f"pred {p}", color="green" if a == p else "red", fontsize=10); ax.axis("off")
    plt.suptitle("Sample test images with network predictions"); plt.tight_layout(); plt.savefig("digits_pred.png", dpi=90); plt.show()
    plt.plot(state["net"].loss_curve_); plt.xlabel("Iteration"); plt.ylabel("Loss"); plt.title("Training loss curve")
    plt.savefig("digits_loss.png", dpi=90, bbox_inches="tight"); plt.show()
    cm = confusion_matrix(y_te, state["pred"])
    plt.imshow(cm, cmap="Purples")
    for (i, j), v in np.ndenumerate(cm):
        if v:
            plt.text(j, i, v, ha="center", va="center", fontsize=7)
    plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
    plt.savefig("digits_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: digits_pred.png, digits_loss.png, digits_confusion.png")


print("=" * 60)
print("   HANDWRITTEN DIGIT RECOGNISER  (Neural Network)")
print("=" * 60)
while True:
    print("\n1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        train()
    elif "net" not in state and ch in "34567":
        print("Train the network first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        per_digit()
    elif ch == "5":
        experiment()
    elif ch == "6":
        show_image()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Load and scale images
  3. Show menu and read choice
  4. Network trained? → No: train first
  5. Forward pass -> predicted digit
  6. Show accuracy / image
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1Summary1797 images 8x8PASS
2TrainLoss decreasesPASS
3EvaluateAccuracy ~ 97 %PASS
4Per-digit10 rowsPASS
5ExperimentBigger network betterPASS
6Image 4ASCII digitPASS
7Image 999'Choose 1-450'PASS
โš  Limitations
  • Low-resolution 8x8 images
  • Dense network ignores 2-D structure
  • Digits written by few people
  • No real camera input
๐Ÿš€ Future scope
  • CNN on MNIST 28x28 with Keras
  • Draw-a-digit web app
  • Recognise PIN codes on envelopes
  • Hindi (Devanagari) digits

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, Counter, load_digits, train_test_split, MLPClassifier, accuracy_score, confusion_matrix are loaded.
  2. Global variables / constants are created: digits, state.
  3. 7 functions are defined (lines 18โ€“79) - Python stores them but does NOT run them yet.
  4. Main program starts at line 13: X, y = digits.data / 16.0, digits.target - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()18โ€“21Summarymain program
train()24โ€“28Trainmain program
evaluate()31โ€“36Evaluatemain program
per_digit()39โ€“44Per digitmain program
experiment()47โ€“50Experimentmain program
show_image()53โ€“62Show imagemain program
charts()65โ€“79Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
13
X, y = digits.data / 16.0, digits.target
๐Ÿงฎ Store / Calculate Stores digits.data / 16.0, digits.target into X, y respectively
14
X_tr, X_te, y_tr, y_te, img_tr, img_te = train_test_split(X, y, digits.images, test_size=0.25, random_state=0, stratify=y)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te, img_tr, img_te
15
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
82
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
83
print("   HANDWRITTEN DIGIT RECOGNISER  (Neural Network)")
๐Ÿ–ฅ๏ธ Output Displays the text "HANDWRITTEN DIGIT RECOGNISER (Neuโ€ฆ" on the screen
84
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
85
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
86
print("\n1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Train 3.Evaluate 4.Peโ€ฆ" on the screen
87
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
88
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
89
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
90
break
๐Ÿ” Loop BREAK - leaves the loop immediately
91
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
92
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
93
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
94
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
95
elif "net" not in state and ch in "34567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("net" is not present in state AND ch is present in "34567")
96
print("Train the network first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the network first (option 2โ€ฆ" on the screen
97
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
98
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
99
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
100
per_digit()
๐Ÿงฎ Store / Calculate Calls our own function per_digit()
101
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
102
experiment()
๐Ÿงฎ Store / Calculate Calls our own function experiment()
103
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
104
show_image()
๐Ÿงฎ Store / Calculate Calls our own function show_image()
105
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
106
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
107
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
108
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HANDWRITTEN DIGIT RECOGNISER (Neural Network) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the network first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Images: 1797 | each (8, 8) = 64 inputs (+3 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Network: 64 inputs -> 64 -> 32 -> 10 outputs | weights: 6570 (+2 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate()
    shows: Test accuracy: 97.78 % (+3 more lines)
  6. You type 4 at Enter choice:
    runs: per_digit()
    shows: digit 0: 100.00 % #################### (+10 more lines)
  7. You type 5 at Enter choice:
    runs: experiment()
    shows: hidden (16,) accuracy 97.33 % iterations 400 (+3 more lines)
  8. You type 6 at Enter choice:
    runs: show_image()
  9. You type 4 at Test image number (1-450):
    shows: ....++##++...... (+9 more lines)
  10. You type 6 at Enter choice:
    runs: show_image()
  11. You type 999 at Test image number (1-450):
    shows: Choose 1-450. (+1 more lines)
  12. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  13. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
summary() - lines 18โ€“21
LineCodeWhat it does
18
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
19
print("Images:", len(X), "| each", digits.images[0].shape, "=", X.shape[1], "inputs")
๐Ÿ–ฅ๏ธ Output Displays the text "Images:", then the value of len(X), then the text "| each", then the value of digits.images[0].shape, then the text "=", then the value of X.shape[1], then the text "inputs" on the screen
20
print("Class counts:", dict(Counter(int(v) for v in y)))
๐Ÿ–ฅ๏ธ Output Displays the text "Class counts:", then the value of dict(Counter(int(v) for v in y)) on the screen
21
print("Train:", len(y_tr), "| Test:", len(y_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Train:", then the value of len(y_tr), then the text "| Test:", then the value of len(y_te) on the screen
train() - lines 24โ€“28
LineCodeWhat it does
24
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
25
net = MLPClassifier(hidden_layer_sizes=(64, 32), activation="relu", max_iter=400, random_state=1).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model MLPClassifier(hidden_layer_sizes=(64, 32), acโ€ฆ on the given data; the result is stored in variable net
26
state["net"], state["pred"] = net, net.predict(X_te)
๐Ÿ“ฆ Library / Data Stores the tuple net, net.predict(X_te) in variables state["net"], state["pred"]
27
print("Network: 64 inputs -> 64 -> 32 -> 10 outputs | weights:", sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_))
๐Ÿ–ฅ๏ธ Output Displays the text "Network: 64 inputs -> 64 -> 32 ->โ€ฆ", then the value of sum(w.size for w in net.coefs_) + sum(b.size โ€ฆ on the screen
28
print("Iterations:", net.n_iter_, "| loss first", round(net.loss_curve_[0], 3), "-> final", round(net.loss_, 4))
๐Ÿ–ฅ๏ธ Output Displays the text "Iterations:", then the value of net.n_iter_, then the text "| loss first", then the value of round(net.loss_curve_[0], 3), then the text "-> final", then the value of round(net.loss_, 4) on the screen
evaluate() - lines 31โ€“36
LineCodeWhat it does
31
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
32
p = state["pred"]
๐Ÿงฎ Store / Calculate Stores the item state["pred"] in variable p
33
print("Test accuracy:", round(accuracy_score(y_te, p) * 100, 2), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Test accuracy:", then the value of round(accuracy_score(y_te, p) * 100, 2), then the text "%" on the screen
34
wrong = [(int(a), int(b)) for a, b in zip(y_te, p) if a != b]
๐Ÿงฎ Store / Calculate Stores a new list made by a list comprehension [(int(a), int(b)) for a, b in zip(y_te, p) ifโ€ฆ in variable wrong
35
print("Wrong predictions:", len(wrong), "of", len(y_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Wrong predictions:", then the value of len(wrong), then the text "of", then the value of len(y_te) on the screen
36
print("Most confused (actual -> predicted):", Counter(wrong).most_common(3))
๐Ÿ–ฅ๏ธ Output Displays the text "Most confused (actual -> predicteโ€ฆ", then the value of Counter(wrong).most_common(3) on the screen
per_digit() - lines 39โ€“44
LineCodeWhat it does
39
def per_digit():
๐Ÿงฉ Function DEFINES a function per_digit(). Python only remembers it here - its body runs later, each time per_digit() is called.
40
p = state["pred"]
๐Ÿงฎ Store / Calculate Stores the item state["pred"] in variable p
41
for dgt in range(10):
๐Ÿ” Loop LOOP: gives the numbers 0 to 9 (10 numbers); for each number, dgt takes that value and the indented block runs once
42
m = y_te == dgt
๐Ÿงฎ Store / Calculate Stores True/False for y_te is equal to dgt in variable m
43
acc = (p[m] == dgt).mean() * 100
๐Ÿงฎ Store / Calculate Stores the value of (p[m] == dgt).mean() * 100 (calculated using ร—) in variable acc
44
print(f"  digit {dgt}: {acc:6.2f} %  " + "#" * int(acc / 5))
๐Ÿ–ฅ๏ธ Output Displays the value of f" digit {dgt}: {acc:6.2f} % " + "#" * int(acโ€ฆ on the screen
experiment() - lines 47โ€“50
LineCodeWhat it does
47
def experiment():
๐Ÿงฉ Function DEFINES a function experiment(). Python only remembers it here - its body runs later, each time experiment() is called.
48
for h in [(16,), (64,), (64, 32)]:
๐Ÿ” Loop LOOP: takes each item of [(16,), (64,), (64, 32)] one-by-one into h and runs the indented block for it
49
n = MLPClassifier(hidden_layer_sizes=h, max_iter=400, random_state=1).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model MLPClassifier(hidden_layer_sizes=h, max_iter=โ€ฆ on the given data; the result is stored in variable n
50
print(f"  hidden {str(h):<9} accuracy {accuracy_score(y_te, n.predict(X_te)) * 100:6.2f} %  iterations {n.n_iter_}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" hidden {str(h):<9} accuracy {accuracy_scorโ€ฆ with the values filled into { } on the screen
show_image() - lines 53โ€“62
LineCodeWhat it does
53
def show_image():
๐Ÿงฉ Function DEFINES a function show_image(). Python only remembers it here - its body runs later, each time show_image() is called.
54
i = int(input(f"Test image number (1-{len(y_te)}): "))
โŒจ๏ธ Input Shows f"Test image number (1-{len(y_te)}): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable i
55
if not 1 <= i <= len(y_te):
๐Ÿ”€ Decision CHECKS whether NOT 1 <= i <= len(y_te) is True. If True, the indented lines below run; otherwise they are skipped
56
print(f"Choose 1-{len(y_te)}.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Choose 1-{len(y_te)}." with the values filled into { } on the screen
57
return
๐Ÿงฉ Function Ends the function and goes back to the caller
58
img = img_te[i - 1]
๐Ÿงฎ Store / Calculate Stores the item img_te[i - 1] in variable img
59
for row in img:
๐Ÿ” Loop LOOP: takes each item of img one-by-one into row and runs the indented block for it
60
print("   " + "".join("##" if v > 10 else "++" if v > 4 else ".." for v in row))
๐Ÿ–ฅ๏ธ Output Displays the value of " " + "".join("##" if v > 10 else "++" if v >โ€ฆ on the screen
61
pr = state["net"].predict_proba(X_te[i - 1:i])[0]
๐Ÿงฎ Store / Calculate Stores the item state["net"].predict_proba(X_te[i - 1:i])[0] in variable pr
62
print(f"Actual {y_te[i - 1]} | Predicted {pr.argmax()} with confidence {pr.max() * 100:.1f} %")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Actual {y_te[i - 1]} | Predicted {pr.argmaxโ€ฆ with the values filled into { } on the screen
charts() - lines 65โ€“79
LineCodeWhat it does
65
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
66
fig, axes = plt.subplots(2, 6, figsize=(9, 3.6))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, axes
67
for ax, img, a, p in zip(axes.ravel(), img_te, y_te, state["pred"]):
๐Ÿ” Loop LOOP that walks through axes.ravel(), img_te, y_te, state["pred"] together; ax, img, a, p get one item from each
68
ax.imshow(img, cmap="gray_r"); ax.set_title(f"pred {p}", color="green" if a == p else "red", fontsize=10); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
68
ax.imshow(img, cmap="gray_r"); ax.set_title(f"pred {p}", color="green" if a == p else "red", fontsize=10); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
68
ax.imshow(img, cmap="gray_r"); ax.set_title(f"pred {p}", color="green" if a == p else "red", fontsize=10); ax.axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
69
plt.suptitle("Sample test images with network predictions"); plt.tight_layout(); plt.savefig("digits_pred.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the main title of the figure
69
plt.suptitle("Sample test images with network predictions"); plt.tight_layout(); plt.savefig("digits_pred.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
69
plt.suptitle("Sample test images with network predictions"); plt.tight_layout(); plt.savefig("digits_pred.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "digits_pred.png"
69
plt.suptitle("Sample test images with network predictions"); plt.tight_layout(); plt.savefig("digits_pred.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
70
plt.plot(state["net"].loss_curve_); plt.xlabel("Iteration"); plt.ylabel("Loss"); plt.title("Training loss curve")
๐Ÿ–ฅ๏ธ Output Draws a line chart of state["net"].loss_curve_
70
plt.plot(state["net"].loss_curve_); plt.xlabel("Iteration"); plt.ylabel("Loss"); plt.title("Training loss curve")
๐Ÿ–ฅ๏ธ Output Writes "Iteration" as the label of the X-axis
70
plt.plot(state["net"].loss_curve_); plt.xlabel("Iteration"); plt.ylabel("Loss"); plt.title("Training loss curve")
๐Ÿ–ฅ๏ธ Output Writes "Loss" as the label of the Y-axis
70
plt.plot(state["net"].loss_curve_); plt.xlabel("Iteration"); plt.ylabel("Loss"); plt.title("Training loss curve")
๐Ÿ–ฅ๏ธ Output Writes "Training loss curve" as the title of the chart
71
plt.savefig("digits_loss.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "digits_loss.png"
71
plt.savefig("digits_loss.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
72
cm = confusion_matrix(y_te, state["pred"])
๐Ÿงฎ Store / Calculate Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
73
plt.imshow(cm, cmap="Purples")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
74
for (i, j), v in np.ndenumerate(cm):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(cm) one-by-one into (i, j), v and runs the indented block for it
75
if v:
๐Ÿ”€ Decision CHECKS whether v is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
76
plt.text(j, i, v, ha="center", va="center", fontsize=7)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
77
plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
77
plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
77
plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the X-axis
77
plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Writes "Actual" as the label of the Y-axis
77
plt.xticks(range(10)); plt.yticks(range(10)); plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix" as the title of the chart
78
plt.savefig("digits_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "digits_confusion.png"
78
plt.savefig("digits_confusion.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
79
print("Charts saved: digits_pred.png, digits_loss.png, digits_confusion.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: digits_pred.png, diโ€ฆ" on the screen
Q1. What is a neuron in an MLP?

It computes a weighted sum of inputs plus bias and applies an activation function.

Q2. Why ReLU?

max(0, x) is simple, avoids vanishing gradients and trains fast.

Q3. How many outputs and why?

10 - one for each digit class; the highest output is the prediction.

Q4. What is loss?

A measure of error minimised during training (log-loss for classification).

Q5. What is backpropagation?

Algorithm that computes gradients of the loss and updates weights layer by layer.

04

Celsius to Fahrenheit Neural Network with TensorFlow-Keras

PYTHON + TENSORFLOWSDG 4 - Quality EducationTensorFlow / Keras Sequential modelDense layerloss function (MSE)Adam optimiserepochs
๐Ÿ“ 112 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 66 output lines๐Ÿ“„ 25+ page report

Builds and trains a one-neuron neural network in TensorFlow-Keras that discovers the Celsius-to-Fahrenheit formula from examples, plots the loss curve, inspects the learnt weight and bias and converts temperatures entered by the user.

โœจ Features
  • Seven Celsius / Fahrenheit pairs as training data
  • TensorFlow-Keras Sequential model with one Dense neuron (weight + bias)
  • Training for 1000 epochs with Adam optimiser; loss history
  • Learnt formula compared with F = 1.8C + 32
  • Learning-rate experiment (0.01, 0.1, 1.0)
  • Convert any temperature and compare with formula; 3 charts
โ˜ฐ Main menu
1Show Training DataC and F pairs
2Build & TrainKeras model, 1000 epochs
3Learnt FormulaWeight and bias
4Convert TemperatureNN vs formula
5Learning-rate ExperimentLoss after 200 epochs
6Model SummaryLayers and parameters
7ChartsLoss, fit, learning rates
0ExitEnds program
๐ŸŽฏ Objectives
  • Build, compile and train a Keras Sequential model
  • Visualise how the loss falls during training
  • Inspect learnt parameters and use the model for prediction
๐Ÿ“š Data dictionary
NameTypePurpose
celsius, fahrenheitarraysTraining pairs
modelkeras.SequentialDense(1) network
historyHistoryLoss per epoch
w, bfloatLearnt weight and bias
Why it matters: The Unit 6 practical 'Build a TensorFlow model to convert Celsius to Fahrenheit', extended with loss visualisation and model inspection.
# =====================================================================
#   CELSIUS TO FAHRENHEIT NEURAL NETWORK WITH TENSORFLOW-KERAS
# =====================================================================
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

tf.random.set_seed(42)
celsius = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit = np.array([-40, 14, 32, 46.4, 59, 71.6, 100.4], dtype=float)
state = {}


def build(lr=0.1):
    m = tf.keras.Sequential([tf.keras.Input(shape=(1,)), tf.keras.layers.Dense(units=1)])
    m.compile(loss="mean_squared_error", optimizer=tf.keras.optimizers.Adam(lr))
    return m


def show_data():
    print(f"{'Celsius':>8}{'Fahrenheit':>12}")
    for c, f in zip(celsius, fahrenheit):
        print(f"{c:>8.1f}{f:>12.1f}")


def train():
    m = build()
    h = m.fit(celsius, fahrenheit, epochs=1000, verbose=0)
    state["model"], state["loss"] = m, h.history["loss"]
    l = state["loss"]
    print(f"Loss epoch 1: {l[0]:.2f} | epoch 100: {l[99]:.2f} | epoch 500: {l[499]:.2f} | epoch 1000: {l[-1]:.4f}")


def formula():
    w, b = state["model"].layers[0].get_weights()
    state["wb"] = (w[0][0], b[0])
    print("Learnt formula: F = %.4f x C + %.4f   (true: 1.8 x C + 32)" % state["wb"])


def convert():
    try:
        c = float(input("Temperature in Celsius: "))
    except ValueError:
        print("Enter a number.")
        return
    f = state["model"].predict(np.array([[c]]), verbose=0)[0][0]
    print(f"Neural network: {f:.2f} F | Formula: {c * 1.8 + 32:.2f} F | difference {abs(f - (c * 1.8 + 32)):.3f}")


def lr_experiment():
    state["lr"] = {}
    for lr in (0.01, 0.1, 1.0):
        tf.random.set_seed(42)
        h = build(lr).fit(celsius, fahrenheit, epochs=200, verbose=0).history["loss"]
        state["lr"][lr] = h
        print(f"  learning rate {lr:<5}: loss after 200 epochs = {h[-1]:10.4f}")
    best = min(state["lr"], key=lambda k: state["lr"][k][-1])
    print(f"Lowest loss with learning rate {best}; 0.01 is far too slow for this problem.")


def summary():
    m = state["model"]
    for layer in m.layers:
        print(f"Layer: {layer.name} | type Dense | units {layer.units} | params {layer.count_params()}")
    print("Total trainable parameters:", m.count_params(), "(1 weight + 1 bias)")


def charts():
    plt.plot(state["loss"]); plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss (MSE, log scale)")
    plt.title("Training loss of the neural network"); plt.savefig("tf_loss.png", dpi=90, bbox_inches="tight"); plt.show()
    xs = np.linspace(-50, 110, 50)
    plt.scatter(celsius, fahrenheit, c="red", zorder=3, label="Training data")
    plt.plot(xs, state["model"].predict(xs.reshape(-1, 1), verbose=0).ravel(), label="Neural network")
    plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
    plt.savefig("tf_fit.png", dpi=90, bbox_inches="tight"); plt.show()
    if "lr" not in state:
        lr_experiment()
    for lr, h in state["lr"].items():
        plt.plot(h, label=f"lr = {lr}")
    plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
    plt.savefig("tf_lr.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: tf_loss.png, tf_fit.png, tf_lr.png")


print("=" * 60)
print("   CELSIUS -> FAHRENHEIT NEURAL NETWORK  (TensorFlow-Keras)")
print("=" * 60)
while True:
    print("\n1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        show_data()
    elif ch == "2":
        train()
    elif "model" not in state and ch in "34567":
        print("Train the model first (option 2).")
    elif ch == "3":
        formula()
    elif ch == "4":
        convert()
    elif ch == "5":
        lr_experiment()
    elif ch == "6":
        summary()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Model trained? → No: build and train
  4. model.fit(epochs=1000)
  5. Read weights
  6. Convert input temperature
  7. Choice is 0? → No: show menu
  8. Stop
#Test case / inputExpected resultStatus
1TrainLoss falls to near 0PASS
2Formulaw ~ 1.8, b ~ 32PASS
3100 C~ 212 FPASS
4-40 C~ -40 FPASS
536.6 C~ 97.9 FPASS
6LR experimentHigher rate converges faster herePASS
7Convert 'abc''Enter a number'PASS
โš  Limitations
  • Toy problem with a known formula
  • Very small dataset
  • Single neuron only
  • Training is random (seeded)
๐Ÿš€ Future scope
  • Deeper networks for non-linear problems
  • Predict feels-like temperature with humidity
  • Deploy with TensorFlow Lite
  • Visualise with TensorBoard

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, tensorflow - deep learning, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: celsius, fahrenheit, state.
  3. 8 functions are defined (lines 14โ€“82) - Python stores them but does NOT run them yet.
  4. Main program starts at line 8: tf.random.set_seed(42) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
build(lr)14โ€“17Buildtrain(), lr_experiment()
show_data()20โ€“23Show datamain program
train()26โ€“31Trainmain program
formula()34โ€“37Formulamain program
convert()40โ€“47Convertmain program
lr_experiment()50โ€“58Lr experimentcharts(), main program
summary()61โ€“65Summarymain program
charts()68โ€“82Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
8
tf.random.set_seed(42)
๐Ÿงฎ Store / Calculate Calls tf.random.set_seed(42)
9
celsius = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
๐Ÿ“ฆ Library / Data Makes a NumPy array from [-40, -10, 0, 8, 15, 22, 38]; the result is stored in variable celsius
10
fahrenheit = np.array([-40, 14, 32, 46.4, 59, 71.6, 100.4], dtype=float)
๐Ÿ“ฆ Library / Data Makes a NumPy array from [-40, 14, 32, 46.4, 59, 71.6, 100.4]; the result is stored in variable fahrenheit
11
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
85
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
86
print("   CELSIUS -> FAHRENHEIT NEURAL NETWORK  (TensorFlow-Keras)")
๐Ÿ–ฅ๏ธ Output Displays the text "CELSIUS -> FAHRENHEIT NEURAL NETWโ€ฆ" on the screen
87
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
88
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
89
print("\n1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Data 2.Train 3.Formula 4.Converโ€ฆ" on the screen
90
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
91
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
92
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
93
break
๐Ÿ” Loop BREAK - leaves the loop immediately
94
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
95
show_data()
๐Ÿงฎ Store / Calculate Calls our own function show_data()
96
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
97
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
98
elif "model" not in state and ch in "34567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "34567")
99
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
100
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
101
formula()
๐Ÿงฎ Store / Calculate Calls our own function formula()
102
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
103
convert()
๐Ÿงฎ Store / Calculate Calls our own function convert()
104
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
105
lr_experiment()
๐Ÿงฎ Store / Calculate Calls our own function lr_experiment()
106
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
107
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
108
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
109
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
110
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
111
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Inside each function - line by line
build() - lines 14โ€“17
LineCodeWhat it does
14
def build(lr=0.1):
๐Ÿงฉ Function DEFINES a function build(lr). Python only remembers it here - its body runs later, each time build() is called.
15
m = tf.keras.Sequential([tf.keras.Input(shape=(1,)), tf.keras.layers.Dense(units=1)])
๐Ÿงฎ Store / Calculate Calls tf.keras.Sequential([tf.keras.Input(shape=(1โ€ฆ); the result is stored in variable m
16
m.compile(loss="mean_squared_error", optimizer=tf.keras.optimizers.Adam(lr))
๐Ÿงฎ Store / Calculate Calls m.compile()
17
return m
๐Ÿงฉ Function Sends back (returns) the value of m to the line that called the function
show_data() - lines 20โ€“23
LineCodeWhat it does
20
def show_data():
๐Ÿงฉ Function DEFINES a function show_data(). Python only remembers it here - its body runs later, each time show_data() is called.
21
print(f"{'Celsius':>8}{'Fahrenheit':>12}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{'Celsius':>8}{'Fahrenheit':>12}" with the values filled into { } on the screen
22
for c, f in zip(celsius, fahrenheit):
๐Ÿ” Loop LOOP that walks through celsius, fahrenheit together; c, f get one item from each
23
print(f"{c:>8.1f}{f:>12.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"{c:>8.1f}{f:>12.1f}" with the values filled into { } on the screen
train() - lines 26โ€“31
LineCodeWhat it does
26
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
27
m = build()
๐Ÿงฎ Store / Calculate Calls our own function build(); the result is stored in variable m
28
h = m.fit(celsius, fahrenheit, epochs=1000, verbose=0)
๐Ÿ“ฆ Library / Data Trains (fits) the model m on the given data; the result is stored in variable h
29
state["model"], state["loss"] = m, h.history["loss"]
๐Ÿงฎ Store / Calculate Stores the tuple m, h.history["loss"] in variables state["model"], state["loss"]
30
l = state["loss"]
๐Ÿงฎ Store / Calculate Stores the item state["loss"] in variable l
31
print(f"Loss epoch 1: {l[0]:.2f} | epoch 100: {l[99]:.2f} | epoch 500: {l[499]:.2f} | epoch 1000: {l[-1]:.4f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Loss epoch 1: {l[0]:.2f} | epoch 100: {l[99โ€ฆ with the values filled into { } on the screen
formula() - lines 34โ€“37
LineCodeWhat it does
34
def formula():
๐Ÿงฉ Function DEFINES a function formula(). Python only remembers it here - its body runs later, each time formula() is called.
35
w, b = state["model"].layers[0].get_weights()
๐Ÿงฎ Store / Calculate Calls state["model"].layers[0].get_weights(); the result is stored in variables w, b
36
state["wb"] = (w[0][0], b[0])
๐Ÿงฎ Store / Calculate Puts the tuple (w[0][0], b[0]) into state["wb"] (item "wb" of state)
37
print("Learnt formula: F = %.4f x C + %.4f   (true: 1.8 x C + 32)" % state["wb"])
๐Ÿ–ฅ๏ธ Output Displays the value of "Learnt formula: F = %.4f x C + %.4f (true: 1โ€ฆ on the screen
convert() - lines 40โ€“47
LineCodeWhat it does
40
def convert():
๐Ÿงฉ Function DEFINES a function convert(). Python only remembers it here - its body runs later, each time convert() is called.
41
try:
๐Ÿ›ก๏ธ Error handling TRY block - Python runs these lines; if an error occurs, it jumps to the matching except block instead of crashing
42
c = float(input("Temperature in Celsius: "))
โŒจ๏ธ Input Shows "Temperature in Celsius: ", reads what the user types, and float() converts that text into a decimal number; the number is stored in variable c
43
except ValueError:
๐Ÿ›ก๏ธ Error handling EXCEPT: runs only if ValueError occurs - wrong type of value (e.g. letters typed where a number was expected)
44
print("Enter a number.")
๐Ÿ–ฅ๏ธ Output Displays the text "Enter a number." on the screen
45
return
๐Ÿงฉ Function Ends the function and goes back to the caller
46
f = state["model"].predict(np.array([[c]]), verbose=0)[0][0]
๐Ÿ“ฆ Library / Data Stores the item state["model"].predict(np.array([[c]]), verboโ€ฆ in variable f
47
print(f"Neural network: {f:.2f} F | Formula: {c * 1.8 + 32:.2f} F | difference {abs(f - (c * 1.8 + 32)):.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Neural network: {f:.2f} F | Formula: {c * 1โ€ฆ with the values filled into { } on the screen
lr_experiment() - lines 50โ€“58
LineCodeWhat it does
50
def lr_experiment():
๐Ÿงฉ Function DEFINES a function lr_experiment(). Python only remembers it here - its body runs later, each time lr_experiment() is called.
51
state["lr"] = {}
๐Ÿงฎ Store / Calculate Puts an empty dictionary {} into state["lr"] (item "lr" of state)
52
for lr in (0.01, 0.1, 1.0):
๐Ÿ” Loop LOOP: takes each item of (0.01, 0.1, 1.0) one-by-one into lr and runs the indented block for it
53
tf.random.set_seed(42)
๐Ÿงฎ Store / Calculate Calls tf.random.set_seed(42)
54
h = build(lr).fit(celsius, fahrenheit, epochs=200, verbose=0).history["loss"]
๐Ÿ“ฆ Library / Data Stores the item build(lr).fit(celsius, fahrenheit, epochs=200โ€ฆ in variable h
55
state["lr"][lr] = h
๐Ÿงฎ Store / Calculate Puts the value of h into state["lr"][lr] (item lr of state["lr"])
56
print(f"  learning rate {lr:<5}: loss after 200 epochs = {h[-1]:10.4f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" learning rate {lr:<5}: loss after 200 epocโ€ฆ with the values filled into { } on the screen
57
best = min(state["lr"], key=lambda k: state["lr"][k][-1])
๐Ÿงฎ Store / Calculate Finds the smallest value among state["lr"]; the result is stored in variable best
58
print(f"Lowest loss with learning rate {best}; 0.01 is far too slow for this problem.")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Lowest loss with learning rate {best}; 0.01โ€ฆ with the values filled into { } on the screen
summary() - lines 61โ€“65
LineCodeWhat it does
61
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
62
m = state["model"]
๐Ÿงฎ Store / Calculate Stores the item state["model"] in variable m
63
for layer in m.layers:
๐Ÿ” Loop LOOP: takes each item of m.layers one-by-one into layer and runs the indented block for it
64
print(f"Layer: {layer.name} | type Dense | units {layer.units} | params {layer.count_params()}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Layer: {layer.name} | type Dense | units {lโ€ฆ with the values filled into { } on the screen
65
print("Total trainable parameters:", m.count_params(), "(1 weight + 1 bias)")
๐Ÿ–ฅ๏ธ Output Displays the text "Total trainable parameters:", then the value of m.count_params(), then the text "(1 weight + 1 bias)" on the screen
charts() - lines 68โ€“82
LineCodeWhat it does
68
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
69
plt.plot(state["loss"]); plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss (MSE, log scale)")
๐Ÿ–ฅ๏ธ Output Draws a line chart of state["loss"]
69
plt.plot(state["loss"]); plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss (MSE, log scale)")
๐Ÿ–ฅ๏ธ Output Calls plt.yscale("log")
69
plt.plot(state["loss"]); plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss (MSE, log scale)")
๐Ÿ–ฅ๏ธ Output Writes "Epoch" as the label of the X-axis
69
plt.plot(state["loss"]); plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss (MSE, log scale)")
๐Ÿ–ฅ๏ธ Output Writes "Loss (MSE, log scale)" as the label of the Y-axis
70
plt.title("Training loss of the neural network"); plt.savefig("tf_loss.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Training loss of the neural network" as the title of the chart
70
plt.title("Training loss of the neural network"); plt.savefig("tf_loss.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "tf_loss.png"
70
plt.title("Training loss of the neural network"); plt.savefig("tf_loss.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
71
xs = np.linspace(-50, 110, 50)
๐Ÿ“ฆ Library / Data Makes 50 equally spaced numbers from -50 to 110; the result is stored in variable xs
72
plt.scatter(celsius, fahrenheit, c="red", zorder=3, label="Training data")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of celsius, fahrenheit
73
plt.plot(xs, state["model"].predict(xs.reshape(-1, 1), verbose=0).ravel(), label="Neural network")
๐Ÿ–ฅ๏ธ Output Draws a line chart of xs, state["model"].predict(xs.reshape(-1, 1), verโ€ฆ
74
plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
๐Ÿ–ฅ๏ธ Output Draws a line chart of xs, xs * 1.8 + 32, "k:"
74
plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
๐Ÿ–ฅ๏ธ Output Writes "Celsius" as the label of the X-axis
74
plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
๐Ÿ–ฅ๏ธ Output Writes "Fahrenheit" as the label of the Y-axis
74
plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
74
plt.plot(xs, xs * 1.8 + 32, "k:", label="True formula"); plt.xlabel("Celsius"); plt.ylabel("Fahrenheit"); plt.legend(); plt.title("Learnt relation")
๐Ÿ–ฅ๏ธ Output Writes "Learnt relation" as the title of the chart
75
plt.savefig("tf_fit.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "tf_fit.png"
75
plt.savefig("tf_fit.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
76
if "lr" not in state:
๐Ÿ”€ Decision CHECKS whether "lr" is not present in state. If True, the indented lines below run; otherwise they are skipped
77
lr_experiment()
๐Ÿงฎ Store / Calculate Calls our own function lr_experiment()
78
for lr, h in state["lr"].items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary state["lr"]; lr, h get one pair each round
79
plt.plot(h, label=f"lr = {lr}")
๐Ÿ–ฅ๏ธ Output Draws a line chart of h
80
plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
๐Ÿ–ฅ๏ธ Output Calls plt.yscale("log")
80
plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Epoch" as the label of the X-axis
80
plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Loss" as the label of the Y-axis
80
plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Effect of learning rate" as the title of the chart
80
plt.yscale("log"); plt.xlabel("Epoch"); plt.ylabel("Loss"); plt.title("Effect of learning rate"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
81
plt.savefig("tf_lr.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "tf_lr.png"
81
plt.savefig("tf_lr.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
print("Charts saved: tf_loss.png, tf_fit.png, tf_lr.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: tf_loss.png, tf_fitโ€ฆ" on the screen
Q1. What does a Dense layer compute?

output = activation(w . x + b); here linear, so F = w x C + b.

Q2. What is an epoch?

One complete pass of the training data through the network.

Q3. What is the role of the optimiser?

Adam updates weights using gradients to reduce loss.

Q4. Effect of a too-high learning rate?

Loss can oscillate or diverge; too low makes training slow.

Q5. Why is this machine learning, not programming?

We gave examples, not the formula; the network learnt w and b itself.

05

School Health Records - Data Cleaning & CSV Pipeline (SDG 3)

PYTHON + PANDASSDG 3 - Good Health and Well-beingread_csv / to_csvdata auditmissing-value strategiesoutlier checkderived columns
๐Ÿ“ 120 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 82 output lines๐Ÿ“„ 25+ page report

Imports a school health-survey CSV with gaps, audits the data quality, fills missing values with suitable strategies, detects outliers, computes BMI categories and sleep adequacy, exports a clean file and a class summary CSV.

โœจ Features
  • Raw survey file health_survey.csv imported with Pandas
  • Data audit: missing values, data types, duplicates and impossible values
  • Cleaning: mean / median / mode imputation and outlier check with IQR
  • Transformation: BMI, BMI status (pd.cut), Sleep_OK flag, age group
  • Export: health_clean.csv and health_summary.csv; read back to verify
  • Pipeline log and 3 charts (missing values, BMI status, sleep)
โ˜ฐ Main menu
1Importread_csv and preview
2AuditMissing values, dtypes, duplicates
3CleanImpute and check outliers
4TransformBMI, status, flags
5Export & Verifyto_csv and read back
6Run Full PipelineSteps 1-5 together
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Import data from CSV and audit missing values and data types
  • Apply appropriate imputation (mean / median / mode) and detect outliers using the IQR rule
  • Create derived columns and export clean data and summaries to CSV
๐Ÿ“š Data dictionary
NameTypePurpose
raw / dfDataFrameOriginal and working copy
health_clean.csvCSV fileCleaned data
health_summary.csvCSV fileDiet-wise summary
loglistPipeline steps done
Why it matters: Implements Unit 1 (Python Programming-II) practicals - import/export of CSV and handling missing values - as a reusable data pipeline.
# =====================================================================
#   SCHOOL HEALTH RECORDS - DATA CLEANING & CSV PIPELINE   (SDG 3)
# =====================================================================
import pandas as pd
import matplotlib.pyplot as plt

state, log = {}, []


def imp():
    state["raw"] = pd.read_csv("health_survey.csv")
    state["df"] = state["raw"].copy()
    df = state["df"]
    print("IMPORT -> rows:", df.shape[0], "columns:", df.shape[1])
    print(df.head(6).to_string(index=False))
    log.append("import")


def audit():
    df = state["df"]
    print("Data types:\n" + df.dtypes.to_string())
    print("\nMissing values per column:\n" + df.isnull().sum().to_string())
    print("Total missing cells:", int(df.isnull().sum().sum()), "| duplicate rows:", int(df.duplicated().sum()))
    bad = df[(df.Height_cm < 100) | (df.Weight_kg < 20) | (df.Sleep_hrs > 14)]
    print("Impossible values:", "none" if bad.empty else bad.Name.tolist())
    log.append("audit")


def clean():
    df = state["df"]
    df["Height_cm"] = df["Height_cm"].fillna(round(df["Height_cm"].mean(), 1))
    df["Weight_kg"] = df["Weight_kg"].fillna(df["Weight_kg"].median())
    df["Sleep_hrs"] = df["Sleep_hrs"].fillna(round(df["Sleep_hrs"].mean(), 1))
    df["Diet"] = df["Diet"].fillna(df["Diet"].mode()[0])
    print("CLEAN -> Height: mean, Weight: median, Sleep: mean, Diet: mode")
    print("Missing cells now:", int(df.isnull().sum().sum()))
    q1, q3 = df["Weight_kg"].quantile([0.25, 0.75])
    lo, hi = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
    out = df[(df.Weight_kg < lo) | (df.Weight_kg > hi)]
    print(f"IQR check on weight: normal {lo:.1f} to {hi:.1f} kg | outliers:", out[["Name", "Weight_kg"]].values.tolist() if len(out) else "none")
    log.append("clean")


def transform():
    if "clean" not in log:
        print("Clean the data first (option 3).")
        return
    df = state["df"]
    df["BMI"] = (df.Weight_kg / (df.Height_cm / 100) ** 2).round(1)
    df["BMI_Status"] = pd.cut(df.BMI, [0, 18.5, 25, 30, 60], labels=["Under", "Normal", "Over", "Obese"])
    df["Sleep_OK"] = df.Sleep_hrs >= 7
    df["Age_group"] = pd.cut(df.Age, [0, 14, 16, 19], labels=["13-14", "15-16", "17-18"])
    print("TRANSFORM -> new columns: BMI, BMI_Status, Sleep_OK, Age_group")
    print(df[["Name", "Age_group", "BMI", "BMI_Status", "Sleep_hrs", "Sleep_OK"]].to_string(index=False))
    log.append("transform")


def export():
    df = state["df"]
    df.to_csv("health_clean.csv", index=False)
    s = df.groupby("Diet").agg(Students=("Name", "count"), Avg_BMI=("BMI", "mean"), Avg_sleep=("Sleep_hrs", "mean")).round(2)
    s.to_csv("health_summary.csv")
    back = pd.read_csv("health_clean.csv")
    print("EXPORT -> health_clean.csv", back.shape, "and health_summary.csv")
    print(pd.read_csv("health_summary.csv").to_string(index=False))
    print("Students sleeping less than 7 hours:", int((~df.Sleep_OK).sum()))
    print("BMI status count:", df.BMI_Status.value_counts().to_dict())
    log.append("export")


def full():
    log.clear()
    for f in (imp, audit, clean, transform, export):
        print("\n>>>", f.__name__.upper())
        f()
    print("\nPipeline log:", " -> ".join(log))


def charts():
    state["raw"].isnull().sum().plot(kind="bar", color="#f03e3e", title="Missing values in raw survey")
    plt.xticks(rotation=20); plt.savefig("health_missing.png", dpi=90, bbox_inches="tight"); plt.show()
    df = state["df"]
    df.BMI_Status.value_counts().reindex(["Under", "Normal", "Over", "Obese"]).plot(kind="bar", color=["#74c0fc", "#40c057", "#fab005", "#e03131"], title="BMI status of students")
    plt.xticks(rotation=0); plt.savefig("health_bmi.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.barh(df.Name, df.Sleep_hrs, color=["#40c057" if ok else "#fa5252" for ok in df.Sleep_OK]); plt.axvline(7, ls="--", c="k")
    plt.title("Sleep hours (red = below 7)"); plt.savefig("health_sleep.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: health_missing.png, health_bmi.png, health_sleep.png")


print("=" * 60)
print("   HEALTH DATA PIPELINE  (SDG 3)")
print("=" * 60)
while True:
    print("\n1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        imp()
    elif ch == "6":
        full()
    elif "df" not in state:
        print("Import the data first (option 1).")
    elif ch == "2":
        audit()
    elif ch == "3":
        clean()
    elif ch == "4":
        transform()
    elif ch == "5":
        if "transform" in log:
            export()
        else:
            print("Transform first (option 4).")
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show menu and read choice
  3. Data imported? → No: import first
  4. Audit missing values
  5. Impute: mean / median / mode
  6. Create BMI and flags
  7. Export CSV files
  8. Show summary
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1ImportRows and columnsPASS
2AuditMissing per columnPASS
3CleanMissing = 0PASS
4TransformBMI column addedPASS
5Export2 files read backPASS
6Transform before clean'Clean first'PASS
7Charts3 PNG filesPASS
โš  Limitations
  • Small sample survey
  • Mean imputation can bias data
  • Self-reported values
  • No privacy encryption
๐Ÿš€ Future scope
  • Google Form to CSV automation
  • Use KNN imputation
  • Dashboard for school nurse
  • Anonymise names (privacy)

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. 7 functions are defined (lines 10โ€“87) - Python stores them but does NOT run them yet.
  3. Main program starts at line 7: state, log = {}, [] - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
imp()10โ€“16Impfull() (menu), main program
audit()19โ€“26Auditfull() (menu), main program
clean()29โ€“41Cleanfull() (menu), main program
transform()44โ€“55Transformfull() (menu), main program
export()58โ€“68Exportfull() (menu), main program
full()71โ€“76Fullmain program
charts()79โ€“87Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
7
state, log = {}, []
๐Ÿงฎ Store / Calculate Stores {}, [] into state, log respectively
90
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
91
print("   HEALTH DATA PIPELINE  (SDG 3)")
๐Ÿ–ฅ๏ธ Output Displays the text "HEALTH DATA PIPELINE (SDG 3)" on the screen
92
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
93
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
94
print("\n1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Import 2.Audit 3.Clean 4.Transfโ€ฆ" on the screen
95
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
96
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
97
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
98
break
๐Ÿ” Loop BREAK - leaves the loop immediately
99
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
100
imp()
๐Ÿงฎ Store / Calculate Calls our own function imp()
101
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
102
full()
๐Ÿงฎ Store / Calculate Calls our own function full()
103
elif "df" not in state:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether "df" is not present in state
104
print("Import the data first (option 1).")
๐Ÿ–ฅ๏ธ Output Displays the text "Import the data first (option 1)." on the screen
105
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
106
audit()
๐Ÿงฎ Store / Calculate Calls our own function audit()
107
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
108
clean()
๐Ÿงฎ Store / Calculate Calls our own function clean()
109
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
110
transform()
๐Ÿงฎ Store / Calculate Calls our own function transform()
111
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
112
if "transform" in log:
๐Ÿ”€ Decision CHECKS whether "transform" is present in log. If True, the indented lines below run; otherwise Python jumps to the elif/else part
113
export()
๐Ÿงฎ Store / Calculate Calls our own function export()
114
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
115
print("Transform first (option 4).")
๐Ÿ–ฅ๏ธ Output Displays the text "Transform first (option 4)." on the screen
116
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
117
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
118
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
119
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: HEALTH DATA PIPELINE (SDG 3) (+1 more lines)
  2. You type 4 at Enter choice:
    shows: Import the data first (option 1). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: imp()
    shows: IMPORT -> rows: 12 columns: 6 (+8 more lines)
  4. You type 2 at Enter choice:
    runs: audit()
    shows: Data types: (+16 more lines)
  5. You type 4 at Enter choice:
    runs: transform()
    shows: Clean the data first (option 3). (+1 more lines)
  6. You type 3 at Enter choice:
    runs: clean()
    shows: CLEAN -> Height: mean, Weight: median, Sleep: mean, Diet: mode (+3 more lines)
  7. You type 4 at Enter choice:
    runs: transform()
    shows: TRANSFORM -> new columns: BMI, BMI_Status, Sleep_OK, Age_group (+14 more lines)
  8. You type 5 at Enter choice:
    runs: export()
    shows: EXPORT -> health_clean.csv (12, 10) and health_summary.csv (+6 more lines)
  9. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  10. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
imp() - lines 10โ€“16
LineCodeWhat it does
10
def imp():
๐Ÿงฉ Function DEFINES a function imp(). Python only remembers it here - its body runs later, each time imp() is called.
11
state["raw"] = pd.read_csv("health_survey.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "health_survey.csv" into a DataFrame (table); the result is put into state["raw"] (item "raw" of state)
12
state["df"] = state["raw"].copy()
๐Ÿงฎ Store / Calculate Makes a copy of state["raw"]; the result is put into state["df"] (item "df" of state)
13
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
14
print("IMPORT -> rows:", df.shape[0], "columns:", df.shape[1])
๐Ÿ–ฅ๏ธ Output Displays the text "IMPORT -> rows:", then the value of df.shape[0], then the text "columns:", then the value of df.shape[1] on the screen
15
print(df.head(6).to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.head(6).to_string(index=False) on the screen
16
log.append("import")
๐Ÿงฎ Store / Calculate Adds "import" at the end of list log
audit() - lines 19โ€“26
LineCodeWhat it does
19
def audit():
๐Ÿงฉ Function DEFINES a function audit(). Python only remembers it here - its body runs later, each time audit() is called.
20
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
21
print("Data types:\n" + df.dtypes.to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "Data types:\n" + df.dtypes.to_string() on the screen
22
print("\nMissing values per column:\n" + df.isnull().sum().to_string())
๐Ÿ–ฅ๏ธ Output Displays the value of "\nMissing values per column:\n" + df.isnull(โ€ฆ on the screen
23
print("Total missing cells:", int(df.isnull().sum().sum()), "| duplicate rows:", int(df.duplicated().sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Total missing cells:", then the value of int(df.isnull().sum().sum()), then the text "| duplicate rows:", then the value of int(df.duplicated().sum()) on the screen
24
bad = df[(df.Height_cm < 100) | (df.Weight_kg < 20) | (df.Sleep_hrs > 14)]
๐Ÿ“ฆ Library / Data Stores the item df[(df.Height_cm < 100) | (df.Weight_kg < 20)โ€ฆ in variable bad
25
print("Impossible values:", "none" if bad.empty else bad.Name.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Impossible values:", then the value of "none" if bad.empty else bad.Name.tolist() on the screen
26
log.append("audit")
๐Ÿงฎ Store / Calculate Adds "audit" at the end of list log
clean() - lines 29โ€“41
LineCodeWhat it does
29
def clean():
๐Ÿงฉ Function DEFINES a function clean(). Python only remembers it here - its body runs later, each time clean() is called.
30
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
31
df["Height_cm"] = df["Height_cm"].fillna(round(df["Height_cm"].mean(), 1))
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df["Height_cm"] with round(df["Height_cm"].mean(), 1); the result is put into df["Height_cm"] (item "Height_cm" of df)
32
df["Weight_kg"] = df["Weight_kg"].fillna(df["Weight_kg"].median())
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df["Weight_kg"] with df["Weight_kg"].median(); the result is put into df["Weight_kg"] (item "Weight_kg" of df)
33
df["Sleep_hrs"] = df["Sleep_hrs"].fillna(round(df["Sleep_hrs"].mean(), 1))
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df["Sleep_hrs"] with round(df["Sleep_hrs"].mean(), 1); the result is put into df["Sleep_hrs"] (item "Sleep_hrs" of df)
34
df["Diet"] = df["Diet"].fillna(df["Diet"].mode()[0])
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of df["Diet"] with df["Diet"].mode()[0]; the result is put into df["Diet"] (item "Diet" of df)
35
print("CLEAN -> Height: mean, Weight: median, Sleep: mean, Diet: mode")
๐Ÿ–ฅ๏ธ Output Displays the text "CLEAN -> Height: mean, Weight: meโ€ฆ" on the screen
36
print("Missing cells now:", int(df.isnull().sum().sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Missing cells now:", then the value of int(df.isnull().sum().sum()) on the screen
37
q1, q3 = df["Weight_kg"].quantile([0.25, 0.75])
๐Ÿงฎ Store / Calculate Finds the quantile [0.25, 0.75] of df["Weight_kg"]; the result is stored in variables q1, q3
38
lo, hi = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
๐Ÿงฎ Store / Calculate Stores q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1) into lo, hi respectively
39
out = df[(df.Weight_kg < lo) | (df.Weight_kg > hi)]
๐Ÿ“ฆ Library / Data Stores the item df[(df.Weight_kg < lo) | (df.Weight_kg > hi)] in variable out
40
print(f"IQR check on weight: normal {lo:.1f} to {hi:.1f} kg | outliers:", out[["Name", "Weight_kg"]].values.tolist() if len(out) else "none")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"IQR check on weight: normal {lo:.1f} to {hiโ€ฆ with the values filled into { }, then the value of out[["Name", "Weight_kg"]].values.tolist() ifโ€ฆ on the screen
41
log.append("clean")
๐Ÿงฎ Store / Calculate Adds "clean" at the end of list log
transform() - lines 44โ€“55
LineCodeWhat it does
44
def transform():
๐Ÿงฉ Function DEFINES a function transform(). Python only remembers it here - its body runs later, each time transform() is called.
45
if "clean" not in log:
๐Ÿ”€ Decision CHECKS whether "clean" is not present in log. If True, the indented lines below run; otherwise they are skipped
46
print("Clean the data first (option 3).")
๐Ÿ–ฅ๏ธ Output Displays the text "Clean the data first (option 3)." on the screen
47
return
๐Ÿงฉ Function Ends the function and goes back to the caller
48
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
49
df["BMI"] = (df.Weight_kg / (df.Height_cm / 100) ** 2).round(1)
๐Ÿ“ฆ Library / Data Rounds the values of df.Weight_kg / (df.Height_cm / 100) ** 2 to 1 decimal places; the result is put into df["BMI"] (item "BMI" of df)
50
df["BMI_Status"] = pd.cut(df.BMI, [0, 18.5, 25, 30, 60], labels=["Under", "Normal", "Over", "Obese"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["BMI_Status"] (item "BMI_Status" of df)
51
df["Sleep_OK"] = df.Sleep_hrs >= 7
๐Ÿ“ฆ Library / Data Puts True/False for df.Sleep_hrs is greater than or equal to 7 into df["Sleep_OK"] (item "Sleep_OK" of df)
52
df["Age_group"] = pd.cut(df.Age, [0, 14, 16, 19], labels=["13-14", "15-16", "17-18"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["Age_group"] (item "Age_group" of df)
53
print("TRANSFORM -> new columns: BMI, BMI_Status, Sleep_OK, Age_group")
๐Ÿ–ฅ๏ธ Output Displays the text "TRANSFORM -> new columns: BMI, BMโ€ฆ" on the screen
54
print(df[["Name", "Age_group", "BMI", "BMI_Status", "Sleep_hrs", "Sleep_OK"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df[["Name", "Age_group", "BMI", "BMI_Status",โ€ฆ on the screen
55
log.append("transform")
๐Ÿงฎ Store / Calculate Adds "transform" at the end of list log
export() - lines 58โ€“68
LineCodeWhat it does
58
def export():
๐Ÿงฉ Function DEFINES a function export(). Python only remembers it here - its body runs later, each time export() is called.
59
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
60
df.to_csv("health_clean.csv", index=False)
๐Ÿ“ฆ Library / Data Saves the DataFrame into CSV file "health_clean.csv"
61
s = df.groupby("Diet").agg(Students=("Name", "count"), Avg_BMI=("BMI", "mean"), Avg_sleep=("Sleep_hrs", "mean")).round(2)
๐Ÿ“ฆ Library / Data Rounds the values of df.groupby("Diet").agg(Students=("Name", "couโ€ฆ to 2 decimal places; the result is stored in variable s
62
s.to_csv("health_summary.csv")
๐Ÿงฎ Store / Calculate Saves the DataFrame into CSV file "health_summary.csv"
63
back = pd.read_csv("health_clean.csv")
๐Ÿ“ฆ Library / Data Reads the CSV file "health_clean.csv" into a DataFrame (table); the result is stored in variable back
64
print("EXPORT -> health_clean.csv", back.shape, "and health_summary.csv")
๐Ÿ–ฅ๏ธ Output Displays the text "EXPORT -> health_clean.csv", then the value of back.shape, then the text "and health_summary.csv" on the screen
65
print(pd.read_csv("health_summary.csv").to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of pd.read_csv("health_summary.csv").to_string(iโ€ฆ on the screen
66
print("Students sleeping less than 7 hours:", int((~df.Sleep_OK).sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Students sleeping less than 7 houโ€ฆ", then the value of int((~df.Sleep_OK).sum()) on the screen
67
print("BMI status count:", df.BMI_Status.value_counts().to_dict())
๐Ÿ–ฅ๏ธ Output Displays the text "BMI status count:", then the value of df.BMI_Status.value_counts().to_dict() on the screen
68
log.append("export")
๐Ÿงฎ Store / Calculate Adds "export" at the end of list log
full() - lines 71โ€“76
LineCodeWhat it does
71
def full():
๐Ÿงฉ Function DEFINES a function full(). Python only remembers it here - its body runs later, each time full() is called.
72
log.clear()
๐Ÿงฎ Store / Calculate Removes all items from log
73
for f in (imp, audit, clean, transform, export):
๐Ÿ” Loop LOOP: takes each item of (imp, audit, clean, transform, export) one-by-one into f and runs the indented block for it
74
print("\n>>>", f.__name__.upper())
๐Ÿ–ฅ๏ธ Output Displays the text ">>>", then the value of f.__name__.upper() on the screen
75
f()
๐Ÿงฎ Store / Calculate Calls f()
76
print("\nPipeline log:", " -> ".join(log))
๐Ÿ–ฅ๏ธ Output Displays the text "Pipeline log:", then the value of " -> ".join(log) on the screen
charts() - lines 79โ€“87
LineCodeWhat it does
79
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
80
state["raw"].isnull().sum().plot(kind="bar", color="#f03e3e", title="Missing values in raw survey")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
81
plt.xticks(rotation=20); plt.savefig("health_missing.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
81
plt.xticks(rotation=20); plt.savefig("health_missing.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "health_missing.png"
81
plt.xticks(rotation=20); plt.savefig("health_missing.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
83
df.BMI_Status.value_counts().reindex(["Under", "Normal", "Over", "Obese"]).plot(kind="bar", color=["#74c0fc", "#40c057", "#fab005", "#e03131"], title="BMI stโ€ฆ
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
84
plt.xticks(rotation=0); plt.savefig("health_bmi.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
84
plt.xticks(rotation=0); plt.savefig("health_bmi.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "health_bmi.png"
84
plt.xticks(rotation=0); plt.savefig("health_bmi.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
85
plt.barh(df.Name, df.Sleep_hrs, color=["#40c057" if ok else "#fa5252" for ok in df.Sleep_OK]); plt.axvline(7, ls="--", c="k")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
85
plt.barh(df.Name, df.Sleep_hrs, color=["#40c057" if ok else "#fa5252" for ok in df.Sleep_OK]); plt.axvline(7, ls="--", c="k")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
86
plt.title("Sleep hours (red = below 7)"); plt.savefig("health_sleep.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Writes "Sleep hours (red = below 7)" as the title of the chart
86
plt.title("Sleep hours (red = below 7)"); plt.savefig("health_sleep.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "health_sleep.png"
86
plt.title("Sleep hours (red = below 7)"); plt.savefig("health_sleep.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
87
print("Charts saved: health_missing.png, health_bmi.png, health_sleep.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: health_missing.png,โ€ฆ" on the screen
Q1. Why impute instead of deleting rows?

Deleting loses data; imputing keeps the record by filling a reasonable value.

Q2. When median instead of mean?

When the column has outliers or is skewed (like weight).

Q3. What is the mode used for?

Filling categorical columns like Diet.

Q4. What is a data pipeline?

A fixed sequence of steps - import, audit, clean, transform, export - that can be repeated.

Q5. Which SDG?

SDG 3 - Good Health and Well-being.

06

Smart Object Counter & Shape Detector with OpenCV (Computer Vision)

PYTHON + OPENCVSDG 9 - Industry, Innovation and InfrastructureComputer vision process: acquisitionpre-processing (grayscaleblurthreshold)feature extraction (contours
๐Ÿ“ 126 lines of codeโ˜ฐ 7 menu options๐Ÿ–ฅ๏ธ 79 output lines๐Ÿ“„ 25+ page report

Follows the four stages of the computer vision process to count objects in an image and identify each one as a triangle, rectangle/square, pentagon or circle from its contour, then draws labels on the image - like a quality-check camera on a factory line.

โœจ Features
  • Computer-vision pipeline on shapes.jpg: acquisition, pre-processing, feature extraction, analysis
  • Grayscale, Gaussian blur and binary threshold; contours with cv2.findContours
  • Shape classification by number of corners (approxPolyDP) and aspect ratio
  • Area, perimeter, centroid (moments) and circularity of each object
  • Adjustable threshold and minimum area; dominant colour of each shape
  • Pipeline steps image, labelled output and count chart
โ˜ฐ Main menu
1Image InfoSize and pixel stats
2Detect ShapesContours, corners, shape names
3Object MeasurementsArea, perimeter, centroid, circularity
4Colour of Each ShapeMean BGR inside contour
5Change SettingsThreshold and minimum area
6ChartsSteps, detections, counts
0ExitEnds program
๐ŸŽฏ Objectives
  • Apply pre-processing: grayscale conversion, blurring and thresholding
  • Extract contour features: area, perimeter and number of vertices
  • Classify and count objects and annotate the output image
๐Ÿ“š Data dictionary
NameTypePurpose
img / gray / thresharraysImage at each stage
contourslistOutlines of objects
objectslist of dictshape, area, perimeter, corners, centre
THRESH, MIN_AREAintSettings
Why it matters: Implements Unit 3 'Making Machines See' end to end with OpenCV (advanced learners' practical).
# =====================================================================
#   SMART OBJECT COUNTER & SHAPE DETECTOR WITH OPENCV  (Computer Vision)
# =====================================================================
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("shapes.jpg")
THRESH, MIN_AREA = 230, 300
objects = []


def stages():
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    _, th = cv2.threshold(blur, THRESH, 255, cv2.THRESH_BINARY_INV)
    return gray, blur, th


def info():
    gray = stages()[0]
    print("Image size:", img.shape[1], "x", img.shape[0], "| channels:", img.shape[2])
    print("Gray min / max / mean:", gray.min(), "/", gray.max(), "/", round(gray.mean(), 1))


def colour_name(bgr):
    b, g, r = bgr
    if r > 150 and g < 100 and b < 100: return "Red"
    if g > 120 and r < 100 and b < 120: return "Green"
    if b > 150 and r < 100: return "Blue"
    if r > 180 and g > 150 and b < 100: return "Yellow"
    if r > 150 and b > 150 and g < 120: return "Purple"
    if r > 180 and 80 < g < 180 and b < 80: return "Orange"
    return "Other"


def detect(show=True):
    objects.clear()
    th = stages()[2]
    contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for c in sorted(contours, key=lambda c: cv2.boundingRect(c)[0]):
        area = cv2.contourArea(c)
        if area < MIN_AREA:
            continue
        peri = cv2.arcLength(c, True)
        v = len(cv2.approxPolyDP(c, 0.03 * peri, True))
        x, y, w, h = cv2.boundingRect(c)
        shape = {3: "Triangle", 5: "Pentagon"}.get(v, "Circle")
        if v == 4:
            shape = "Square" if 0.9 <= w / h <= 1.1 else "Rectangle"
        M = cv2.moments(c)
        mask = np.zeros(th.shape, np.uint8)
        cv2.drawContours(mask, [c], -1, 255, -1)
        objects.append({"shape": shape, "area": area, "peri": peri, "v": v, "c": c, "box": (x, y, w, h),
                        "centre": (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])),
                        "colour": colour_name(cv2.mean(img, mask=mask)[:3])})
    if show:
        print(f"Settings: threshold {THRESH}, minimum area {MIN_AREA}")
        print("{:<4}{:<11}{:>8}{:>10}{:>9}".format("No", "Shape", "Area", "Perimeter", "Corners"))
        for i, o in enumerate(objects, 1):
            print("{:<4}{:<11}{:>8.0f}{:>10.1f}{:>9}".format(i, o["shape"], o["area"], o["peri"], o["v"]))
        counts = {}
        for o in objects:
            counts[o["shape"]] = counts.get(o["shape"], 0) + 1
        print("Total objects:", len(objects), "| Count by shape:", counts)


def measurements():
    if not objects:
        detect(False)
    print("{:<4}{:<11}{:>12}{:>13}".format("No", "Shape", "Centre", "Circularity"))
    for i, o in enumerate(objects, 1):
        circ = 4 * np.pi * o["area"] / o["peri"] ** 2
        print("{:<4}{:<11}{:>12}{:>13.3f}".format(i, o["shape"], str(o["centre"]), circ))
    big = max(objects, key=lambda o: o["area"])
    print("Largest object:", big["shape"], "with area", int(big["area"]), "px")


def colours():
    if not objects:
        detect(False)
    for i, o in enumerate(objects, 1):
        print(f"  {i}. {o['shape']:<10} colour: {o['colour']}")


def settings():
    global THRESH, MIN_AREA
    THRESH = int(input("Threshold (0-255): "))
    MIN_AREA = int(input("Minimum area (pixels): "))
    print("Settings changed. Run Detect again.")


def charts():
    detect(False)
    gray, blur, th = stages()
    fig, ax = plt.subplots(1, 4, figsize=(13, 3))
    for a, im, t in zip(ax, [cv2.cvtColor(img, cv2.COLOR_BGR2RGB), gray, blur, th], ["1. Original", "2. Grayscale", "3. Blur", "4. Threshold"]):
        a.imshow(im, cmap=None if im.ndim == 3 else "gray"); a.set_title(t); a.axis("off")
    plt.tight_layout(); plt.savefig("shapes_steps.png", dpi=80); plt.show()
    out = img.copy()
    for o in objects:
        cv2.drawContours(out, [o["c"]], -1, (0, 0, 0), 2)
        cv2.putText(out, o["shape"], (o["box"][0], o["box"][1] - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
        cv2.circle(out, o["centre"], 3, (0, 0, 255), -1)
    plt.figure(figsize=(7, 4)); plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)); plt.title("Detected shapes"); plt.axis("off")
    plt.savefig("shapes_detected.png", dpi=90, bbox_inches="tight"); plt.show()
    counts = {}
    for o in objects:
        counts[o["shape"]] = counts.get(o["shape"], 0) + 1
    plt.bar(counts.keys(), counts.values(), color="#228be6"); plt.title("Objects counted by shape"); plt.ylabel("Count")
    plt.savefig("shapes_count.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: shapes_steps.png, shapes_detected.png, shapes_count.png")


print("=" * 60)
print("   SMART OBJECT COUNTER  (OpenCV)")
print("=" * 60)
menu = {"1": info, "2": detect, "3": measurements, "4": colours, "5": settings, "6": charts}
while True:
    print("\n1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    menu.get(ch, lambda: print("Invalid choice"))()

        
  1. Start
  2. Read image
  3. Gray -> blur -> threshold
  4. Find contours
  5. Area >= MIN_AREA? → No: ignore noise
  6. Approximate polygon, count corners
  7. Corners = 3 / 4 / 5? → No: circle
  8. Label and count shapes
  9. Stop
#Test case / inputExpected resultStatus
1Image infoWidth x heightPASS
2DetectShapes listed with cornersPASS
3MeasurementsCircularity ~ 1 for circlePASS
4ColourDominant colour namesPASS
5Threshold 200Count may changePASS
6Charts3 PNG filesPASS
โš  Limitations
  • Works on clean, light backgrounds
  • Overlapping shapes are merged
  • Rule-based classification
  • Fixed threshold
๐Ÿš€ Future scope
  • Real-time webcam counting
  • YOLO object detection
  • Count products on a conveyor belt
  • Count seeds / tablets in industry

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): cv2 - OpenCV image processing, numpy - fast arrays and maths, matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: img, objects.
  3. 8 functions are defined (lines 13โ€“112) - Python stores them but does NOT run them yet.
  4. Main program starts at line 9: THRESH, MIN_AREA = 230, 300 - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
stages()13โ€“17Stagesinfo(), detect(), charts()
info()20โ€“23Infomain program (menu)
colour_name(bgr)26โ€“34Colour namedetect()
detect(show)37โ€“65Detectmeasurements(), colours(), charts(), main program (menu)
measurements()68โ€“76Measurementsmain program (menu)
colours()79โ€“83Coloursmain program (menu)
settings()86โ€“90Settingsmain program (menu)
charts()93โ€“112Chartsmain program (menu)
โ‘ข Main program - line by line
LineCodeWhat it does
9
THRESH, MIN_AREA = 230, 300
๐Ÿงฎ Store / Calculate Stores 230, 300 into THRESH, MIN_AREA respectively
10
objects = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable objects
115
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
116
print("   SMART OBJECT COUNTER  (OpenCV)")
๐Ÿ–ฅ๏ธ Output Displays the text "SMART OBJECT COUNTER (OpenCV)" on the screen
117
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
118
menu = {"1": info, "2": detect, "3": measurements, "4": colours, "5": settings, "6": charts}
๐Ÿงฎ Store / Calculate Stores a dictionary {"1": info, "2": detect, "3": measurements, "โ€ฆ in variable menu
119
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
120
print("\n1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Info 2.Detect 3.Measurements 4.โ€ฆ" on the screen
121
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
122
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise they are skipped
123
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
124
break
๐Ÿ” Loop BREAK - leaves the loop immediately
125
menu.get(ch, lambda: print("Invalid choice"))()
๐Ÿ–ฅ๏ธ Output Calls menu.get(ch, lambda: print("Invalid choice"))โ€ฆ
โ‘ฃ Inside each function - line by line
stages() - lines 13โ€“17
LineCodeWhat it does
13
def stages():
๐Ÿงฉ Function DEFINES a function stages(). Python only remembers it here - its body runs later, each time stages() is called.
14
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
๐Ÿ“ฆ Library / Data Converts the colour format of the image; the result is stored in variable gray
15
blur = cv2.GaussianBlur(gray, (5, 5), 0)
๐Ÿ“ฆ Library / Data Blurs (smooths) the image; the result is stored in variable blur
16
_, th = cv2.threshold(blur, THRESH, 255, cv2.THRESH_BINARY_INV)
๐Ÿ“ฆ Library / Data Turns the image into black & white using a cut-off; the result is stored in variables _, th
17
return gray, blur, th
๐Ÿงฉ Function Sends back (returns) the tuple gray, blur, th to the line that called the function
info() - lines 20โ€“23
LineCodeWhat it does
20
def info():
๐Ÿงฉ Function DEFINES a function info(). Python only remembers it here - its body runs later, each time info() is called.
21
gray = stages()[0]
๐Ÿงฎ Store / Calculate Stores the item stages()[0] in variable gray
22
print("Image size:", img.shape[1], "x", img.shape[0], "| channels:", img.shape[2])
๐Ÿ–ฅ๏ธ Output Displays the text "Image size:", then the value of img.shape[1], then the text "x", then the value of img.shape[0], then the text "| channels:", then the value of img.shape[2] on the screen
23
print("Gray min / max / mean:", gray.min(), "/", gray.max(), "/", round(gray.mean(), 1))
๐Ÿ–ฅ๏ธ Output Displays the text "Gray min / max / mean:", then the value of gray.min(), then the text "/", then the value of gray.max(), then the text "/", then the value of round(gray.mean(), 1) on the screen
colour_name() - lines 26โ€“34
LineCodeWhat it does
26
def colour_name(bgr):
๐Ÿงฉ Function DEFINES a function colour_name(bgr). Python only remembers it here - its body runs later, each time colour_name() is called.
27
b, g, r = bgr
๐Ÿงฎ Store / Calculate Stores the value of bgr in variables b, g, r
28
if r > 150 and g < 100 and b < 100: return "Red"
๐Ÿ”€ Decision CHECKS whether (r is greater than 150 AND g is less than 100 AND b is less than 100). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Red" to the line that called the function
29
if g > 120 and r < 100 and b < 120: return "Green"
๐Ÿ”€ Decision CHECKS whether (g is greater than 120 AND r is less than 100 AND b is less than 120). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Green" to the line that called the function
30
if b > 150 and r < 100: return "Blue"
๐Ÿ”€ Decision CHECKS whether (b is greater than 150 AND r is less than 100). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Blue" to the line that called the function
31
if r > 180 and g > 150 and b < 100: return "Yellow"
๐Ÿ”€ Decision CHECKS whether (r is greater than 180 AND g is greater than 150 AND b is less than 100). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Yellow" to the line that called the function
32
if r > 150 and b > 150 and g < 120: return "Purple"
๐Ÿ”€ Decision CHECKS whether (r is greater than 150 AND b is greater than 150 AND g is less than 120). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Purple" to the line that called the function
33
if r > 180 and 80 < g < 180 and b < 80: return "Orange"
๐Ÿ”€ Decision CHECKS whether (r is greater than 180 AND 80 < g < 180 is True AND b is less than 80). If True, the indented lines below run; otherwise they are skipped โ†’ here: sends back (returns) the text "Orange" to the line that called the function
34
return "Other"
๐Ÿงฉ Function Sends back (returns) the text "Other" to the line that called the function
detect() - lines 37โ€“65
LineCodeWhat it does
37
def detect(show=True):
๐Ÿงฉ Function DEFINES a function detect(show). Python only remembers it here - its body runs later, each time detect() is called.
38
objects.clear()
๐Ÿงฎ Store / Calculate Removes all items from objects
39
th = stages()[2]
๐Ÿงฎ Store / Calculate Stores the item stages()[2] in variable th
40
contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
๐Ÿ“ฆ Library / Data Finds the outlines of shapes; the result is stored in variables contours, _
41
for c in sorted(contours, key=lambda c: cv2.boundingRect(c)[0]):
๐Ÿ” Loop LOOP: takes each item of sorted(contours, key=lambda c: cv2.boundingReโ€ฆ one-by-one into c and runs the indented block for it
42
area = cv2.contourArea(c)
๐Ÿ“ฆ Library / Data Calls cv2.contourArea(c); the result is stored in variable area
43
if area < MIN_AREA:
๐Ÿ”€ Decision CHECKS whether area is less than MIN_AREA. If True, the indented lines below run; otherwise they are skipped
44
continue
๐Ÿ” Loop CONTINUE - skips the rest of this round and goes to the next round of the loop
45
peri = cv2.arcLength(c, True)
๐Ÿ“ฆ Library / Data Calls cv2.arcLength(c, True); the result is stored in variable peri
46
v = len(cv2.approxPolyDP(c, 0.03 * peri, True))
๐Ÿ“ฆ Library / Data Counts the number of items / characters in cv2.approxPolyDP(c, 0.03 * peri, True); the result is stored in variable v
47
x, y, w, h = cv2.boundingRect(c)
๐Ÿ“ฆ Library / Data Calls cv2.boundingRect(c); the result is stored in variables x, y, w, h
48
shape = {3: "Triangle", 5: "Pentagon"}.get(v, "Circle")
๐Ÿงฎ Store / Calculate Gets the value for key v from {3: "Triangle", 5: "Pentagon"} (or "Circle" if the key is not there); the result is stored in variable shape
49
if v == 4:
๐Ÿ”€ Decision CHECKS whether v is equal to 4. If True, the indented lines below run; otherwise they are skipped
50
shape = "Square" if 0.9 <= w / h <= 1.1 else "Rectangle"
๐Ÿงฎ Store / Calculate Stores either "Square" or "Rectangle" depending on 0.9 <= w / h <= 1.1 in variable shape
51
M = cv2.moments(c)
๐Ÿ“ฆ Library / Data Calls cv2.moments(c); the result is stored in variable M
52
mask = np.zeros(th.shape, np.uint8)
๐Ÿ“ฆ Library / Data Makes a NumPy array filled with 0s; the result is stored in variable mask
53
cv2.drawContours(mask, [c], -1, 255, -1)
๐Ÿ“ฆ Library / Data Draws the outlines
54
objects.append({"shape": shape, "area": area, "peri": peri, "v": v, "c": c, "box": (x, y, w, h),
                "centre": (int(M["m10"] / M["m00"]), int(M["โ€ฆ
๐Ÿ“ฆ Library / Data Adds {"shape": shape, "area": area, "peri": peri, โ€ฆ at the end of list objects
57
if show:
๐Ÿ”€ Decision CHECKS whether show is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
58
print(f"Settings: threshold {THRESH}, minimum area {MIN_AREA}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Settings: threshold {THRESH}, minimum area โ€ฆ with the values filled into { } on the screen
59
print("{:<4}{:<11}{:>8}{:>10}{:>9}".format("No", "Shape", "Area", "Perimeter", "Corners"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<11}{:>8}{:>10}{:>9}".format("No", "Sโ€ฆ on the screen
60
for i, o in enumerate(objects, 1):
๐Ÿ” Loop LOOP over objects with position: in each round i, o get (position, item)
61
print("{:<4}{:<11}{:>8.0f}{:>10.1f}{:>9}".format(i, o["shape"], o["area"], o["peri"], o["v"]))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<11}{:>8.0f}{:>10.1f}{:>9}".format(i,โ€ฆ on the screen
62
counts = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable counts
63
for o in objects:
๐Ÿ” Loop LOOP: takes each item of objects one-by-one into o and runs the indented block for it
64
counts[o["shape"]] = counts.get(o["shape"], 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of counts.get(o["shape"], 0) + 1 (calculated using +) into counts[o["shape"]] (item o["shape"] of counts)
65
print("Total objects:", len(objects), "| Count by shape:", counts)
๐Ÿ–ฅ๏ธ Output Displays the text "Total objects:", then the value of len(objects), then the text "| Count by shape:", then the value of counts on the screen
measurements() - lines 68โ€“76
LineCodeWhat it does
68
def measurements():
๐Ÿงฉ Function DEFINES a function measurements(). Python only remembers it here - its body runs later, each time measurements() is called.
69
if not objects:
๐Ÿ”€ Decision CHECKS whether objects is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
70
detect(False)
๐Ÿงฎ Store / Calculate Calls our own function detect(False)
71
print("{:<4}{:<11}{:>12}{:>13}".format("No", "Shape", "Centre", "Circularity"))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<11}{:>12}{:>13}".format("No", "Shapeโ€ฆ on the screen
72
for i, o in enumerate(objects, 1):
๐Ÿ” Loop LOOP over objects with position: in each round i, o get (position, item)
73
circ = 4 * np.pi * o["area"] / o["peri"] ** 2
๐Ÿ“ฆ Library / Data Stores the value of 4 * np.pi * o["area"] / o["peri"] ** 2 (calculated using รท) in variable circ
74
print("{:<4}{:<11}{:>12}{:>13.3f}".format(i, o["shape"], str(o["centre"]), circ))
๐Ÿ–ฅ๏ธ Output Displays the value of "{:<4}{:<11}{:>12}{:>13.3f}".format(i, o["shaโ€ฆ on the screen
75
big = max(objects, key=lambda o: o["area"])
๐Ÿงฎ Store / Calculate Finds the largest value among objects; the result is stored in variable big
76
print("Largest object:", big["shape"], "with area", int(big["area"]), "px")
๐Ÿ–ฅ๏ธ Output Displays the text "Largest object:", then the value of big["shape"], then the text "with area", then the value of int(big["area"]), then the text "px" on the screen
colours() - lines 79โ€“83
LineCodeWhat it does
79
def colours():
๐Ÿงฉ Function DEFINES a function colours(). Python only remembers it here - its body runs later, each time colours() is called.
80
if not objects:
๐Ÿ”€ Decision CHECKS whether objects is False (or empty / zero). If True, the indented lines below run; otherwise they are skipped
81
detect(False)
๐Ÿงฎ Store / Calculate Calls our own function detect(False)
82
for i, o in enumerate(objects, 1):
๐Ÿ” Loop LOOP over objects with position: in each round i, o get (position, item)
83
print(f"  {i}. {o['shape']:<10} colour: {o['colour']}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {i}. {o['shape']:<10} colour: {o['colour']โ€ฆ with the values filled into { } on the screen
settings() - lines 86โ€“90
LineCodeWhat it does
86
def settings():
๐Ÿงฉ Function DEFINES a function settings(). Python only remembers it here - its body runs later, each time settings() is called.
87
global THRESH, MIN_AREA
๐Ÿงฉ Function Tells Python that THRESH, MIN_AREA means the GLOBAL variable (outside the function)
88
THRESH = int(input("Threshold (0-255): "))
โŒจ๏ธ Input Shows "Threshold (0-255): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable THRESH
89
MIN_AREA = int(input("Minimum area (pixels): "))
โŒจ๏ธ Input Shows "Minimum area (pixels): ", reads what the user types, and int() converts that text into a whole number; the number is stored in variable MIN_AREA
90
print("Settings changed. Run Detect again.")
๐Ÿ–ฅ๏ธ Output Displays the text "Settings changed. Run Detect agaiโ€ฆ" on the screen
charts() - lines 93โ€“112
LineCodeWhat it does
93
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
94
detect(False)
๐Ÿงฎ Store / Calculate Calls our own function detect(False)
95
gray, blur, th = stages()
๐Ÿงฎ Store / Calculate Calls our own function stages(); the result is stored in variables gray, blur, th
96
fig, ax = plt.subplots(1, 4, figsize=(13, 3))
๐Ÿ–ฅ๏ธ Output Creates a figure with chart area(s); the result is stored in variables fig, ax
97
for a, im, t in zip(ax, [cv2.cvtColor(img, cv2.COLOR_BGR2RGB), gray, blur, th], ["1. Original", "2. Grayscale", "3. Blur", "4. Threshold"]):
๐Ÿ” Loop LOOP that walks through ax, [cv2.cvtColor(img, cv2.COLOR_BGR2RGB), gray, โ€ฆ, ["1. Original", "2. Grayscale", "3. Blur", "4โ€ฆ together; a, im, t get one item from each
98
a.imshow(im, cmap=None if im.ndim == 3 else "gray"); a.set_title(t); a.axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
98
a.imshow(im, cmap=None if im.ndim == 3 else "gray"); a.set_title(t); a.axis("off")
๐Ÿ–ฅ๏ธ Output Sets the title of this chart
98
a.imshow(im, cmap=None if im.ndim == 3 else "gray"); a.set_title(t); a.axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
99
plt.tight_layout(); plt.savefig("shapes_steps.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
99
plt.tight_layout(); plt.savefig("shapes_steps.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "shapes_steps.png"
99
plt.tight_layout(); plt.savefig("shapes_steps.png", dpi=80); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
100
out = img.copy()
๐Ÿงฎ Store / Calculate Makes a copy of img; the result is stored in variable out
101
for o in objects:
๐Ÿ” Loop LOOP: takes each item of objects one-by-one into o and runs the indented block for it
102
cv2.drawContours(out, [o["c"]], -1, (0, 0, 0), 2)
๐Ÿ“ฆ Library / Data Draws the outlines
103
cv2.putText(out, o["shape"], (o["box"][0], o["box"][1] - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
๐Ÿ“ฆ Library / Data Writes text on the image
104
cv2.circle(out, o["centre"], 3, (0, 0, 255), -1)
๐Ÿ“ฆ Library / Data Calls cv2.circle(out, o["centre"], 3, (0,โ€ฆ)
105
plt.figure(figsize=(7, 4)); plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)); plt.title("Detected shapes"); plt.axis("off")
๐Ÿ–ฅ๏ธ Output Starts a new chart figure
105
plt.figure(figsize=(7, 4)); plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)); plt.title("Detected shapes"); plt.axis("off")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
105
plt.figure(figsize=(7, 4)); plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)); plt.title("Detected shapes"); plt.axis("off")
๐Ÿ–ฅ๏ธ Output Writes "Detected shapes" as the title of the chart
105
plt.figure(figsize=(7, 4)); plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)); plt.title("Detected shapes"); plt.axis("off")
๐Ÿ–ฅ๏ธ Output Sets axis options
106
plt.savefig("shapes_detected.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "shapes_detected.png"
106
plt.savefig("shapes_detected.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
107
counts = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable counts
108
for o in objects:
๐Ÿ” Loop LOOP: takes each item of objects one-by-one into o and runs the indented block for it
109
counts[o["shape"]] = counts.get(o["shape"], 0) + 1
๐Ÿงฎ Store / Calculate Puts the value of counts.get(o["shape"], 0) + 1 (calculated using +) into counts[o["shape"]] (item o["shape"] of counts)
110
plt.bar(counts.keys(), counts.values(), color="#228be6"); plt.title("Objects counted by shape"); plt.ylabel("Count")
๐Ÿ–ฅ๏ธ Output Draws a bar chart of counts.keys(), counts.values()
110
plt.bar(counts.keys(), counts.values(), color="#228be6"); plt.title("Objects counted by shape"); plt.ylabel("Count")
๐Ÿ–ฅ๏ธ Output Writes "Objects counted by shape" as the title of the chart
110
plt.bar(counts.keys(), counts.values(), color="#228be6"); plt.title("Objects counted by shape"); plt.ylabel("Count")
๐Ÿ–ฅ๏ธ Output Writes "Count" as the label of the Y-axis
111
plt.savefig("shapes_count.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "shapes_count.png"
111
plt.savefig("shapes_count.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
112
print("Charts saved: shapes_steps.png, shapes_detected.png, shapes_count.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: shapes_steps.png, sโ€ฆ" on the screen
Q1. What is a contour?

A curve joining continuous boundary points of the same intensity - the outline of an object.

Q2. Why blur before threshold?

Blur removes noise so small specks do not become false contours.

Q3. What does approxPolyDP do?

Simplifies a contour to a polygon with fewer vertices; the vertex count tells the shape.

Q4. What is circularity?

4 pi Area / Perimeter^2; equals 1 for a perfect circle.

Q5. Stages of a CV pipeline?

Acquisition, pre-processing, feature extraction, analysis / interpretation.

07

Traffic Sensor Data-Stream Analytics (Big Data, SDG 11)

PYTHON + PANDASSDG 11 - Sustainable Cities and CommunitiesData streamssliding-window averagereal-time alertsreservoir sampling5 Vs of Big Data
๐Ÿ“ 128 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 57 output lines๐Ÿ“„ 25+ page report

Simulates a high-velocity stream of vehicle counts from road sensors (one reading per minute for 24 hours, 4 junctions), processes it one record at a time with a sliding window to raise congestion alerts, keeps a reservoir sample, and then summarises the full data with Pandas.

โœจ Features
  • Simulated sensor stream: 4 junctions x 1440 minutes = 5760 records (velocity of Big Data)
  • Sliding-window (15 min) average with congestion alerts and alert reset
  • Reservoir sampling of 200 records to estimate the mean of the whole stream
  • Hourly aggregation, peak hours and busiest junction
  • Stream statistics by junction and the 5 V's of Big Data
  • Hourly line chart, window chart and sample vs full distribution
โ˜ฐ Main menu
1Run StreamProcess all records
2Congestion AlertsWindow average > limit
3Reservoir SampleEstimate vs true mean
4Hourly AnalysisPeak hours
5Junction ReportTotals and maximum per junction
6Big Data V'sVolume, velocity, variety...
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Simulate a continuous data stream and process it record by record
  • Use a sliding window and reservoir sampling with fixed memory
  • Summarise the stream with Pandas to extract value (peak hours, busiest junction)
๐Ÿ“š Data dictionary
NameTypePurpose
stream()generatorYields (minute, junction, cars)
windowsdict of dequeLast 15 readings per junction
reservoirlistRandom sample of K records
dfDataFrameAll records for batch analysis
Why it matters: Makes the Unit 5 ideas - Big Data characteristics and mining data streams - concrete and measurable.
# =====================================================================
#   TRAFFIC SENSOR DATA-STREAM ANALYTICS  (Big Data, SDG 11)
# =====================================================================
import random
from collections import deque
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

random.seed(7); np.random.seed(7)
junctions = ["Azadpur", "Shalimar Bagh", "Pitampura", "Rohini"]
base = {"Azadpur": 55, "Shalimar Bagh": 40, "Pitampura": 35, "Rohini": 45}
WINDOW, LIMIT, K = 15, 95, 200
state = {}


def stream():
    for minute in range(24 * 60):
        h = minute / 60
        rush = 60 * np.exp(-((h - 9) ** 2) / 2) + 70 * np.exp(-((h - 18) ** 2) / 3)
        for j in junctions:
            yield minute, j, max(0, int(base[j] * 0.4 + rush * base[j] / 50 + np.random.normal(0, 6)))


def run():
    windows = {j: deque(maxlen=WINDOW) for j in junctions}
    alert_on = {j: False for j in junctions}
    alerts, reservoir, rows, wavg, n = [], [], [], [], 0
    for minute, j, cars in stream():
        n += 1
        rows.append((minute, j, cars))
        w = windows[j]; w.append(cars)
        avg = sum(w) / len(w)
        if j == "Azadpur":
            wavg.append(avg)
        if len(w) == WINDOW and avg > LIMIT and not alert_on[j]:
            alerts.append((f"{minute // 60:02d}:{minute % 60:02d}", j, round(avg, 1))); alert_on[j] = True
        elif avg < LIMIT * 0.8:
            alert_on[j] = False
        if len(reservoir) < K:
            reservoir.append(cars)
        else:
            r = random.randint(0, n - 1)
            if r < K:
                reservoir[r] = cars
    df = pd.DataFrame(rows, columns=["minute", "junction", "cars"])
    df["hour"] = df.minute // 60
    state.update(alerts=alerts, reservoir=reservoir, df=df, wavg=wavg)
    print("Records streamed (4 per minute):", n, "| alerts:", len(alerts))


def alerts():
    print(f"Congestion alerts (15-min average > {LIMIT} vehicles/min):")
    for a in state["alerts"]:
        print("  ALERT", a[0], "-", f"{a[1]:<14}", "avg", a[2])


def reservoir():
    r, df = state["reservoir"], state["df"]
    print("Reservoir size:", len(r), "| sample mean:", round(np.mean(r), 2), "| true mean:", round(df.cars.mean(), 2))
    print("Error of estimate:", round(abs(np.mean(r) - df.cars.mean()) / df.cars.mean() * 100, 2), "% using only", round(len(r) / len(df) * 100, 1), "% of data")


def hourly():
    h = state["df"].groupby("hour").cars.sum()
    print("Peak hours:", h.nlargest(3).index.tolist(), "| quietest:", h.nsmallest(3).index.tolist())
    for hr in range(6, 22, 3):
        print(f"  {hr:02d}:00  {h[hr]:>6}  " + "#" * int(h[hr] / 1000))


def junction_report():
    g = state["df"].groupby("junction").cars.agg(["sum", "mean", "max"]).round(1).sort_values("sum", ascending=False)
    print(g)
    print("Busiest junction:", g.index[0], "| total vehicles counted:", int(state["df"].cars.sum()))


def vs():
    df = state["df"]
    print(f"Volume  : {len(df)} records in one day ({len(df) * 365:,} per year)")
    print("Velocity: 4 new records every minute (real cities: thousands per second)")
    print("Variety : numbers here; real systems add camera video and GPS")
    print("Veracity: sensor noise -> we use 15-minute averages, not single readings")
    print("Value   : alerts help traffic police divert vehicles in time")


def charts():
    df = state["df"]
    df.pivot_table(index="hour", columns="junction", values="cars", aggfunc="sum").plot(figsize=(8, 4))
    plt.ylabel("Vehicles per hour"); plt.title("Hourly traffic from the sensor stream")
    plt.savefig("traffic_stream.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.plot(np.arange(len(state["wavg"])) / 60, state["wavg"]); plt.axhline(LIMIT, c="r", ls="--", label="Alert limit")
    plt.xlabel("Hour"); plt.ylabel("15-min avg (cars/min)"); plt.title("Sliding-window average - Azadpur"); plt.legend()
    plt.savefig("traffic_window.png", dpi=90, bbox_inches="tight"); plt.show()
    plt.hist(df.cars, bins=30, density=True, alpha=.5, label="Full stream")
    plt.hist(state["reservoir"], bins=30, density=True, alpha=.5, label="Reservoir sample")
    plt.xlabel("Cars per minute"); plt.title("Sample represents the stream"); plt.legend()
    plt.savefig("traffic_reservoir.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: traffic_stream.png, traffic_window.png, traffic_reservoir.png")


print("=" * 60)
print("   TRAFFIC DATA-STREAM ANALYTICS  (Big Data)")
print("=" * 60)
while True:
    print("\n1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        run()
    elif "df" not in state and ch in "234567":
        print("Run the stream first (option 1).")
    elif ch == "2":
        alerts()
    elif ch == "3":
        reservoir()
    elif ch == "4":
        hourly()
    elif ch == "5":
        junction_report()
    elif ch == "6":
        vs()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Read next record from stream
  3. Add to junction window
  4. Window avg > LIMIT and no alert? → No: continue
  5. Raise congestion alert
  6. Reservoir sampling step
  7. Stream ended? → No: read next record
  8. Reports
  9. Stop
#Test case / inputExpected resultStatus
1Run stream5760 recordsPASS
2AlertsEvening rush alertsPASS
3ReservoirSample mean close to true meanPASS
4HourlyPeaks at 9 and 18 hPASS
5Junction reportAzadpur busiestPASS
6Alerts before run'Run the stream first'PASS
7Charts3 PNG filesPASS
โš  Limitations
  • Simulated sensor data
  • Single day
  • No GPS / map
  • Python loop not truly distributed
๐Ÿš€ Future scope
  • Apache Kafka + Spark Streaming
  • Live data from city traffic API
  • Signal timing optimisation
  • Predict congestion 30 minutes ahead

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): random - random number functions, deque, numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts are loaded.
  2. Global variables / constants are created: junctions, base, state.
  3. 8 functions are defined (lines 17โ€“98) - Python stores them but does NOT run them yet.
  4. Main program starts at line 10: random.seed(7); np.random.seed(7) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
stream()17โ€“22Streamrun()
run()25โ€“49Runmain program
alerts()52โ€“55Alertsrun() (menu), run() (menu), run() (menu), main program
reservoir()58โ€“61Reservoirrun() (menu), run() (menu), run() (menu), run() (menu)
hourly()64โ€“68Hourlymain program
junction_report()71โ€“74Junction reportmain program
vs()77โ€“83Vsmain program
charts()86โ€“98Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
10
random.seed(7); np.random.seed(7)
๐Ÿ“ฆ Library / Data Fixes the starting point of random numbers (7) so results repeat
10
random.seed(7); np.random.seed(7)
๐Ÿ“ฆ Library / Data Fixes the starting point of random numbers (7) so results repeat
11
junctions = ["Azadpur", "Shalimar Bagh", "Pitampura", "Rohini"]
๐Ÿงฎ Store / Calculate Stores a list ["Azadpur", "Shalimar Bagh", "Pitampura", "Roโ€ฆ in variable junctions
12
base = {"Azadpur": 55, "Shalimar Bagh": 40, "Pitampura": 35, "Rohini": 45}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Azadpur": 55, "Shalimar Bagh": 40, "Pitampuโ€ฆ in variable base
13
WINDOW, LIMIT, K = 15, 95, 200
๐Ÿงฎ Store / Calculate Stores 15, 95, 200 into WINDOW, LIMIT, K respectively
14
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
101
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
102
print("   TRAFFIC DATA-STREAM ANALYTICS  (Big Data)")
๐Ÿ–ฅ๏ธ Output Displays the text "TRAFFIC DATA-STREAM ANALYTICS (Biโ€ฆ" on the screen
103
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
104
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
105
print("\n1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Run Stream 2.Alerts 3.Reservoirโ€ฆ" on the screen
106
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
107
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
108
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
109
break
๐Ÿ” Loop BREAK - leaves the loop immediately
110
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
111
run()
๐Ÿงฎ Store / Calculate Calls our own function run()
112
elif "df" not in state and ch in "234567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("df" is not present in state AND ch is present in "234567")
113
print("Run the stream first (option 1).")
๐Ÿ–ฅ๏ธ Output Displays the text "Run the stream first (option 1)." on the screen
114
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
115
alerts()
๐Ÿงฎ Store / Calculate Calls our own function alerts()
116
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
117
reservoir()
๐Ÿงฎ Store / Calculate Calls our own function reservoir()
118
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
119
hourly()
๐Ÿงฎ Store / Calculate Calls our own function hourly()
120
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
121
junction_report()
๐Ÿงฎ Store / Calculate Calls our own function junction_report()
122
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
123
vs()
๐Ÿงฎ Store / Calculate Calls our own function vs()
124
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
125
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
126
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
127
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: TRAFFIC DATA-STREAM ANALYTICS (Big Data) (+1 more lines)
  2. You type 2 at Enter choice:
    shows: Run the stream first (option 1). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: run() โ†’ stream() ร—5761
    shows: Records streamed (4 per minute): 5760 | alerts: 1 (+1 more lines)
  4. You type 2 at Enter choice:
    runs: alerts()
    shows: Congestion alerts (15-min average > 95 vehicles/min): (+2 more lines)
  5. You type 3 at Enter choice:
    runs: reservoir()
    shows: Reservoir size: 200 | sample mean: 29.8 | true mean: 30.2 (+2 more lines)
  6. You type 4 at Enter choice:
    runs: hourly()
    shows: Peak hours: [18, 17, 9] | quietest: [1, 12, 13] (+7 more lines)
  7. You type 5 at Enter choice:
    runs: junction_report()
    shows: sum mean max (+7 more lines)
  8. You type 6 at Enter choice:
    runs: vs()
    shows: Volume : 5760 records in one day (2,102,400 per year) (+5 more lines)
  9. You type 7 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  10. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
stream() - lines 17โ€“22
LineCodeWhat it does
17
def stream():
๐Ÿงฉ Function DEFINES a function stream(). Python only remembers it here - its body runs later, each time stream() is called.
18
for minute in range(24 * 60):
๐Ÿ” Loop LOOP: gives the numbers 0, 1, 2 โ€ฆ up to 24 * 60 - 1; for each number, minute takes that value and the indented block runs once
19
h = minute / 60
๐Ÿงฎ Store / Calculate Stores the value of minute / 60 (calculated using รท) in variable h
20
rush = 60 * np.exp(-((h - 9) ** 2) / 2) + 70 * np.exp(-((h - 18) ** 2) / 3)
๐Ÿ“ฆ Library / Data Stores the value of 60 * np.exp(-((h - 9) ** 2) / 2) + 70 * np.exโ€ฆ (calculated using +) in variable rush
21
for j in junctions:
๐Ÿ” Loop LOOP: takes each item of junctions one-by-one into j and runs the indented block for it
22
yield minute, j, max(0, int(base[j] * 0.4 + rush * base[j] / 50 + np.random.normal(0, 6)))
๐Ÿ“ฆ Library / Data Evaluates yield minute, j, max(0, int(base[j] * 0.4 + rโ€ฆ
run() - lines 25โ€“49
LineCodeWhat it does
25
def run():
๐Ÿงฉ Function DEFINES a function run(). Python only remembers it here - its body runs later, each time run() is called.
26
windows = {j: deque(maxlen=WINDOW) for j in junctions}
๐Ÿงฎ Store / Calculate Stores a new dictionary made by a comprehension in variable windows
27
alert_on = {j: False for j in junctions}
๐Ÿงฎ Store / Calculate Stores a new dictionary made by a comprehension in variable alert_on
28
alerts, reservoir, rows, wavg, n = [], [], [], [], 0
๐Ÿงฎ Store / Calculate Stores [], [], [], [], 0 into alerts, reservoir, rows, wavg, n respectively
29
for minute, j, cars in stream():
๐Ÿ” Loop LOOP: takes each item of stream() one-by-one into minute, j, cars and runs the indented block for it
30
n += 1
๐Ÿงฎ Store / Calculate Adds 1 to n (same as n = n + 1)
31
rows.append((minute, j, cars))
๐Ÿงฎ Store / Calculate Adds (minute, j, cars) at the end of list rows
32
w = windows[j]; w.append(cars)
๐Ÿงฎ Store / Calculate Stores the item windows[j] in variable w
32
w = windows[j]; w.append(cars)
๐Ÿงฎ Store / Calculate Adds cars at the end of list w
33
avg = sum(w) / len(w)
๐Ÿงฎ Store / Calculate Stores the value of sum(w) / len(w) (calculated using รท) in variable avg
34
if j == "Azadpur":
๐Ÿ”€ Decision CHECKS whether j is equal to "Azadpur". If True, the indented lines below run; otherwise they are skipped
35
wavg.append(avg)
๐Ÿงฎ Store / Calculate Adds avg at the end of list wavg
36
if len(w) == WINDOW and avg > LIMIT and not alert_on[j]:
๐Ÿ”€ Decision CHECKS whether (len(w) is equal to WINDOW AND avg is greater than LIMIT AND NOT alert_on[j] is True). If True, the indented lines below run; otherwise Python jumps to the elif/else part
37
alerts.append((f"{minute // 60:02d}:{minute % 60:02d}", j, round(avg, 1))); alert_on[j] = True
๐Ÿงฎ Store / Calculate Adds (f"{minute // 60:02d}:{minute % 60:02d}", j, โ€ฆ at the end of list alerts
37
alerts.append((f"{minute // 60:02d}:{minute % 60:02d}", j, round(avg, 1))); alert_on[j] = True
๐Ÿงฎ Store / Calculate Puts True into alert_on[j] (item j of alert_on)
38
elif avg < LIMIT * 0.8:
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether avg is less than LIMIT * 0.8
39
alert_on[j] = False
๐Ÿงฎ Store / Calculate Puts False into alert_on[j] (item j of alert_on)
40
if len(reservoir) < K:
๐Ÿ”€ Decision CHECKS whether len(reservoir) is less than K. If True, the indented lines below run; otherwise Python jumps to the elif/else part
41
reservoir.append(cars)
๐Ÿงฎ Store / Calculate Adds cars at the end of list reservoir
42
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
43
r = random.randint(0, n - 1)
๐Ÿงฎ Store / Calculate Picks a random whole number from 0 to n - 1 (both included); the result is stored in variable r
44
if r < K:
๐Ÿ”€ Decision CHECKS whether r is less than K. If True, the indented lines below run; otherwise they are skipped
45
reservoir[r] = cars
๐Ÿงฎ Store / Calculate Puts the value of cars into reservoir[r] (item r of reservoir)
46
df = pd.DataFrame(rows, columns=["minute", "junction", "cars"])
๐Ÿ“ฆ Library / Data Creates a pandas DataFrame (table) from rows; the result is stored in variable df
47
df["hour"] = df.minute // 60
๐Ÿ“ฆ Library / Data Puts the value of df.minute // 60 (calculated using // (integer division)) into df["hour"] (item "hour" of df)
48
state.update(alerts=alerts, reservoir=reservoir, df=df, wavg=wavg)
๐Ÿงฎ Store / Calculate Updates state with
49
print("Records streamed (4 per minute):", n, "| alerts:", len(alerts))
๐Ÿ–ฅ๏ธ Output Displays the text "Records streamed (4 per minute):", then the value of n, then the text "| alerts:", then the value of len(alerts) on the screen
alerts() - lines 52โ€“55
LineCodeWhat it does
52
def alerts():
๐Ÿงฉ Function DEFINES a function alerts(). Python only remembers it here - its body runs later, each time alerts() is called.
53
print(f"Congestion alerts (15-min average > {LIMIT} vehicles/min):")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Congestion alerts (15-min average > {LIMIT}โ€ฆ with the values filled into { } on the screen
54
for a in state["alerts"]:
๐Ÿ” Loop LOOP: takes each item of state["alerts"] one-by-one into a and runs the indented block for it
55
print("  ALERT", a[0], "-", f"{a[1]:<14}", "avg", a[2])
๐Ÿ–ฅ๏ธ Output Displays the text "ALERT", then the value of a[0], then the text "-", then the f-string f"{a[1]:<14}" with the values filled into { }, then the text "avg", then the value of a[2] on the screen
reservoir() - lines 58โ€“61
LineCodeWhat it does
58
def reservoir():
๐Ÿงฉ Function DEFINES a function reservoir(). Python only remembers it here - its body runs later, each time reservoir() is called.
59
r, df = state["reservoir"], state["df"]
๐Ÿงฎ Store / Calculate Stores state["reservoir"], state["df"] into r, df respectively
60
print("Reservoir size:", len(r), "| sample mean:", round(np.mean(r), 2), "| true mean:", round(df.cars.mean(), 2))
๐Ÿ–ฅ๏ธ Output Displays the text "Reservoir size:", then the value of len(r), then the text "| sample mean:", then the value of round(np.mean(r), 2), then the text "| true mean:", then the value of round(df.cars.mean(), 2) on the screen
61
print("Error of estimate:", round(abs(np.mean(r) - df.cars.mean()) / df.cars.mean() * 100, 2), "% using only", round(len(r) / len(df) * 100, 1), "% of data")
๐Ÿ–ฅ๏ธ Output Displays the text "Error of estimate:", then the value of round(abs(np.mean(r) - df.cars.mean()) / df.cโ€ฆ, then the text "% using only", then the value of round(len(r) / len(df) * 100, 1), then the text "% of data" on the screen
hourly() - lines 64โ€“68
LineCodeWhat it does
64
def hourly():
๐Ÿงฉ Function DEFINES a function hourly(). Python only remembers it here - its body runs later, each time hourly() is called.
65
h = state["df"].groupby("hour").cars.sum()
๐Ÿงฎ Store / Calculate Adds up all values of state["df"].groupby("hour").cars; the result is stored in variable h
66
print("Peak hours:", h.nlargest(3).index.tolist(), "| quietest:", h.nsmallest(3).index.tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Peak hours:", then the value of h.nlargest(3).index.tolist(), then the text "| quietest:", then the value of h.nsmallest(3).index.tolist() on the screen
67
for hr in range(6, 22, 3):
๐Ÿ” Loop LOOP: gives the numbers from 6 up to (not including) 22, jumping by 3; for each number, hr takes that value and the indented block runs once
68
print(f"  {hr:02d}:00  {h[hr]:>6}  " + "#" * int(h[hr] / 1000))
๐Ÿ–ฅ๏ธ Output Displays the value of f" {hr:02d}:00 {h[hr]:>6} " + "#" * int(h[hr]โ€ฆ on the screen
junction_report() - lines 71โ€“74
LineCodeWhat it does
71
def junction_report():
๐Ÿงฉ Function DEFINES a function junction_report(). Python only remembers it here - its body runs later, each time junction_report() is called.
72
g = state["df"].groupby("junction").cars.agg(["sum", "mean", "max"]).round(1).sort_values("sum", ascending=False)
๐Ÿงฎ Store / Calculate Sorts state["df"].groupby("junction").cars.agg(["suโ€ฆ by "sum" in descending order; the result is stored in variable g
73
print(g)
๐Ÿ–ฅ๏ธ Output Displays the value of g on the screen
74
print("Busiest junction:", g.index[0], "| total vehicles counted:", int(state["df"].cars.sum()))
๐Ÿ–ฅ๏ธ Output Displays the text "Busiest junction:", then the value of g.index[0], then the text "| total vehicles counted:", then the value of int(state["df"].cars.sum()) on the screen
vs() - lines 77โ€“83
LineCodeWhat it does
77
def vs():
๐Ÿงฉ Function DEFINES a function vs(). Python only remembers it here - its body runs later, each time vs() is called.
78
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
79
print(f"Volume  : {len(df)} records in one day ({len(df) * 365:,} per year)")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Volume : {len(df)} records in one day ({lenโ€ฆ with the values filled into { } on the screen
80
print("Velocity: 4 new records every minute (real cities: thousands per second)")
๐Ÿ–ฅ๏ธ Output Displays the text "Velocity: 4 new records every minโ€ฆ" on the screen
81
print("Variety : numbers here; real systems add camera video and GPS")
๐Ÿ–ฅ๏ธ Output Displays the text "Variety : numbers here; real systโ€ฆ" on the screen
82
print("Veracity: sensor noise -> we use 15-minute averages, not single readings")
๐Ÿ–ฅ๏ธ Output Displays the text "Veracity: sensor noise -> we use โ€ฆ" on the screen
83
print("Value   : alerts help traffic police divert vehicles in time")
๐Ÿ–ฅ๏ธ Output Displays the text "Value : alerts help traffic policโ€ฆ" on the screen
charts() - lines 86โ€“98
LineCodeWhat it does
86
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
87
df = state["df"]
๐Ÿงฎ Store / Calculate Stores the item state["df"] in variable df
88
df.pivot_table(index="hour", columns="junction", values="cars", aggfunc="sum").plot(figsize=(8, 4))
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
89
plt.ylabel("Vehicles per hour"); plt.title("Hourly traffic from the sensor stream")
๐Ÿ–ฅ๏ธ Output Writes "Vehicles per hour" as the label of the Y-axis
89
plt.ylabel("Vehicles per hour"); plt.title("Hourly traffic from the sensor stream")
๐Ÿ–ฅ๏ธ Output Writes "Hourly traffic from the sensor stream" as the title of the chart
90
plt.savefig("traffic_stream.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "traffic_stream.png"
90
plt.savefig("traffic_stream.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
91
plt.plot(np.arange(len(state["wavg"])) / 60, state["wavg"]); plt.axhline(LIMIT, c="r", ls="--", label="Alert limit")
๐Ÿ–ฅ๏ธ Output Draws a line chart of np.arange(len(state["wavg"])) / 60, state["wavg"]
91
plt.plot(np.arange(len(state["wavg"])) / 60, state["wavg"]); plt.axhline(LIMIT, c="r", ls="--", label="Alert limit")
๐Ÿ–ฅ๏ธ Output Draws a horizontal reference line
92
plt.xlabel("Hour"); plt.ylabel("15-min avg (cars/min)"); plt.title("Sliding-window average - Azadpur"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Hour" as the label of the X-axis
92
plt.xlabel("Hour"); plt.ylabel("15-min avg (cars/min)"); plt.title("Sliding-window average - Azadpur"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "15-min avg (cars/min)" as the label of the Y-axis
92
plt.xlabel("Hour"); plt.ylabel("15-min avg (cars/min)"); plt.title("Sliding-window average - Azadpur"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Sliding-window average - Azadpur" as the title of the chart
92
plt.xlabel("Hour"); plt.ylabel("15-min avg (cars/min)"); plt.title("Sliding-window average - Azadpur"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
93
plt.savefig("traffic_window.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "traffic_window.png"
93
plt.savefig("traffic_window.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
94
plt.hist(df.cars, bins=30, density=True, alpha=.5, label="Full stream")
๐Ÿ–ฅ๏ธ Output Draws a histogram of df.cars
95
plt.hist(state["reservoir"], bins=30, density=True, alpha=.5, label="Reservoir sample")
๐Ÿ–ฅ๏ธ Output Draws a histogram of state["reservoir"]
96
plt.xlabel("Cars per minute"); plt.title("Sample represents the stream"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Cars per minute" as the label of the X-axis
96
plt.xlabel("Cars per minute"); plt.title("Sample represents the stream"); plt.legend()
๐Ÿ–ฅ๏ธ Output Writes "Sample represents the stream" as the title of the chart
96
plt.xlabel("Cars per minute"); plt.title("Sample represents the stream"); plt.legend()
๐Ÿ–ฅ๏ธ Output Shows the legend (which colour means what)
97
plt.savefig("traffic_reservoir.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "traffic_reservoir.png"
97
plt.savefig("traffic_reservoir.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
98
print("Charts saved: traffic_stream.png, traffic_window.png, traffic_reservoir.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: traffic_stream.png,โ€ฆ" on the screen
Q1. What is a data stream?

Continuous, fast-arriving data that must be processed on the fly, often without storing everything.

Q2. What is a sliding window?

Analysis on only the most recent N records, which move forward as new data arrives.

Q3. What is reservoir sampling?

A method to keep a uniform random sample of fixed size K from a stream of unknown length.

Q4. Name the V's of Big Data.

Volume, Velocity, Variety, Veracity and Value.

Q5. Why use deque(maxlen)?

It automatically drops the oldest item when a new one is added - perfect for windows.

08

Product Review Sentiment Classifier - TF-IDF + Logistic Regression (SDG 12)

PYTHON + SKLEARNSDG 12 - Responsible Consumption and ProductionNLP pipelineTF-IDF vectorisationn-gramsLogistic Regressionclassification report
๐Ÿ“ 116 lines of codeโ˜ฐ 8 menu options๐Ÿ–ฅ๏ธ 76 output lines๐Ÿ“„ 25+ page report

Classifies 84 sample reviews of eco-friendly products as positive or negative using TF-IDF features (unigrams and bigrams) and Logistic Regression, evaluates on test reviews, shows the most informative words and predicts the sentiment of new reviews typed by the user.

โœจ Features
  • 84 product reviews of eco-friendly products (positive / negative)
  • TF-IDF features with unigrams and bigrams; stop words removed
  • Logistic Regression classifier with accuracy and classification report
  • Most positive and negative words / phrases from model coefficients
  • Classify new reviews with probability; handles 'not good' through bigrams
  • Compare with Naive Bayes; 3 charts
โ˜ฐ Main menu
1Dataset SummaryCounts and samples
2Train & EvaluateTF-IDF + LogReg
3Top WordsPositive / negative coefficients
4Classify ReviewType a review
5Compare with Naive BayesAccuracy of both
6TF-IDF of a SentenceWeights of its words
7Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Convert reviews to TF-IDF vectors with unigrams and bigrams
  • Train and evaluate a Logistic Regression sentiment classifier
  • Interpret the model through its most positive and negative words
๐Ÿ“š Data dictionary
NameTypePurpose
texts, labelslistsReviews and 1/0 labels
vecTfidfVectorizerngram_range (1, 2)
clfLogisticRegressionClassifier
wordsarrayFeature names
Why it matters: A machine-learning upgrade of the Class X lexicon approach, using the TF-IDF concept taught in NLP.
# =====================================================================
#   PRODUCT REVIEW SENTIMENT CLASSIFIER - TF-IDF + LOGISTIC REGRESSION
# =====================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

products = ["jute bag", "steel bottle", "solar lamp", "bamboo brush", "compost bin", "cloth bag"]
good = ["excellent quality and worth the price", "very good and durable", "great product, eco friendly", "love it, works perfectly",
        "highly recommend, good value for money", "nice design and strong material", "happy with the quality, long lasting"]
bad = ["poor quality, waste of money", "not good, broke in a week", "very bad, stopped working", "not worth the price, cheap material",
       "worst purchase, do not buy", "damaged on arrival, poor packaging", "not happy, low quality and leaks"]
pos = [f"the {p} is {g}" for p in products for g in good]
neg = [f"the {p} is {b}" for p in products for b in bad]
texts, labels = pos + neg, [1] * len(pos) + [0] * len(neg)
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.25, random_state=4, stratify=labels)
vec = TfidfVectorizer(ngram_range=(1, 2), stop_words=["the", "is", "and", "a", "it"])
state = {}


def summary():
    print("Reviews:", len(texts), "| positive:", len(pos), "| negative:", len(neg))
    print("Train:", len(X_tr), "| Test:", len(X_te))
    print("Example +:", pos[0]); print("Example -:", neg[1])


def train():
    clf = LogisticRegression(C=5, max_iter=1000).fit(vec.fit_transform(X_tr), y_tr)
    pred = clf.predict(vec.transform(X_te))
    state["clf"], state["pred"] = clf, pred
    print("Features (words + word pairs):", len(vec.vocabulary_))
    print("Test accuracy:", round(accuracy_score(y_te, pred), 3))
    print(classification_report(y_te, pred, target_names=["negative", "positive"]))


def top_words():
    words = np.array(vec.get_feature_names_out())
    order = np.argsort(state["clf"].coef_[0])
    print("Most negative:", words[order[:8]].tolist())
    print("Most positive:", words[order[-8:]][::-1].tolist())
    return words, order


def classify():
    r = input("Enter a review: ")
    p = state["clf"].predict_proba(vec.transform([r.lower()]))[0][1]
    label = "POSITIVE" if p >= 0.5 else "NEGATIVE"
    print("Sentiment:", label, f"(positive probability {p:.2f})")
    state.setdefault("history", []).append((r[:30], p))


def compare():
    nb = MultinomialNB().fit(vec.transform(X_tr), y_tr)
    print("Logistic Regression accuracy:", round(accuracy_score(y_te, state["pred"]), 3))
    print("Naive Bayes accuracy        :", round(accuracy_score(y_te, nb.predict(vec.transform(X_te))), 3))


def tfidf_sentence():
    s = input("Sentence: ").lower()
    v = vec.transform([s])
    words = vec.get_feature_names_out()
    for i in v.nonzero()[1]:
        print(f"  {words[i]:<18} tf-idf {v[0, i]:.3f}  coef {state['clf'].coef_[0][i]:+.2f}")


def charts():
    words, order = top_words()
    sel = np.r_[order[:7], order[-7:]]
    c = state["clf"].coef_[0][sel]
    plt.barh(words[sel], c, color=["#e03131" if v < 0 else "#2f9e44" for v in c]); plt.title("Most influential words / phrases")
    plt.savefig("review_words.png", dpi=90, bbox_inches="tight"); plt.show()
    cm = confusion_matrix(y_te, state["pred"])
    plt.imshow(cm, cmap="Greens")
    for (i, j), v in np.ndenumerate(cm):
        plt.text(j, i, v, ha="center", va="center", fontsize=16)
    plt.xticks([0, 1], ["Neg", "Pos"]); plt.yticks([0, 1], ["Neg", "Pos"]); plt.title("Confusion matrix")
    plt.savefig("review_cm.png", dpi=90, bbox_inches="tight"); plt.show()
    h = state.get("history", [])
    plt.barh([t for t, _ in h], [p for _, p in h], color=["#2f9e44" if p >= .5 else "#e03131" for _, p in h])
    plt.axvline(.5, ls="--", c="k"); plt.xlim(0, 1); plt.title("Positive probability of your reviews")
    plt.savefig("review_probs.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: review_words.png, review_cm.png, review_probs.png")


print("=" * 60)
print("   REVIEW SENTIMENT CLASSIFIER  (TF-IDF + Logistic Regression)")
print("=" * 60)
while True:
    print("\n1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        summary()
    elif ch == "2":
        train()
    elif "clf" not in state and ch in "34567":
        print("Train the model first (option 2).")
    elif ch == "3":
        top_words()
    elif ch == "4":
        classify()
    elif ch == "5":
        compare()
    elif ch == "6":
        tfidf_sentence()
    elif ch == "7":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Build review dataset
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. TF-IDF transform review
  6. predict_proba
  7. p >= 0.5? → No: NEGATIVE
  8. POSITIVE
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1TrainAccuracy ~ 1.0PASS
2Top wordsexcellent / poorPASS
3'bamboo toothbrush is excellent'POSITIVEPASS
4'not good, bottle leaks'NEGATIVEPASS
5CompareBoth accuraciesPASS
6TF-IDF sentenceWord weightsPASS
7Classify before train'Train first'PASS
โš  Limitations
  • Template-generated reviews
  • Sarcasm not handled
  • English only
  • Small vocabulary
๐Ÿš€ Future scope
  • Real Amazon / Flipkart reviews
  • Aspect-based sentiment (price, quality, delivery)
  • Transformers (BERT)
  • Hindi reviews

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, matplotlib.pyplot - drawing charts, TfidfVectorizer, LogisticRegression, MultinomialNB, train_test_split, accuracy_score, classification_report, confusion_matrix are loaded.
  2. Global variables / constants are created: products, good, bad, pos, neg, vec, state.
  3. 7 functions are defined (lines 25โ€“86) - Python stores them but does NOT run them yet.
  4. Main program starts at line 19: texts, labels = pos + neg, [1] * len(pos) + [0] * len(neg) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
summary()25โ€“28Summarymain program
train()31โ€“37Trainmain program
top_words()40โ€“45Top wordscharts(), main program
classify()48โ€“53Classifymain program
compare()56โ€“59Comparemain program
tfidf_sentence()62โ€“67Tfidf sentencemain program
charts()70โ€“86Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
19
texts, labels = pos + neg, [1] * len(pos) + [0] * len(neg)
๐Ÿงฎ Store / Calculate Stores pos + neg, [1] * len(pos) + [0] * len(neg) into texts, labels respectively
20
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.25, random_state=4, stratify=labels)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te
21
vec = TfidfVectorizer(ngram_range=(1, 2), stop_words=["the", "is", "and", "a", "it"])
๐Ÿงฎ Store / Calculate Calls TfidfVectorizer(); the result is stored in variable vec
22
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
89
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
90
print("   REVIEW SENTIMENT CLASSIFIER  (TF-IDF + Logistic Regression)")
๐Ÿ–ฅ๏ธ Output Displays the text "REVIEW SENTIMENT CLASSIFIER (TF-Iโ€ฆ" on the screen
91
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
92
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
93
print("\n1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Summary 2.Train 3.Top Words 4.Cโ€ฆ" on the screen
94
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
95
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
96
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
97
break
๐Ÿ” Loop BREAK - leaves the loop immediately
98
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
99
summary()
๐Ÿงฎ Store / Calculate Calls our own function summary()
100
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
101
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
102
elif "clf" not in state and ch in "34567":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("clf" is not present in state AND ch is present in "34567")
103
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
104
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
105
top_words()
๐Ÿงฎ Store / Calculate Calls our own function top_words()
106
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
107
classify()
๐Ÿงฎ Store / Calculate Calls our own function classify()
108
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
109
compare()
๐Ÿงฎ Store / Calculate Calls our own function compare()
110
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
111
tfidf_sentence()
๐Ÿงฎ Store / Calculate Calls our own function tfidf_sentence()
112
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
113
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
114
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
115
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: REVIEW SENTIMENT CLASSIFIER (TF-IDF + Logistic Regression) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: summary()
    shows: Reviews: 84 | positive: 42 | negative: 42 (+4 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Features (words + word pairs): 159 (+8 more lines)
  5. You type 3 at Enter choice:
    runs: top_words()
    shows: Most negative: ['not', 'poor', 'cheap', 'cheap material', 'price cheap', 'not worth', 'lea (+2 more lines)
  6. You type 4 at Enter choice:
    runs: classify()
  7. You type The bamboo toothbrush is excellent and eco friendly at Enter a review:
    shows: Sentiment: POSITIVE (positive probability 0.84) (+1 more lines)
  8. You type 4 at Enter choice:
    runs: classify()
  9. You type Not good, the steel bottle leaks and broke in a week at Enter a review:
    shows: Sentiment: NEGATIVE (positive probability 0.12) (+1 more lines)
  10. You type 4 at Enter choice:
    runs: classify()
  11. You type Delivery was quick but the jute bag is poor quality at Enter a review:
    shows: Sentiment: NEGATIVE (positive probability 0.36) (+1 more lines)
  12. You type 5 at Enter choice:
    runs: compare()
    shows: Logistic Regression accuracy: 1.0 (+2 more lines)
  13. You type 6 at Enter choice:
    runs: tfidf_sentence()
  14. You type the solar lamp is not worth the price at Sentence:
    shows: lamp tf-idf 0.291 coef +0.03 (+9 more lines)
  15. You type 7 at Enter choice:
    runs: charts() โ†’ top_words()
    shows: Most negative: ['not', 'poor', 'cheap', 'cheap material', 'price cheap', 'not worth', 'lea (+6 more lines)
  16. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
summary() - lines 25โ€“28
LineCodeWhat it does
25
def summary():
๐Ÿงฉ Function DEFINES a function summary(). Python only remembers it here - its body runs later, each time summary() is called.
26
print("Reviews:", len(texts), "| positive:", len(pos), "| negative:", len(neg))
๐Ÿ–ฅ๏ธ Output Displays the text "Reviews:", then the value of len(texts), then the text "| positive:", then the value of len(pos), then the text "| negative:", then the value of len(neg) on the screen
27
print("Train:", len(X_tr), "| Test:", len(X_te))
๐Ÿ–ฅ๏ธ Output Displays the text "Train:", then the value of len(X_tr), then the text "| Test:", then the value of len(X_te) on the screen
28
print("Example +:", pos[0]); print("Example -:", neg[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Example +:", then the value of pos[0] on the screen
28
print("Example +:", pos[0]); print("Example -:", neg[1])
๐Ÿ–ฅ๏ธ Output Displays the text "Example -:", then the value of neg[1] on the screen
train() - lines 31โ€“37
LineCodeWhat it does
31
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
32
clf = LogisticRegression(C=5, max_iter=1000).fit(vec.fit_transform(X_tr), y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model LogisticRegression(C=5, max_iter=1000) on the given data; the result is stored in variable clf
33
pred = clf.predict(vec.transform(X_te))
๐Ÿ“ฆ Library / Data Uses the trained model clf to predict answers for vec.transform(X_te); the result is stored in variable pred
34
state["clf"], state["pred"] = clf, pred
๐Ÿงฎ Store / Calculate Stores the tuple clf, pred in variables state["clf"], state["pred"]
35
print("Features (words + word pairs):", len(vec.vocabulary_))
๐Ÿ–ฅ๏ธ Output Displays the text "Features (words + word pairs):", then the value of len(vec.vocabulary_) on the screen
36
print("Test accuracy:", round(accuracy_score(y_te, pred), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Test accuracy:", then the value of round(accuracy_score(y_te, pred), 3) on the screen
37
print(classification_report(y_te, pred, target_names=["negative", "positive"]))
๐Ÿ–ฅ๏ธ Output Displays the value of classification_report(y_te, pred, target_nameโ€ฆ on the screen
top_words() - lines 40โ€“45
LineCodeWhat it does
40
def top_words():
๐Ÿงฉ Function DEFINES a function top_words(). Python only remembers it here - its body runs later, each time top_words() is called.
41
words = np.array(vec.get_feature_names_out())
๐Ÿ“ฆ Library / Data Makes a NumPy array from vec.get_feature_names_out(); the result is stored in variable words
42
order = np.argsort(state["clf"].coef_[0])
๐Ÿ“ฆ Library / Data Gives the positions that would sort np; the result is stored in variable order
43
print("Most negative:", words[order[:8]].tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Most negative:", then the value of words[order[:8]].tolist() on the screen
44
print("Most positive:", words[order[-8:]][::-1].tolist())
๐Ÿ–ฅ๏ธ Output Displays the text "Most positive:", then the value of words[order[-8:]][::-1].tolist() on the screen
45
return words, order
๐Ÿงฉ Function Sends back (returns) the tuple words, order to the line that called the function
classify() - lines 48โ€“53
LineCodeWhat it does
48
def classify():
๐Ÿงฉ Function DEFINES a function classify(). Python only remembers it here - its body runs later, each time classify() is called.
49
r = input("Enter a review: ")
โŒจ๏ธ Input Shows the message "Enter a review: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable r
50
p = state["clf"].predict_proba(vec.transform([r.lower()]))[0][1]
๐Ÿงฎ Store / Calculate Stores the item state["clf"].predict_proba(vec.transform([r.lโ€ฆ in variable p
51
label = "POSITIVE" if p >= 0.5 else "NEGATIVE"
๐Ÿงฎ Store / Calculate Stores either "POSITIVE" or "NEGATIVE" depending on p >= 0.5 in variable label
52
print("Sentiment:", label, f"(positive probability {p:.2f})")
๐Ÿ–ฅ๏ธ Output Displays the text "Sentiment:", then the value of label, then the f-string f"(positive probability {p:.2f})" with the values filled into { } on the screen
53
state.setdefault("history", []).append((r[:30], p))
๐Ÿงฎ Store / Calculate Adds (r[:30], p) at the end of list state.setdefault("history", [])
compare() - lines 56โ€“59
LineCodeWhat it does
56
def compare():
๐Ÿงฉ Function DEFINES a function compare(). Python only remembers it here - its body runs later, each time compare() is called.
57
nb = MultinomialNB().fit(vec.transform(X_tr), y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model MultinomialNB() on the given data; the result is stored in variable nb
58
print("Logistic Regression accuracy:", round(accuracy_score(y_te, state["pred"]), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Logistic Regression accuracy:", then the value of round(accuracy_score(y_te, state["pred"]), 3) on the screen
59
print("Naive Bayes accuracy        :", round(accuracy_score(y_te, nb.predict(vec.transform(X_te))), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Naive Bayes accuracy :", then the value of round(accuracy_score(y_te, nb.predict(vec.traโ€ฆ on the screen
tfidf_sentence() - lines 62โ€“67
LineCodeWhat it does
62
def tfidf_sentence():
๐Ÿงฉ Function DEFINES a function tfidf_sentence(). Python only remembers it here - its body runs later, each time tfidf_sentence() is called.
63
s = input("Sentence: ").lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable s
64
v = vec.transform([s])
๐Ÿงฎ Store / Calculate Converts (scales / changes) [s] using what was learnt; the result is stored in variable v
65
words = vec.get_feature_names_out()
๐Ÿงฎ Store / Calculate Gives the names of the features (words); the result is stored in variable words
66
for i in v.nonzero()[1]:
๐Ÿ” Loop LOOP: takes each item of v.nonzero()[1] one-by-one into i and runs the indented block for it
67
print(f"  {words[i]:<18} tf-idf {v[0, i]:.3f}  coef {state['clf'].coef_[0][i]:+.2f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {words[i]:<18} tf-idf {v[0, i]:.3f} coef {โ€ฆ with the values filled into { } on the screen
charts() - lines 70โ€“86
LineCodeWhat it does
70
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
71
words, order = top_words()
๐Ÿงฎ Store / Calculate Calls our own function top_words(); the result is stored in variables words, order
72
sel = np.r_[order[:7], order[-7:]]
๐Ÿ“ฆ Library / Data Stores a slice np.r_[order[:7], order[-7:]] (part of np.r_) in variable sel
73
c = state["clf"].coef_[0][sel]
๐Ÿงฎ Store / Calculate Stores the item state["clf"].coef_[0][sel] in variable c
74
plt.barh(words[sel], c, color=["#e03131" if v < 0 else "#2f9e44" for v in c]); plt.title("Most influential words / phrases")
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
74
plt.barh(words[sel], c, color=["#e03131" if v < 0 else "#2f9e44" for v in c]); plt.title("Most influential words / phrases")
๐Ÿ–ฅ๏ธ Output Writes "Most influential words / phrases" as the title of the chart
75
plt.savefig("review_words.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "review_words.png"
75
plt.savefig("review_words.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
76
cm = confusion_matrix(y_te, state["pred"])
๐Ÿงฎ Store / Calculate Makes the confusion matrix (actual vs predicted counts); the result is stored in variable cm
77
plt.imshow(cm, cmap="Greens")
๐Ÿ–ฅ๏ธ Output Shows the image / matrix as a picture
78
for (i, j), v in np.ndenumerate(cm):
๐Ÿ” Loop LOOP: takes each item of np.ndenumerate(cm) one-by-one into (i, j), v and runs the indented block for it
79
plt.text(j, i, v, ha="center", va="center", fontsize=16)
๐Ÿ–ฅ๏ธ Output Writes text on the chart
80
plt.xticks([0, 1], ["Neg", "Pos"]); plt.yticks([0, 1], ["Neg", "Pos"]); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
80
plt.xticks([0, 1], ["Neg", "Pos"]); plt.yticks([0, 1], ["Neg", "Pos"]); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the Y-axis
80
plt.xticks([0, 1], ["Neg", "Pos"]); plt.yticks([0, 1], ["Neg", "Pos"]); plt.title("Confusion matrix")
๐Ÿ–ฅ๏ธ Output Writes "Confusion matrix" as the title of the chart
81
plt.savefig("review_cm.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "review_cm.png"
81
plt.savefig("review_cm.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
82
h = state.get("history", [])
๐Ÿงฎ Store / Calculate Gets the value for key "history" from state (or [] if the key is not there); the result is stored in variable h
83
plt.barh([t for t, _ in h], [p for _, p in h], color=["#2f9e44" if p >= .5 else "#e03131" for _, p in h])
๐Ÿ–ฅ๏ธ Output Draws a horizontal bar chart
84
plt.axvline(.5, ls="--", c="k"); plt.xlim(0, 1); plt.title("Positive probability of your reviews")
๐Ÿ–ฅ๏ธ Output Draws a vertical reference line
84
plt.axvline(.5, ls="--", c="k"); plt.xlim(0, 1); plt.title("Positive probability of your reviews")
๐Ÿ–ฅ๏ธ Output Sets the range of the X-axis
84
plt.axvline(.5, ls="--", c="k"); plt.xlim(0, 1); plt.title("Positive probability of your reviews")
๐Ÿ–ฅ๏ธ Output Writes "Positive probability of your reviews" as the title of the chart
85
plt.savefig("review_probs.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "review_probs.png"
85
plt.savefig("review_probs.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
86
print("Charts saved: review_words.png, review_cm.png, review_probs.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: review_words.png, rโ€ฆ" on the screen
Q1. What is TF-IDF?

Term Frequency x Inverse Document Frequency - gives high weight to words frequent in a document but rare overall.

Q2. Why bigrams?

Pairs like 'not good' carry meaning that single words miss.

Q3. How are important words found?

From logistic regression coefficients: large positive = positive sentiment.

Q4. What is the C parameter?

Inverse of regularisation strength; higher C fits training data more closely.

Q5. Which SDG?

SDG 12 - Responsible Consumption (choosing good eco products).

09

Crop Yield Prediction using the Data Science Methodology (SDG 2)

PYTHON + SKLEARNSDG 2 - Zero Hunger10 steps of Data Science Methodologyfeature engineeringmodel comparisonk-fold CVhold-out test
๐Ÿ“ 139 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 94 output lines๐Ÿ“„ 25+ page report

Walks through every step of the IBM Data Science Methodology - from business understanding to feedback - to predict wheat yield from rainfall, temperature, fertiliser, irrigation and soil quality using a Random Forest, with the steps printed as a capstone report.

โœจ Features
  • Data Science Methodology in 10 steps (business understanding to feedback)
  • 300 simulated wheat plots: rainfall, temperature, fertiliser, irrigation, soil
  • Data understanding: missing values, statistics, correlation
  • Preparation: median imputation and one-hot encoding of soil
  • Modeling with Linear Regression and Random Forest (5-fold CV); evaluation on hold-out
  • Deployment: predict yield for a farmer's plot; fertiliser what-if; 3 charts
โ˜ฐ Main menu
1Steps 1-3 UnderstandingProblem, approach, data needs
2Steps 4-5 Collect & UnderstandData, missing, correlation
3Step 6 PrepareImpute + one-hot
4Steps 7-8 Model & EvaluateCV and hold-out
5Step 9 Deploy - Predict PlotUser inputs a plot
6Fertiliser What-ifYield vs fertiliser
7Step 10 FeedbackRetraining plan
8Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Follow and document all 10 steps of the Data Science Methodology
  • Compare models using cross-validation and validate on hold-out data
  • Deploy the best model as a function and explain feature importance
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameRain_mm, Temp_C, Fert_kg, Irrigated, Soil, Yield
dataDataFrameOne-hot encoded data
modelsdictLinearRegression, RandomForest
modelestimatorBest model
Why it matters: A template capstone project that students can adapt to their own SDG problem and document step by step.
# =====================================================================
#   CROP YIELD PREDICTION USING THE DATA SCIENCE METHODOLOGY  (SDG 2)
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score

rng = np.random.default_rng(21)
n = 300
df = pd.DataFrame({"Rain_mm": rng.normal(600, 120, n).round(), "Temp_C": rng.normal(21, 2.5, n).round(1),
                   "Fert_kg": rng.uniform(40, 180, n).round(), "Irrigated": rng.integers(0, 2, n),
                   "Soil": rng.choice(["poor", "average", "good"], n, p=[0.25, 0.45, 0.30])})
soil_eff = df.Soil.map({"poor": -6, "average": 0, "good": 5})
df["Yield"] = (20 + 0.015 * df.Rain_mm - 0.6 * (df.Temp_C - 20) ** 2 + 0.12 * df.Fert_kg - 0.0003 * df.Fert_kg ** 2
               + 6 * df.Irrigated + soil_eff + rng.normal(0, 2, n)).clip(lower=8).round(1)
df.loc[rng.choice(n, 12, replace=False), "Rain_mm"] = np.nan
state = {}


def understanding():
    print("STEP 1 Business understanding : predict wheat yield to plan seeds, credit and storage")
    print("STEP 2 Analytic approach      : supervised REGRESSION (target = yield, quintal/ha)")
    print("STEP 3 Data requirements      : rainfall, temperature, fertiliser, irrigation, soil type")


def collect():
    print("STEP 4 Data collection        :", len(df), "plot records (simulated survey)")
    print("STEP 5 Data understanding")
    print(df.describe().round(1))
    print("Missing values:", df.isnull().sum().to_dict())
    print("Correlation with yield:", df.drop(columns="Soil").corr()["Yield"].drop("Yield").round(2).to_dict())
    print("Average yield by soil:", df.groupby("Soil").Yield.mean().round(1).to_dict())


def prepare():
    d = df.copy()
    d["Rain_mm"] = d.Rain_mm.fillna(d.Rain_mm.median())
    data = pd.get_dummies(d, columns=["Soil"], dtype=int)
    state["X"], state["y"] = data.drop(columns="Yield"), data.Yield
    print("STEP 6 Data preparation: median imputation + one-hot soil")
    print("Missing now:", int(data.isnull().sum().sum()), "| features:", list(state["X"].columns))


def model_eval():
    if "X" not in state:
        prepare()
    X_tr, X_te, y_tr, y_te = train_test_split(state["X"], state["y"], test_size=0.2, random_state=0)
    models = {"Linear Regression": LinearRegression(), "Random Forest": RandomForestRegressor(n_estimators=200, random_state=0)}
    scores = {}
    print("STEP 7 Modeling (5-fold CV RMSE):")
    for name, m in models.items():
        scores[name] = -cross_val_score(m, X_tr, y_tr, cv=5, scoring="neg_root_mean_squared_error").mean()
        print(f"   {name:<18} {scores[name]:.3f}")
    best = min(scores, key=scores.get)
    m = models[best].fit(X_tr, y_tr)
    p = m.predict(X_te)
    state.update(model=m, best=best, test=(y_te, p))
    print(f"STEP 8 Evaluation (hold-out): {best} | RMSE {np.sqrt(mean_squared_error(y_te, p)):.3f} | R2 {r2_score(y_te, p):.3f}")


def predict_plot():
    vals = [float(input("Rainfall (mm)        : ")), float(input("Temperature (C)      : ")), float(input("Fertiliser (kg/ha)   : ")), int(input("Irrigated (1/0)      : "))]
    soil = input("Soil (poor/average/good): ").strip().lower()
    if soil not in ("poor", "average", "good"):
        print("Soil must be poor/average/good.")
        return
    row = dict(zip(["Rain_mm", "Temp_C", "Fert_kg", "Irrigated"], vals))
    row.update({"Soil_average": int(soil == "average"), "Soil_good": int(soil == "good"), "Soil_poor": int(soil == "poor")})
    y = state["model"].predict(pd.DataFrame([row])[state["X"].columns])[0]
    print(f"STEP 9 Deployment: predicted yield {y:.1f} quintal/ha -> about {y * 2.47:.0f} quintal per 2.47 acres")


def what_if():
    base = state["X"].median().to_dict()
    base.update({"Irrigated": 1, "Soil_average": 1, "Soil_good": 0, "Soil_poor": 0})
    res = []
    for f in range(40, 200, 20):
        base["Fert_kg"] = f
        res.append((f, state["model"].predict(pd.DataFrame([base])[state["X"].columns])[0]))
        print(f"  fertiliser {f:>3} kg/ha -> yield {res[-1][1]:.1f}")
    bf = max(res, key=lambda r: r[1])
    print(f"Best fertiliser dose about {bf[0]} kg/ha; more than this does not help (diminishing returns).")
    return res


def feedback():
    print("STEP 10 Feedback: after harvest, record actual yield of each plot,")
    print("        compare with prediction, add the new data and retrain every season.")


def charts():
    m = state["model"]
    imp = pd.Series(getattr(m, "feature_importances_", np.abs(getattr(m, "coef_", np.zeros(7)))), index=state["X"].columns).sort_values()
    imp.plot(kind="barh", color="seagreen", figsize=(6, 3.5)); plt.title(f"Feature importance ({state['best']})")
    plt.tight_layout(); plt.savefig("yield_importance.png", dpi=90); plt.show()
    y_te, p = state["test"]
    plt.scatter(y_te, p, c="#e67700"); plt.plot([y_te.min(), y_te.max()], [y_te.min(), y_te.max()], "k--")
    plt.xlabel("Actual yield"); plt.ylabel("Predicted"); plt.title("Hold-out: actual vs predicted")
    plt.savefig("yield_pred.png", dpi=90, bbox_inches="tight"); plt.show()
    res = what_if()
    plt.plot([r[0] for r in res], [r[1] for r in res], "o-"); plt.xlabel("Fertiliser kg/ha"); plt.ylabel("Predicted yield"); plt.title("Fertiliser what-if")
    plt.savefig("yield_fert.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: yield_importance.png, yield_pred.png, yield_fert.png")


print("=" * 60)
print("   CROP YIELD PREDICTION - DATA SCIENCE METHODOLOGY  (SDG 2)")
print("=" * 60)
while True:
    print("\n1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Bye!")
        break
    elif ch == "1":
        understanding()
    elif ch == "2":
        collect()
    elif ch == "3":
        prepare()
    elif ch == "4":
        model_eval()
    elif ch == "7":
        feedback()
    elif "model" not in state and ch in "568":
        print("Build the model first (option 4).")
    elif ch == "5":
        predict_plot()
    elif ch == "6":
        what_if()
    elif ch == "8":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Show methodology menu
  3. Collect and understand data
  4. Prepare (impute, encode)
  5. Cross-validate models
  6. Model ready? → No: run modeling step
  7. Predict yield for new plot
  8. Choice is 0? → No: show menu
  9. Stop
#Test case / inputExpected resultStatus
1Understanding10-step planPASS
2Collect300 rows, 12 missingPASS
3Prepare0 missing, 7 featuresPASS
4ModelRF lower RMSEPASS
5Predict 650, 22, 120, 1, goodYield in q/haPASS
6Soil 'sandy''Soil must be poor/average/good'PASS
7What-ifBest fertiliser amountPASS
8Charts3 PNG filesPASS
โš  Limitations
  • Simulated data
  • Single crop
  • No pest / seed variety data
  • Random forest is less interpretable
๐Ÿš€ Future scope
  • Satellite NDVI data
  • District-level data from data.gov.in
  • Mobile app for Krishi Vigyan Kendra
  • Weather forecast integration

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, train_test_split, cross_val_score, LinearRegression, RandomForestRegressor, mean_squared_error, r2_score are loaded.
  2. Global variables / constants are created: rng, n, df, soil_eff, state.
  3. 8 functions are defined (lines 24โ€“107) - Python stores them but does NOT run them yet.
  4. Main program starts at line 18: df["Yield"] = (20 + 0.015 * df.Rain_mm - 0.6 * (df.Temp_C - 20) ** 2 + - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
understanding()24โ€“27Understandingmain program
collect()30โ€“36Collectmain program
prepare()39โ€“45Preparemodel_eval(), main program
model_eval()48โ€“62Model evalmain program
predict_plot()65โ€“74Predict plotmain program
what_if()77โ€“87What ifcharts(), main program
feedback()90โ€“92Feedbackmain program
charts()95โ€“107Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
18
df["Yield"] = (20 + 0.015 * df.Rain_mm - 0.6 * (df.Temp_C - 20) ** 2 + 0.12 * df.Fert_kg - 0.0003 * df.Fert_kg ** 2
               + 6 * df.Irrigated + soil_โ€ฆ
๐Ÿ“ฆ Library / Data Rounds the values of (20 + 0.015 * df.Rain_mm - 0.6 * (df.Temp_C -โ€ฆ to 1 decimal places; the result is put into df["Yield"] (item "Yield" of df)
20
df.loc[rng.choice(n, 12, replace=False), "Rain_mm"] = np.nan
๐Ÿ“ฆ Library / Data Puts np.nan into df.loc[rng.choice(n, 12, replace=False), "Raiโ€ฆ (item rng.choice(n, 12, replace=False), "Rain_mm" of df.loc)
21
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
110
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
111
print("   CROP YIELD PREDICTION - DATA SCIENCE METHODOLOGY  (SDG 2)")
๐Ÿ–ฅ๏ธ Output Displays the text "CROP YIELD PREDICTION - DATA SCIEโ€ฆ" on the screen
112
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
113
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
114
print("\n1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Understand 2.Collect 3.Prepare โ€ฆ" on the screen
115
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
116
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
117
print("Bye!")
๐Ÿ–ฅ๏ธ Output Displays the text "Bye!" on the screen
118
break
๐Ÿ” Loop BREAK - leaves the loop immediately
119
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
120
understanding()
๐Ÿงฎ Store / Calculate Calls our own function understanding()
121
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
122
collect()
๐Ÿงฎ Store / Calculate Calls our own function collect()
123
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
124
prepare()
๐Ÿงฎ Store / Calculate Calls our own function prepare()
125
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
126
model_eval()
๐Ÿงฎ Store / Calculate Calls our own function model_eval()
127
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
128
feedback()
๐Ÿงฎ Store / Calculate Calls our own function feedback()
129
elif "model" not in state and ch in "568":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("model" is not present in state AND ch is present in "568")
130
print("Build the model first (option 4).")
๐Ÿ–ฅ๏ธ Output Displays the text "Build the model first (option 4)." on the screen
131
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
132
predict_plot()
๐Ÿงฎ Store / Calculate Calls our own function predict_plot()
133
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
134
what_if()
๐Ÿงฎ Store / Calculate Calls our own function what_if()
135
elif ch == "8":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "8"
136
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
137
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
138
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: CROP YIELD PREDICTION - DATA SCIENCE METHODOLOGY (SDG 2) (+1 more lines)
  2. You type 5 at Enter choice:
    shows: Build the model first (option 4). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: understanding()
    shows: STEP 1 Business understanding : predict wheat yield to plan seeds, credit and storage (+3 more lines)
  4. You type 2 at Enter choice:
    runs: collect()
    shows: STEP 4 Data collection : 300 plot records (simulated survey) (+14 more lines)
  5. You type 3 at Enter choice:
    runs: prepare()
    shows: STEP 6 Data preparation: median imputation + one-hot soil (+2 more lines)
  6. You type 4 at Enter choice:
    runs: model_eval()
    shows: STEP 7 Modeling (5-fold CV RMSE): (+4 more lines)
  7. You type 5 at Enter choice:
    runs: predict_plot()
  8. You type 650 at Rainfall (mm) :
  9. You type 22 at Temperature (C) :
  10. You type 120 at Fertiliser (kg/ha) :
  11. You type 1 at Irrigated (1/0) :
  12. You type good at Soil (poor/average/good):
    shows: STEP 9 Deployment: predicted yield 49.5 quintal/ha -> about 122 quintal per 2.47 acres (+1 more lines)
  13. You type 5 at Enter choice:
    runs: predict_plot()
  14. You type 600 at Rainfall (mm) :
  15. You type 21 at Temperature (C) :
  16. You type 100 at Fertiliser (kg/ha) :
  17. You type 0 at Irrigated (1/0) :
  18. You type sandy at Soil (poor/average/good):
    shows: Soil must be poor/average/good. (+1 more lines)
  19. You type 6 at Enter choice:
    runs: what_if()
    shows: fertiliser 40 kg/ha -> yield 37.9 (+9 more lines)
  20. You type 7 at Enter choice:
    runs: feedback()
    shows: STEP 10 Feedback: after harvest, record actual yield of each plot, (+2 more lines)
  21. You type 8 at Enter choice:
    runs: charts() โ†’ what_if()
    shows: [chart is drawn] (+13 more lines)
  22. You type 0 at Enter choice:
    shows: Bye!
โ‘ค Inside each function - line by line
understanding() - lines 24โ€“27
LineCodeWhat it does
24
def understanding():
๐Ÿงฉ Function DEFINES a function understanding(). Python only remembers it here - its body runs later, each time understanding() is called.
25
print("STEP 1 Business understanding : predict wheat yield to plan seeds, credit and storage")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 1 Business understanding : pโ€ฆ" on the screen
26
print("STEP 2 Analytic approach      : supervised REGRESSION (target = yield, quintal/ha)")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 2 Analytic approach : supervโ€ฆ" on the screen
27
print("STEP 3 Data requirements      : rainfall, temperature, fertiliser, irrigation, soil type")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 3 Data requirements : rainfaโ€ฆ" on the screen
collect() - lines 30โ€“36
LineCodeWhat it does
30
def collect():
๐Ÿงฉ Function DEFINES a function collect(). Python only remembers it here - its body runs later, each time collect() is called.
31
print("STEP 4 Data collection        :", len(df), "plot records (simulated survey)")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 4 Data collection :", then the value of len(df), then the text "plot records (simulated survey)" on the screen
32
print("STEP 5 Data understanding")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 5 Data understanding" on the screen
33
print(df.describe().round(1))
๐Ÿ–ฅ๏ธ Output Displays the value of df.describe().round(1) on the screen
34
print("Missing values:", df.isnull().sum().to_dict())
๐Ÿ–ฅ๏ธ Output Displays the text "Missing values:", then the value of df.isnull().sum().to_dict() on the screen
35
print("Correlation with yield:", df.drop(columns="Soil").corr()["Yield"].drop("Yield").round(2).to_dict())
๐Ÿ–ฅ๏ธ Output Displays the text "Correlation with yield:", then the value of df.drop(columns="Soil").corr()["Yield"].drop(โ€ฆ on the screen
36
print("Average yield by soil:", df.groupby("Soil").Yield.mean().round(1).to_dict())
๐Ÿ–ฅ๏ธ Output Displays the text "Average yield by soil:", then the value of df.groupby("Soil").Yield.mean().round(1).to_dโ€ฆ on the screen
prepare() - lines 39โ€“45
LineCodeWhat it does
39
def prepare():
๐Ÿงฉ Function DEFINES a function prepare(). Python only remembers it here - its body runs later, each time prepare() is called.
40
d = df.copy()
๐Ÿ“ฆ Library / Data Makes a copy of df; the result is stored in variable d
41
d["Rain_mm"] = d.Rain_mm.fillna(d.Rain_mm.median())
๐Ÿงฎ Store / Calculate Fills the missing (NaN) values of d.Rain_mm with d.Rain_mm.median(); the result is put into d["Rain_mm"] (item "Rain_mm" of d)
42
data = pd.get_dummies(d, columns=["Soil"], dtype=int)
๐Ÿ“ฆ Library / Data Calls pd.get_dummies(d); the result is stored in variable data
43
state["X"], state["y"] = data.drop(columns="Yield"), data.Yield
๐Ÿงฎ Store / Calculate Stores the tuple data.drop(columns="Yield"), data.Yield in variables state["X"], state["y"]
44
print("STEP 6 Data preparation: median imputation + one-hot soil")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 6 Data preparation: median iโ€ฆ" on the screen
45
print("Missing now:", int(data.isnull().sum().sum()), "| features:", list(state["X"].columns))
๐Ÿ–ฅ๏ธ Output Displays the text "Missing now:", then the value of int(data.isnull().sum().sum()), then the text "| features:", then the value of list(state["X"].columns) on the screen
model_eval() - lines 48โ€“62
LineCodeWhat it does
48
def model_eval():
๐Ÿงฉ Function DEFINES a function model_eval(). Python only remembers it here - its body runs later, each time model_eval() is called.
49
if "X" not in state:
๐Ÿ”€ Decision CHECKS whether "X" is not present in state. If True, the indented lines below run; otherwise they are skipped
50
prepare()
๐Ÿงฎ Store / Calculate Calls our own function prepare()
51
X_tr, X_te, y_tr, y_te = train_test_split(state["X"], state["y"], test_size=0.2, random_state=0)
๐Ÿงฎ Store / Calculate Splits the data into training and testing parts (20% for testing) and stores them in X_tr, X_te, y_tr, y_te
52
models = {"Linear Regression": LinearRegression(), "Random Forest": RandomForestRegressor(n_estimators=200, random_state=0)}
๐Ÿงฎ Store / Calculate Stores a dictionary {"Linear Regression": LinearRegression(), "Raโ€ฆ in variable models
53
scores = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable scores
54
print("STEP 7 Modeling (5-fold CV RMSE):")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 7 Modeling (5-fold CV RMSE):" on the screen
55
for name, m in models.items():
๐Ÿ” Loop LOOP over every (key, value) pair of dictionary models; name, m get one pair each round
56
scores[name] = -cross_val_score(m, X_tr, y_tr, cv=5, scoring="neg_root_mean_squared_error").mean()
๐Ÿงฎ Store / Calculate Puts -cross_val_score(m, X_tr, y_tr, cv=5, scoringโ€ฆ into scores[name] (item name of scores)
57
print(f"   {name:<18} {scores[name]:.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" {name:<18} {scores[name]:.3f}" with the values filled into { } on the screen
58
best = min(scores, key=scores.get)
๐Ÿงฎ Store / Calculate Finds the smallest value among scores; the result is stored in variable best
59
m = models[best].fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model models[best] on the given data; the result is stored in variable m
60
p = m.predict(X_te)
๐Ÿ“ฆ Library / Data Uses the trained model m to predict answers for X_te; the result is stored in variable p
61
state.update(model=m, best=best, test=(y_te, p))
๐Ÿงฎ Store / Calculate Updates state with
62
print(f"STEP 8 Evaluation (hold-out): {best} | RMSE {np.sqrt(mean_squared_error(y_te, p)):.3f} | R2 {r2_score(y_te, p):.3f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"STEP 8 Evaluation (hold-out): {best} | RMSEโ€ฆ with the values filled into { } on the screen
predict_plot() - lines 65โ€“74
LineCodeWhat it does
65
def predict_plot():
๐Ÿงฉ Function DEFINES a function predict_plot(). Python only remembers it here - its body runs later, each time predict_plot() is called.
66
vals = [float(input("Rainfall (mm)        : ")), float(input("Temperature (C)      : ")), float(input("Fertiliser (kg/ha)   : ")), int(input("Irrigated (1/0)โ€ฆ
โŒจ๏ธ Input Stores a list [float(input("Rainfall (mm) : ")), float(inpuโ€ฆ in variable vals
67
soil = input("Soil (poor/average/good): ").strip().lower()
โŒจ๏ธ Input Reads the typed text, changes its case with .lower() and stores it in variable soil
68
if soil not in ("poor", "average", "good"):
๐Ÿ”€ Decision CHECKS whether soil is not present in ("poor", "average", "good"). If True, the indented lines below run; otherwise they are skipped
69
print("Soil must be poor/average/good.")
๐Ÿ–ฅ๏ธ Output Displays the text "Soil must be poor/average/good." on the screen
70
return
๐Ÿงฉ Function Ends the function and goes back to the caller
71
row = dict(zip(["Rain_mm", "Temp_C", "Fert_kg", "Irrigated"], vals))
๐Ÿงฎ Store / Calculate Makes a dictionary; the result is stored in variable row
72
row.update({"Soil_average": int(soil == "average"), "Soil_good": int(soil == "good"), "Soil_poor": int(soil == "poor")})
๐Ÿงฎ Store / Calculate Updates row with {"Soil_average": int(soil == "average"), "Soiโ€ฆ
73
y = state["model"].predict(pd.DataFrame([row])[state["X"].columns])[0]
๐Ÿ“ฆ Library / Data Stores the item state["model"].predict(pd.DataFrame([row])[stโ€ฆ in variable y
74
print(f"STEP 9 Deployment: predicted yield {y:.1f} quintal/ha -> about {y * 2.47:.0f} quintal per 2.47 acres")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"STEP 9 Deployment: predicted yield {y:.1f} โ€ฆ with the values filled into { } on the screen
what_if() - lines 77โ€“87
LineCodeWhat it does
77
def what_if():
๐Ÿงฉ Function DEFINES a function what_if(). Python only remembers it here - its body runs later, each time what_if() is called.
78
base = state["X"].median().to_dict()
๐Ÿงฎ Store / Calculate Converts state["X"].median() into a dictionary; the result is stored in variable base
79
base.update({"Irrigated": 1, "Soil_average": 1, "Soil_good": 0, "Soil_poor": 0})
๐Ÿงฎ Store / Calculate Updates base with {"Irrigated": 1, "Soil_average": 1, "Soil_gooโ€ฆ
80
res = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable res
81
for f in range(40, 200, 20):
๐Ÿ” Loop LOOP: gives the numbers from 40 up to (not including) 200, jumping by 20; for each number, f takes that value and the indented block runs once
82
base["Fert_kg"] = f
๐Ÿงฎ Store / Calculate Puts the value of f into base["Fert_kg"] (item "Fert_kg" of base)
83
res.append((f, state["model"].predict(pd.DataFrame([base])[state["X"].columns])[0]))
๐Ÿ“ฆ Library / Data Adds (f, state["model"].predict(pd.DataFrame([baseโ€ฆ at the end of list res
84
print(f"  fertiliser {f:>3} kg/ha -> yield {res[-1][1]:.1f}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f" fertiliser {f:>3} kg/ha -> yield {res[-1][โ€ฆ with the values filled into { } on the screen
85
bf = max(res, key=lambda r: r[1])
๐Ÿงฎ Store / Calculate Finds the largest value among res; the result is stored in variable bf
86
print(f"Best fertiliser dose about {bf[0]} kg/ha; more than this does not help (diminishing returns).")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Best fertiliser dose about {bf[0]} kg/ha; mโ€ฆ with the values filled into { } on the screen
87
return res
๐Ÿงฉ Function Sends back (returns) the value of res to the line that called the function
feedback() - lines 90โ€“92
LineCodeWhat it does
90
def feedback():
๐Ÿงฉ Function DEFINES a function feedback(). Python only remembers it here - its body runs later, each time feedback() is called.
91
print("STEP 10 Feedback: after harvest, record actual yield of each plot,")
๐Ÿ–ฅ๏ธ Output Displays the text "STEP 10 Feedback: after harvest, โ€ฆ" on the screen
92
print("        compare with prediction, add the new data and retrain every season.")
๐Ÿ–ฅ๏ธ Output Displays the text "compare with prediction, add the โ€ฆ" on the screen
charts() - lines 95โ€“107
LineCodeWhat it does
95
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
96
m = state["model"]
๐Ÿงฎ Store / Calculate Stores the item state["model"] in variable m
97
imp = pd.Series(getattr(m, "feature_importances_", np.abs(getattr(m, "coef_", np.zeros(7)))), index=state["X"].columns).sort_values()
๐Ÿ“ฆ Library / Data Sorts pd.Series(getattr(m, "feature_importances_", โ€ฆ by ; the result is stored in variable imp
98
imp.plot(kind="barh", color="seagreen", figsize=(6, 3.5)); plt.title(f"Feature importance ({state['best']})")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
98
imp.plot(kind="barh", color="seagreen", figsize=(6, 3.5)); plt.title(f"Feature importance ({state['best']})")
๐Ÿ–ฅ๏ธ Output Writes f"Feature importance ({state['best']})" as the title of the chart
99
plt.tight_layout(); plt.savefig("yield_importance.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
99
plt.tight_layout(); plt.savefig("yield_importance.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "yield_importance.png"
99
plt.tight_layout(); plt.savefig("yield_importance.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
100
y_te, p = state["test"]
๐Ÿงฎ Store / Calculate Stores the item state["test"] in variables y_te, p
101
plt.scatter(y_te, p, c="#e67700"); plt.plot([y_te.min(), y_te.max()], [y_te.min(), y_te.max()], "k--")
๐Ÿ–ฅ๏ธ Output Draws a scatter chart (dots) of y_te, p
101
plt.scatter(y_te, p, c="#e67700"); plt.plot([y_te.min(), y_te.max()], [y_te.min(), y_te.max()], "k--")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [y_te.min(), y_te.max()], [y_te.min(), y_te.max()], "k--"
102
plt.xlabel("Actual yield"); plt.ylabel("Predicted"); plt.title("Hold-out: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes "Actual yield" as the label of the X-axis
102
plt.xlabel("Actual yield"); plt.ylabel("Predicted"); plt.title("Hold-out: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes "Predicted" as the label of the Y-axis
102
plt.xlabel("Actual yield"); plt.ylabel("Predicted"); plt.title("Hold-out: actual vs predicted")
๐Ÿ–ฅ๏ธ Output Writes "Hold-out: actual vs predicted" as the title of the chart
103
plt.savefig("yield_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "yield_pred.png"
103
plt.savefig("yield_pred.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
104
res = what_if()
๐Ÿงฎ Store / Calculate Calls our own function what_if(); the result is stored in variable res
105
plt.plot([r[0] for r in res], [r[1] for r in res], "o-"); plt.xlabel("Fertiliser kg/ha"); plt.ylabel("Predicted yield"); plt.title("Fertiliser what-if")
๐Ÿ–ฅ๏ธ Output Draws a line chart of [r[0] for r in res], [r[1] for r in res], "o-"
105
plt.plot([r[0] for r in res], [r[1] for r in res], "o-"); plt.xlabel("Fertiliser kg/ha"); plt.ylabel("Predicted yield"); plt.title("Fertiliser what-if")
๐Ÿ–ฅ๏ธ Output Writes "Fertiliser kg/ha" as the label of the X-axis
105
plt.plot([r[0] for r in res], [r[1] for r in res], "o-"); plt.xlabel("Fertiliser kg/ha"); plt.ylabel("Predicted yield"); plt.title("Fertiliser what-if")
๐Ÿ–ฅ๏ธ Output Writes "Predicted yield" as the label of the Y-axis
105
plt.plot([r[0] for r in res], [r[1] for r in res], "o-"); plt.xlabel("Fertiliser kg/ha"); plt.ylabel("Predicted yield"); plt.title("Fertiliser what-if")
๐Ÿ–ฅ๏ธ Output Writes "Fertiliser what-if" as the title of the chart
106
plt.savefig("yield_fert.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "yield_fert.png"
106
plt.savefig("yield_fert.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
107
print("Charts saved: yield_importance.png, yield_pred.png, yield_fert.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: yield_importance.pnโ€ฆ" on the screen
Q1. Name the steps of the Data Science Methodology.

Business understanding, analytic approach, data requirements, collection, understanding, preparation, modeling, evaluation, deployment, feedback.

Q2. Why one-hot encode soil?

Models need numbers; one-hot creates a 0/1 column for each soil type without implying order.

Q3. Why median imputation for rainfall?

Median is robust to extreme rainfall values.

Q4. Why did Random Forest perform better?

It captures non-linear effects such as too much fertiliser reducing yield.

Q5. What is feedback in the methodology?

Comparing predictions with actual harvests and retraining the model.

10

Student Dropout Early-Warning System with Data Story (SDG 4)

PYTHON + SKLEARNSDG 4 - Quality EducationDecision Tree classifierclass imbalance (class_weight)recall for at-risk studentsfeature importancedata storytelling
๐Ÿ“ 119 lines of codeโ˜ฐ 9 menu options๐Ÿ–ฅ๏ธ 103 output lines๐Ÿ“„ 25+ page report

Predicts which students are at risk of dropping out from attendance, marks trend, distance from school, mid-day-meal participation and family income using a Decision Tree, prints the learnt rules and tells a short data story with a chart for the school management committee.

โœจ Features
  • 500 simulated student records: attendance, change in marks, distance, mid-day meal, family income
  • Decision tree (depth 3, balanced classes) as an early-warning model
  • Recall-focused evaluation (catch at-risk students) and learnt rules in plain text
  • Risk check for an individual student with reasons
  • Data story: setup, insight, action with three charts
  • Class-level list of top-10 highest-risk students for counselling
โ˜ฐ Main menu
1Data OverviewRecords and at-risk share
2Train ModelDecision tree
3EvaluateConfusion matrix, recall, precision
4Learnt Rulesexport_text
5Check a StudentRisk and reasons
6Top-10 Risk ListHighest probabilities
7Data StorySetup -> insight -> action
8Charts3 charts
0ExitEnds program
๐ŸŽฏ Objectives
  • Build an interpretable Decision Tree for an imbalanced classification problem
  • Evaluate with recall and precision for the at-risk class and read the tree rules
  • Communicate the findings as a data story with a supporting chart
๐Ÿ“š Data dictionary
NameTypePurpose
dfDataFrameAttendance, Marks_change, Distance_km, MDM_meals, Income_k, Dropout
treeDecisionTreeClassifierEarly-warning model
featureslistModel inputs
rateSeriesDropout % by attendance band
Why it matters: Combines Unit 2 (methodology & evaluation) and Unit 8 (data storytelling) in a socially meaningful capstone.
# =====================================================================
#   STUDENT DROPOUT EARLY-WARNING SYSTEM WITH DATA STORY  (SDG 4)
# =====================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import train_test_split
from sklearn.metrics import recall_score, precision_score, confusion_matrix

rng = np.random.default_rng(12)
n = 500
df = pd.DataFrame({"Attendance": rng.normal(84, 10, n).clip(35, 100).round(), "Marks_change": rng.normal(0, 8, n).round(1),
                   "Distance_km": rng.exponential(3, n).round(1), "MDM_meals": rng.integers(0, 2, n),
                   "Income_k": rng.normal(15, 6, n).clip(3).round(1)})
risk = (-0.12 * (df.Attendance - 84) - 0.08 * df.Marks_change + 0.15 * df.Distance_km - 0.8 * df.MDM_meals - 0.05 * df.Income_k + rng.normal(0, 0.8, n))
df["Dropout"] = (risk > np.quantile(risk, 0.85)).astype(int)
df.insert(0, "Student", [f"S{i:03d}" for i in range(1, n + 1)])
features = ["Attendance", "Marks_change", "Distance_km", "MDM_meals", "Income_k"]
X_tr, X_te, y_tr, y_te = train_test_split(df[features], df.Dropout, test_size=0.25, random_state=3, stratify=df.Dropout)
df["Band"] = pd.cut(df.Attendance, [0, 70, 80, 90, 100], labels=["<70", "70-80", "80-90", "90+"])
state = {}


def overview():
    print("Students:", n, "| at-risk share:", round(df.Dropout.mean() * 100, 1), "%")
    print(df.groupby("Dropout")[features].mean().round(1).rename(index={0: "Not at risk", 1: "At risk"}))


def train():
    state["tree"] = DecisionTreeClassifier(max_depth=3, class_weight="balanced", random_state=0).fit(X_tr, y_tr)
    print("Decision tree trained (depth 3, balanced classes) on", len(y_tr), "students.")


def evaluate():
    p = state["tree"].predict(X_te)
    print("Confusion matrix [[TN FP] [FN TP]]:\n", confusion_matrix(y_te, p))
    print("Recall (at-risk caught)   :", round(recall_score(y_te, p), 3))
    print("Precision (alerts correct):", round(precision_score(y_te, p), 3))


def rules():
    print(export_text(state["tree"], feature_names=features, decimals=1))


def check():
    vals = [float(input("Attendance %         : ")), float(input("Change in marks      : ")), float(input("Distance to school km: ")),
            int(input("Gets mid-day meal 1/0: ")), float(input("Family income (k/mo) : "))]
    p = state["tree"].predict_proba(pd.DataFrame([vals], columns=features))[0][1]
    print(f"Risk probability: {p:.2f} -> {'HIGH RISK' if p >= 0.5 else 'LOW RISK'}")
    reasons = []
    if vals[0] < 75: reasons.append("low attendance")
    if vals[1] < -5: reasons.append("falling marks")
    if vals[2] > 5: reasons.append("lives far from school")
    if vals[3] == 0: reasons.append("not taking mid-day meals")
    if vals[4] < 8: reasons.append("low family income")
    if reasons:
        print("Warning signs:", ", ".join(reasons))
    if p >= 0.5:
        print("Action: call parents, remedial classes, check transport / scholarship support.")


def top10():
    df["Risk_prob"] = state["tree"].predict_proba(df[features])[:, 1].round(2)
    print(df.sort_values(["Risk_prob", "Attendance"], ascending=[False, True]).head(10)[["Student"] + features + ["Risk_prob"]].to_string(index=False))


def story():
    rate = df.groupby("Band", observed=True).Dropout.mean() * 100
    meal = df.groupby("MDM_meals").Dropout.mean() * 100
    print("SETUP   : 1 in", round(1 / df.Dropout.mean()), "students in our data is at risk of dropping out.")
    print("INSIGHT : risk is", round(rate.iloc[0]), "% when attendance is below 70 %, but only", round(rate.iloc[-1]), "% above 90 %.")
    print("          Mid-day meal takers: risk", round(meal[1]), "% vs", round(meal[0]), "% for others.")
    print("ACTION  : weekly attendance follow-up, remedial classes when marks fall,")
    print("          ensure every eligible child receives mid-day meals.")


def charts():
    rate = df.groupby("Band", observed=True).Dropout.mean() * 100
    rate.plot(kind="bar", color=["#e03131", "#f08c00", "#fab005", "#2b8a3e"], figsize=(6, 3.8))
    plt.ylabel("Students at risk (%)"); plt.xlabel("Attendance band (%)"); plt.title("Low attendance is the strongest warning sign"); plt.xticks(rotation=0)
    plt.tight_layout(); plt.savefig("dropout_story.png", dpi=90); plt.show()
    pd.Series(state["tree"].feature_importances_, index=features).sort_values().plot(kind="barh", color="#5f3dc4", title="What the model looks at")
    plt.savefig("dropout_importance.png", dpi=90, bbox_inches="tight"); plt.show()
    (df.groupby("MDM_meals").Dropout.mean() * 100).rename({0: "No meal", 1: "Mid-day meal"}).plot(kind="bar", color=["#fa5252", "#40c057"], title="Risk % by mid-day meal")
    plt.xticks(rotation=0); plt.savefig("dropout_meals.png", dpi=90, bbox_inches="tight"); plt.show()
    print("Charts saved: dropout_story.png, dropout_importance.png, dropout_meals.png")


print("=" * 60)
print("   DROPOUT EARLY-WARNING SYSTEM  (SDG 4)")
print("=" * 60)
while True:
    print("\n1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit")
    ch = input("Enter choice: ")
    if ch == "0":
        print("Every child in school!")
        break
    elif ch == "1":
        overview()
    elif ch == "2":
        train()
    elif ch == "7":
        story()
    elif "tree" not in state and ch in "34568":
        print("Train the model first (option 2).")
    elif ch == "3":
        evaluate()
    elif ch == "4":
        rules()
    elif ch == "5":
        check()
    elif ch == "6":
        top10()
    elif ch == "8":
        charts()
    else:
        print("Invalid choice")

        
  1. Start
  2. Create student data
  3. Show menu and read choice
  4. Model trained? → No: train first
  5. Read student details
  6. Predict risk probability
  7. Probability >= 0.5? → No: LOW risk
  8. HIGH risk + reasons + action
  9. Choice is 0? → No: show menu
  10. Stop
#Test case / inputExpected resultStatus
1Overview500 students, 15 % at riskPASS
2EvaluateRecall highPASS
3RulesAttendance first splitPASS
4Student 62 %, -10, 8 km, no meal, 6kHIGH riskPASS
5Student 95 %, +5, 1 km, meal, 20kLOW riskPASS
6Top-10List of studentsPASS
7Story3-part storyPASS
โš  Limitations
  • Simulated data
  • Model may stigmatise - use only for support
  • Few features
  • Needs regular updating
๐Ÿš€ Future scope
  • Use UDISE+ / school records with consent
  • SMS alerts to class teachers
  • Counsellor dashboard
  • Fairness audit across gender / caste groups

When you type python project.py, Python reads the file from top to bottom. Function definitions are only remembered on the way; real work starts at the main program at the bottom, which then calls the functions.

โ‘  Order of execution
  1. Imports (line 4): numpy - fast arrays and maths, pandas - data tables (Series & DataFrame), matplotlib.pyplot - drawing charts, DecisionTreeClassifier, export_text, train_test_split, recall_score, precision_score, confusion_matrix are loaded.
  2. Global variables / constants are created: rng, n, df, risk, features, state.
  3. 8 functions are defined (lines 25โ€“87) - Python stores them but does NOT run them yet.
  4. Main program starts at line 17: df["Dropout"] = (risk > np.quantile(risk, 0.85)).astype(int) - a while True menu loop keeps showing the menu, reads your choice and calls the matching function, until you choose Exit (break).
โ‘ก The functions and their jobs
FunctionLinesWhat it doesCalled from
overview()25โ€“27Overviewmain program
train()30โ€“32Trainmain program
evaluate()35โ€“39Evaluatemain program
rules()42โ€“43Rulesmain program
check()46โ€“60Checkmain program
top10()63โ€“65Top10main program
story()68โ€“75Storymain program
charts()78โ€“87Chartsmain program
โ‘ข Main program - line by line
LineCodeWhat it does
17
df["Dropout"] = (risk > np.quantile(risk, 0.85)).astype(int)
๐Ÿ“ฆ Library / Data Changes the data type of risk > np.quantile(risk, 0.85) to int; the result is put into df["Dropout"] (item "Dropout" of df)
18
df.insert(0, "Student", [f"S{i:03d}" for i in range(1, n + 1)])
๐Ÿ“ฆ Library / Data Inserts "Student" at position 0 in df
19
features = ["Attendance", "Marks_change", "Distance_km", "MDM_meals", "Income_k"]
๐Ÿงฎ Store / Calculate Stores a list ["Attendance", "Marks_change", "Distance_km",โ€ฆ in variable features
20
X_tr, X_te, y_tr, y_te = train_test_split(df[features], df.Dropout, test_size=0.25, random_state=3, stratify=df.Dropout)
๐Ÿ“ฆ Library / Data Splits the data into training and testing parts (25% for testing) and stores them in X_tr, X_te, y_tr, y_te
21
df["Band"] = pd.cut(df.Attendance, [0, 70, 80, 90, 100], labels=["<70", "70-80", "80-90", "90+"])
๐Ÿ“ฆ Library / Data Divides the values into bins / categories; the result is put into df["Band"] (item "Band" of df)
22
state = {}
๐Ÿงฎ Store / Calculate Stores an empty dictionary {} in variable state
90
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
91
print("   DROPOUT EARLY-WARNING SYSTEM  (SDG 4)")
๐Ÿ–ฅ๏ธ Output Displays the text "DROPOUT EARLY-WARNING SYSTEM (SDGโ€ฆ" on the screen
92
print("=" * 60)
๐Ÿ–ฅ๏ธ Output Displays a line of 60 "=" signs on the screen
93
while True:
๐Ÿ” Loop INFINITE LOOP (while True): the block repeats again and again until a break statement stops it
94
print("\n1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit")
๐Ÿ–ฅ๏ธ Output Displays the text "1.Overview 2.Train 3.Evaluate 4.Rโ€ฆ" on the screen
95
ch = input("Enter choice: ")
โŒจ๏ธ Input Shows the message "Enter choice: " and waits; whatever the user types comes back as TEXT (string); it is stored in variable ch
96
if ch == "0":
๐Ÿ”€ Decision CHECKS whether ch is equal to "0". If True, the indented lines below run; otherwise Python jumps to the elif/else part
97
print("Every child in school!")
๐Ÿ–ฅ๏ธ Output Displays the text "Every child in school!" on the screen
98
break
๐Ÿ” Loop BREAK - leaves the loop immediately
99
elif ch == "1":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "1"
100
overview()
๐Ÿงฎ Store / Calculate Calls our own function overview()
101
elif ch == "2":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "2"
102
train()
๐Ÿงฎ Store / Calculate Calls our own function train()
103
elif ch == "7":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "7"
104
story()
๐Ÿงฎ Store / Calculate Calls our own function story()
105
elif "tree" not in state and ch in "34568":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ("tree" is not present in state AND ch is present in "34568")
106
print("Train the model first (option 2).")
๐Ÿ–ฅ๏ธ Output Displays the text "Train the model first (option 2)." on the screen
107
elif ch == "3":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "3"
108
evaluate()
๐Ÿงฎ Store / Calculate Calls our own function evaluate()
109
elif ch == "4":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "4"
110
rules()
๐Ÿงฎ Store / Calculate Calls our own function rules()
111
elif ch == "5":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "5"
112
check()
๐Ÿงฎ Store / Calculate Calls our own function check()
113
elif ch == "6":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "6"
114
top10()
๐Ÿงฎ Store / Calculate Calls our own function top10()
115
elif ch == "8":
๐Ÿ”€ Decision ELIF: checked only when the conditions above were False - checks whether ch is equal to "8"
116
charts()
๐Ÿงฎ Store / Calculate Calls our own function charts()
117
else:
๐Ÿ”€ Decision ELSE: runs only when all the conditions above are False
118
print("Invalid choice")
๐Ÿ–ฅ๏ธ Output Displays the text "Invalid choice" on the screen
โ‘ฃ Walk-through of the sample run

Made by really running the project with the inputs shown in the Live Output tab. It shows what you type โ†’ which function runs โ†’ what appears.

  1. โ–ถ Program starts
    shows: DROPOUT EARLY-WARNING SYSTEM (SDG 4) (+1 more lines)
  2. You type 3 at Enter choice:
    shows: Train the model first (option 2). (+1 more lines)
  3. You type 1 at Enter choice:
    runs: overview()
    shows: Students: 500 | at-risk share: 15.0 % (+5 more lines)
  4. You type 2 at Enter choice:
    runs: train()
    shows: Decision tree trained (depth 3, balanced classes) on 375 students. (+1 more lines)
  5. You type 3 at Enter choice:
    runs: evaluate()
    shows: Confusion matrix [[TN FP] [FN TP]]: (+5 more lines)
  6. You type 4 at Enter choice:
    runs: rules()
    shows: |--- Attendance <= 77.5 (+22 more lines)
  7. You type 5 at Enter choice:
    runs: check()
  8. You type 62 at Attendance % :
  9. You type -10 at Change in marks :
  10. You type 8 at Distance to school km:
  11. You type 0 at Gets mid-day meal 1/0:
  12. You type 6 at Family income (k/mo) :
    shows: Risk probability: 0.94 -> HIGH RISK (+3 more lines)
  13. You type 5 at Enter choice:
    runs: check()
  14. You type 95 at Attendance % :
  15. You type 5 at Change in marks :
  16. You type 1 at Distance to school km:
  17. You type 1 at Gets mid-day meal 1/0:
  18. You type 20 at Family income (k/mo) :
    shows: Risk probability: 0.03 -> LOW RISK (+1 more lines)
  19. You type 6 at Enter choice:
    runs: top10()
    shows: Student Attendance Marks_change Distance_km MDM_meals Income_k Risk_prob (+11 more lines)
  20. You type 7 at Enter choice:
    runs: story()
    shows: SETUP : 1 in 7 students in our data is at risk of dropping out. (+5 more lines)
  21. You type 8 at Enter choice:
    runs: charts()
    shows: [chart is drawn] (+4 more lines)
  22. You type 0 at Enter choice:
    shows: Every child in school!
โ‘ค Inside each function - line by line
overview() - lines 25โ€“27
LineCodeWhat it does
25
def overview():
๐Ÿงฉ Function DEFINES a function overview(). Python only remembers it here - its body runs later, each time overview() is called.
26
print("Students:", n, "| at-risk share:", round(df.Dropout.mean() * 100, 1), "%")
๐Ÿ–ฅ๏ธ Output Displays the text "Students:", then the value of n, then the text "| at-risk share:", then the value of round(df.Dropout.mean() * 100, 1), then the text "%" on the screen
27
print(df.groupby("Dropout")[features].mean().round(1).rename(index={0: "Not at risk", 1: "At risk"}))
๐Ÿ–ฅ๏ธ Output Displays the value of df.groupby("Dropout")[features].mean().round(โ€ฆ on the screen
train() - lines 30โ€“32
LineCodeWhat it does
30
def train():
๐Ÿงฉ Function DEFINES a function train(). Python only remembers it here - its body runs later, each time train() is called.
31
state["tree"] = DecisionTreeClassifier(max_depth=3, class_weight="balanced", random_state=0).fit(X_tr, y_tr)
๐Ÿ“ฆ Library / Data Trains (fits) the model DecisionTreeClassifier(max_depth=3, class_weiโ€ฆ on the given data; the result is put into state["tree"] (item "tree" of state)
32
print("Decision tree trained (depth 3, balanced classes) on", len(y_tr), "students.")
๐Ÿ–ฅ๏ธ Output Displays the text "Decision tree trained (depth 3, bโ€ฆ", then the value of len(y_tr), then the text "students." on the screen
evaluate() - lines 35โ€“39
LineCodeWhat it does
35
def evaluate():
๐Ÿงฉ Function DEFINES a function evaluate(). Python only remembers it here - its body runs later, each time evaluate() is called.
36
p = state["tree"].predict(X_te)
๐Ÿ“ฆ Library / Data Uses the trained model state["tree"] to predict answers for X_te; the result is stored in variable p
37
print("Confusion matrix [[TN FP] [FN TP]]:\n", confusion_matrix(y_te, p))
๐Ÿ–ฅ๏ธ Output Displays the text "Confusion matrix [[TN FP] [FN TP]โ€ฆ", then the value of confusion_matrix(y_te, p) on the screen
38
print("Recall (at-risk caught)   :", round(recall_score(y_te, p), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Recall (at-risk caught) :", then the value of round(recall_score(y_te, p), 3) on the screen
39
print("Precision (alerts correct):", round(precision_score(y_te, p), 3))
๐Ÿ–ฅ๏ธ Output Displays the text "Precision (alerts correct):", then the value of round(precision_score(y_te, p), 3) on the screen
rules() - lines 42โ€“43
LineCodeWhat it does
42
def rules():
๐Ÿงฉ Function DEFINES a function rules(). Python only remembers it here - its body runs later, each time rules() is called.
43
print(export_text(state["tree"], feature_names=features, decimals=1))
๐Ÿ–ฅ๏ธ Output Displays the value of export_text(state["tree"], feature_names=featโ€ฆ on the screen
check() - lines 46โ€“60
LineCodeWhat it does
46
def check():
๐Ÿงฉ Function DEFINES a function check(). Python only remembers it here - its body runs later, each time check() is called.
47
vals = [float(input("Attendance %         : ")), float(input("Change in marks      : ")), float(input("Distance to school km: ")),
        int(input("Gets miโ€ฆ
โŒจ๏ธ Input Stores a list [float(input("Attendance % : ")), float(inputโ€ฆ in variable vals
49
p = state["tree"].predict_proba(pd.DataFrame([vals], columns=features))[0][1]
๐Ÿ“ฆ Library / Data Stores the item state["tree"].predict_proba(pd.DataFrame([valโ€ฆ in variable p
50
print(f"Risk probability: {p:.2f} -> {'HIGH RISK' if p >= 0.5 else 'LOW RISK'}")
๐Ÿ–ฅ๏ธ Output Displays the f-string f"Risk probability: {p:.2f} -> {'HIGH RISK' iโ€ฆ with the values filled into { } on the screen
51
reasons = []
๐Ÿงฎ Store / Calculate Stores an empty list [] in variable reasons
52
if vals[0] < 75: reasons.append("low attendance")
๐Ÿ”€ Decision CHECKS whether vals[0] is less than 75. If True, the indented lines below run; otherwise they are skipped โ†’ here: adds "low attendance" at the end of list reasons
53
if vals[1] < -5: reasons.append("falling marks")
๐Ÿ”€ Decision CHECKS whether vals[1] is less than -5. If True, the indented lines below run; otherwise they are skipped โ†’ here: adds "falling marks" at the end of list reasons
54
if vals[2] > 5: reasons.append("lives far from school")
๐Ÿ”€ Decision CHECKS whether vals[2] is greater than 5. If True, the indented lines below run; otherwise they are skipped โ†’ here: adds "lives far from school" at the end of list reasons
55
if vals[3] == 0: reasons.append("not taking mid-day meals")
๐Ÿ”€ Decision CHECKS whether vals[3] is equal to 0. If True, the indented lines below run; otherwise they are skipped โ†’ here: adds "not taking mid-day meals" at the end of list reasons
56
if vals[4] < 8: reasons.append("low family income")
๐Ÿ”€ Decision CHECKS whether vals[4] is less than 8. If True, the indented lines below run; otherwise they are skipped โ†’ here: adds "low family income" at the end of list reasons
57
if reasons:
๐Ÿ”€ Decision CHECKS whether reasons is True (not empty / not zero). If True, the indented lines below run; otherwise they are skipped
58
print("Warning signs:", ", ".join(reasons))
๐Ÿ–ฅ๏ธ Output Displays the text "Warning signs:", then the value of ", ".join(reasons) on the screen
59
if p >= 0.5:
๐Ÿ”€ Decision CHECKS whether p is greater than or equal to 0.5. If True, the indented lines below run; otherwise they are skipped
60
print("Action: call parents, remedial classes, check transport / scholarship support.")
๐Ÿ–ฅ๏ธ Output Displays the text "Action: call parents, remedial clโ€ฆ" on the screen
top10() - lines 63โ€“65
LineCodeWhat it does
63
def top10():
๐Ÿงฉ Function DEFINES a function top10(). Python only remembers it here - its body runs later, each time top10() is called.
64
df["Risk_prob"] = state["tree"].predict_proba(df[features])[:, 1].round(2)
๐Ÿงฎ Store / Calculate Rounds the values of state["tree"].predict_proba(df[features])[:, โ€ฆ to 2 decimal places; the result is put into df["Risk_prob"] (item "Risk_prob" of df)
65
print(df.sort_values(["Risk_prob", "Attendance"], ascending=[False, True]).head(10)[["Student"] + features + ["Risk_prob"]].to_string(index=False))
๐Ÿ–ฅ๏ธ Output Displays the value of df.sort_values(["Risk_prob", "Attendance"], aโ€ฆ on the screen
story() - lines 68โ€“75
LineCodeWhat it does
68
def story():
๐Ÿงฉ Function DEFINES a function story(). Python only remembers it here - its body runs later, each time story() is called.
69
rate = df.groupby("Band", observed=True).Dropout.mean() * 100
๐Ÿ“ฆ Library / Data Stores the value of df.groupby("Band", observed=True).Dropout.meaโ€ฆ (calculated using ร—) in variable rate
70
meal = df.groupby("MDM_meals").Dropout.mean() * 100
๐Ÿ“ฆ Library / Data Stores the value of df.groupby("MDM_meals").Dropout.mean() * 100 (calculated using ร—) in variable meal
71
print("SETUP   : 1 in", round(1 / df.Dropout.mean()), "students in our data is at risk of dropping out.")
๐Ÿ–ฅ๏ธ Output Displays the text "SETUP : 1 in", then the value of round(1 / df.Dropout.mean()), then the text "students in our data is at risk oโ€ฆ" on the screen
72
print("INSIGHT : risk is", round(rate.iloc[0]), "% when attendance is below 70 %, but only", round(rate.iloc[-1]), "% above 90 %.")
๐Ÿ–ฅ๏ธ Output Displays the text "INSIGHT : risk is", then the value of round(rate.iloc[0]), then the text "% when attendance is below 70 %, โ€ฆ", then the value of round(rate.iloc[-1]), then the text "% above 90 %." on the screen
73
print("          Mid-day meal takers: risk", round(meal[1]), "% vs", round(meal[0]), "% for others.")
๐Ÿ–ฅ๏ธ Output Displays the text "Mid-day meal takers: risk", then the value of round(meal[1]), then the text "% vs", then the value of round(meal[0]), then the text "% for others." on the screen
74
print("ACTION  : weekly attendance follow-up, remedial classes when marks fall,")
๐Ÿ–ฅ๏ธ Output Displays the text "ACTION : weekly attendance followโ€ฆ" on the screen
75
print("          ensure every eligible child receives mid-day meals.")
๐Ÿ–ฅ๏ธ Output Displays the text "ensure every eligible child receiโ€ฆ" on the screen
charts() - lines 78โ€“87
LineCodeWhat it does
78
def charts():
๐Ÿงฉ Function DEFINES a function charts(). Python only remembers it here - its body runs later, each time charts() is called.
79
rate = df.groupby("Band", observed=True).Dropout.mean() * 100
๐Ÿ“ฆ Library / Data Stores the value of df.groupby("Band", observed=True).Dropout.meaโ€ฆ (calculated using ร—) in variable rate
80
rate.plot(kind="bar", color=["#e03131", "#f08c00", "#fab005", "#2b8a3e"], figsize=(6, 3.8))
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
81
plt.ylabel("Students at risk (%)"); plt.xlabel("Attendance band (%)"); plt.title("Low attendance is the strongest warning sign"); plt.xticks(rotation=0)
๐Ÿ–ฅ๏ธ Output Writes "Students at risk (%)" as the label of the Y-axis
81
plt.ylabel("Students at risk (%)"); plt.xlabel("Attendance band (%)"); plt.title("Low attendance is the strongest warning sign"); plt.xticks(rotation=0)
๐Ÿ–ฅ๏ธ Output Writes "Attendance band (%)" as the label of the X-axis
81
plt.ylabel("Students at risk (%)"); plt.xlabel("Attendance band (%)"); plt.title("Low attendance is the strongest warning sign"); plt.xticks(rotation=0)
๐Ÿ–ฅ๏ธ Output Writes "Low attendance is the strongest warning sign" as the title of the chart
81
plt.ylabel("Students at risk (%)"); plt.xlabel("Attendance band (%)"); plt.title("Low attendance is the strongest warning sign"); plt.xticks(rotation=0)
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
82
plt.tight_layout(); plt.savefig("dropout_story.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Adjusts spacing so labels do not overlap
82
plt.tight_layout(); plt.savefig("dropout_story.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "dropout_story.png"
82
plt.tight_layout(); plt.savefig("dropout_story.png", dpi=90); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
83
pd.Series(state["tree"].feature_importances_, index=features).sort_values().plot(kind="barh", color="#5f3dc4", title="What the model looks at")
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
84
plt.savefig("dropout_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "dropout_importance.png"
84
plt.savefig("dropout_importance.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
85
(df.groupby("MDM_meals").Dropout.mean() * 100).rename({0: "No meal", 1: "Mid-day meal"}).plot(kind="bar", color=["#fa5252", "#40c057"], title="Risk % by mid-โ€ฆ
๐Ÿ–ฅ๏ธ Output Draws a line chart of the given values
86
plt.xticks(rotation=0); plt.savefig("dropout_meals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Sets the marks/labels on the X-axis
86
plt.xticks(rotation=0); plt.savefig("dropout_meals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Saves the chart as an image file "dropout_meals.png"
86
plt.xticks(rotation=0); plt.savefig("dropout_meals.png", dpi=90, bbox_inches="tight"); plt.show()
๐Ÿ–ฅ๏ธ Output Displays the chart window
87
print("Charts saved: dropout_story.png, dropout_importance.png, dropout_meals.png")
๐Ÿ–ฅ๏ธ Output Displays the text "Charts saved: dropout_story.png, โ€ฆ" on the screen
Q1. Why focus on recall?

Missing an at-risk student (FN) is worse than an extra counselling call (FP).

Q2. What does class_weight='balanced' do?

Gives more weight to the rare at-risk class so the model does not ignore it.

Q3. Why a decision tree?

Its rules are easy to explain to teachers and parents.

Q4. What is data storytelling?

Presenting data as setup, insight and action with clear visuals so people act on it.

Q5. Which SDG?

SDG 4 - Quality Education.