๐ 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
- 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
- Q2 Introduction to Python Programming Language โ history, installation, features of Python & various Python interpreters. THEORY
- Q3 Write a python program to Input a welcome message and display it. PYTHON
- Q4 Write a python program to Input two numbers and display the larger / smaller number. PYTHON
- Q5 Write a python program to Input three numbers and display the largest / smallest number. PYTHON
- Q6 Write a python program to input two integers x and n, compute xโฟ. PYTHON
- Q7 Write a python program to Generate number/star patterns using nested loop. PYTHON
- 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
- Q9 Write a python program to determine whether a number is a Perfect number, an Armstrong number or a Palindrome. PYTHON
- Q10 Write a python program to Input a number and check if the number is Prime or Composite. PYTHON
- Q11 Write a Python Program to print Fibonacci series up to the entered n positive number. PYTHON
- Q12 Write a Python Program to Compute GCD/HCF and LCM of two Integers. PYTHON
- Q13 Write a Python Program to Count and display the number of vowels, consonants, uppercase, lowercase characters in a string. PYTHON
- 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
- Q15 Write a Python Program to find the largest/smallest number in a list/tuple and display the position of that number. PYTHON
- 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
- Q17 Write a Python Program to Input a list/tuple of elements, search for a given element and display its frequency and position. PYTHON
- 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
- 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
- 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
- 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
- Q22 Write a Python Program to Create a hotel dictionary (bookingid, clientname, date, roomno) and delete a value based on bookingid. PYTHON
- 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
- Q24 Write a Python program to implement the random function random(), randint(), randrange() using the random module. PYTHON
- Q25 Write a Python program to implement statistics functions (mean, median, mode) using the statistics module. PYTHON
- Q26 Write a python program to find the factorial of a positive number. PYTHON
- Q27 Write a python program to find the absolute value of a number (without and with abs()). PYTHON
- Q28 Write a python program to check whether a number is divisible by another number. PYTHON
- 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
- Q1 Introduction to Computer Systems (CPU, Input devices, Output devices, Memory, Hardware & Software etc.) THEORY
- Q2 Introduction to Python (History of Python, Python Modes, Python Software etc.) THEORY
- Q3 Write a python program to design a calculator (+, -, *, /, %, //). PYTHON
- Q4 Write a Python program to calculate perimeter/circumference and area of shapes: triangle, rectangle, square, circle. PYTHON
- Q5 Write a Python program to calculate Simple and Compound Interest. PYTHON
- Q6 Write a python program to find average and grade for given marks. PYTHON
- Q7 Write a Python program to find the sale price of an item with a given cost and discount (%). PYTHON
- Q8 Write a Python program to calculate profit-loss for given Cost and Sell Price. PYTHON
- Q9 Write a python program to calculate EMI for Amount, Period and Interest. EMI = (P*MR*(1+MR)**N)/(((1+MR)**N)-1) PYTHON
- Q10 Write a python program to calculate tax: (a) GST (b) Income Tax. PYTHON
- Q11 Write a python program to find the largest and smallest numbers in a list. PYTHON
- Q12 Write a python program to find the third largest/smallest number in a list. PYTHON
- Q13 Write a python program to find the sum of squares of the first 100 natural numbers. PYTHON
- Q14 Write a python program to print the first 'n' multiples of a given number. PYTHON
- Q15 Write a python program to count the number of vowels in a user entered string. PYTHON
- Q16 Write a python program to print the words starting with a given alphabet in a user entered string. PYTHON
- Q17 Write a python program to print the number of occurrences of a given alphabet in each string. PYTHON
- Q18 Write a python program to Create a dictionary to store names of states and their capitals. PYTHON
- Q19 Write a python program to Create a dictionary of students to store names and marks obtained in 5 subjects. PYTHON
- Q20 Write a python program to print the highest and lowest values in the dictionary. PYTHON
- Q21 Write a python program to create a student dictionary and search by using the name of the student and display the details. PYTHON
- Q22 SQL: To create a school database and access it. SQL
- Q23 SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key). SQL
- Q24 SQL: To insert the details of at least 10 students in the above table. SQL
- Q25 SQL: To display the entire content of the table. SQL
- Q26 SQL: To display Rno, Name and Marks of those students scoring marks more than 50. SQL
- Q27 SQL: To find the average of marks from the student table. SQL
- Q28 SQL: To find the number of students who are from section 'A'. SQL
- Q29 SQL: To display information of all students whose name starts with 'AN'. SQL
- Q30 SQL: To display Rno, Name, DOB of students born between '2005-01-01' and '2005-12-31'. SQL
- Q31 SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names. SQL
- Q32 SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks. SQL
- Q33 SQL: To display the unique sections available in the table. SQL
- Q34 SQL: To display the name and class of students whose marks are less than 33. SQL
- Q35 SQL: To display the structure of the student table. SQL
- 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
- Q1 Search an element in a list and display frequency & location using Linear Search (user-defined function). PYTHON
- Q2 Search an element in a list and display frequency & location using Binary Search (user-defined function). PYTHON
- Q3 Pass a list to a function; double the odd values and half the even values, then display the changed list. PYTHON
- Q4 Input n numbers in a tuple and pass it to a function to count how many even and odd numbers are entered. PYTHON
- Q5 Function with key and value updates the value at that key in a dictionary entered by the user. PYTHON
- Q6 Pass a string to a function and count how many vowels are present in the string. PYTHON
- Q7 Generate random numbers between 1 and 6 (simulate a dice) using a user-defined function. PYTHON
- Q8 Menu driven python program to implement 10 python mathematical functions. PYTHON
- Q9 Implement Python string functions (all listed in Sumita Arora book). PYTHON
- Q10 Menu driven program to delete a student's name from a dictionary and search phone number by student name. PYTHON
- Q11 Read and display file content line by line with each word separated by #. PYTHON
- Q12 Read a text file and display the number of vowels, consonants, uppercase, lowercase characters in the file. PYTHON
- Q13 Menu driven program to count spaces, digits, words and lines from text file TOY.txt. PYTHON
- Q14 Remove all lines that contain the character 'a' in a file and write remaining lines to another file. PYTHON
- Q15 Create a binary file with name and roll number; search for a given roll number and display name. PYTHON
- Q16 Create a dictionary with roll number, name and marks; accept 5 records and write them into a binary file. PYTHON
- Q17 Create a CSV file by entering user-id and password; read and search the password for a given user-id. PYTHON
- Q18 Menu driven program to create a CSV file with dept-id, name, city; read and search a record for given dept-id. PYTHON
- Q19 Implement a Stack using a list (PUSH & POP operations). PYTHON
- Q20 Function PUSH(Arr): from a given list push all numbers divisible by 5 into a stack implemented using a list. PYTHON
- Q21 Function POP(Arr): Arr is a stack implemented using a list of numbers; the function returns the value deleted from the stack. PYTHON
- 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
- Q23 Integrate SQL with Python using the MySQL module โ insert and display employee records. PYTHON
- Q24 Integrate SQL with Python โ search an employee using empno; display the record if present, else show a message. PYTHON
- 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
- Q1 Create Pandas Series from (a) an ndarray (b) a List (labeled & positional index) (c) a Dictionary (d) a Scalar value. PYTHON
- Q2 Perform operations on a Series: (a) Slicing (minimum 5) (b) Filtering (all relational operators). PYTHON
- Q3 Create a Series containing a dictionary of students' results (name, class, percentage, result); print elements above 75%. PYTHON
- Q4 Create Pandas DataFrame & display from (a) ndarray (b) List (labeled & positional index) (c) Dictionary (d) another DataFrame. PYTHON
- Q5 Create a DataFrame of quarterly sales (item category, item name, expenditure); group by category and print total expenditure per category. PYTHON
- Q6 Create a DataFrame for examination results and display row labels, column labels, data types of each column and dimensions. PYTHON
- Q7 Filter out rows based on different criteria such as duplicate rows. PYTHON
- Q8 Importing and exporting data between pandas and a CSV file. PYTHON
- Q9 Given the school result data, analyse the performance of students on different parameters (e.g., subject-wise or class-wise). PYTHON
- Q10 For the DataFrames created above, analyse and plot appropriate charts with title and legend. PYTHON
- Q11 Take data of your interest from an open source (e.g. data.gov.in), aggregate & summarize it, then plot using Matplotlib. PYTHON
- Q12 Locate the 3 largest values in a DataFrame. PYTHON
- Q13 Subtract the mean of a row from each element of that row in a DataFrame. PYTHON
- Q14 Replace all negative values with 0 in a DataFrame. PYTHON
- Q15 Replace all missing values with 999 in a DataFrame. PYTHON
- 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
- Q17 Create a DataFrame using lists (books data); display Class XII books, books priced above 250, and plot a line chart. PYTHON
- Q18 Country/Population/BirthRate DataFrame โ display China & India data, Brazil & Pakistan columns, export CSV, plot bar chart. PYTHON
- Q19 SQL: To create a school database and access it. SQL
- Q20 SQL: To create a student table with student_id, class, section, gender, name, dob, marks (student_id as primary key). SQL
- Q21 SQL: To insert the details of at least 10 students in the above table. SQL
- Q22 SQL: To display the entire content of the table. SQL
- Q23 SQL: To display Rno, Name and Marks of students scoring marks more than 50. SQL
- Q24 SQL: To find the average of marks from the student table. SQL
- Q25 SQL: To find the number of students who are from section 'A'. SQL
- Q26 SQL: To display information of all students whose name starts with 'AN'. SQL
- Q27 SQL: To display Rno, Name, DOB of students born between '2005-01-01' and '2005-12-31'. SQL
- Q28 SQL: To display Rno, Name, DOB, Marks, Email of male students in ascending order of names. SQL
- Q29 SQL: To display Rno, Gender, Name, DOB, Marks, Email in descending order of marks. SQL
- Q30 SQL: To display the unique sections available in the table. SQL
- Q31 SQL: To display the name and class of students whose marks are less than 33. SQL
- Q32 SQL: To display the structure of the student table. SQL
- Q33 SQL: To display the Name and DOB of students who were born in 2008. SQL
- Q34 Write MySQL queries demonstrating: (a) Aggregate Functions (b) Mathematical Functions (c) Text Functions (d) Date & Time Functions (e) GROUP BY. SQL
- 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
- 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
- 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
- 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
- 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
- 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
- Q41 SQL: To delete the details of a particular student from the student table (e.g. student_id = 7). SQL
- Q42 SQL: To display the details of students who scored more than 80 marks. SQL
- Q43 SQL: To find the minimum, maximum, sum and average of the marks in the student table. SQL
- 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
- 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
- Q1 PRINT: Write a program to print personal information like Name, Father's Name, Class and School Name. PYTHON
- Q2 PRINT: Write a program to print the following patterns using multiple print commands (right-angled triangle and inverted triangle of stars). PYTHON
- Q3 PRINT: Write a program to find the square of number 7. PYTHON
- Q4 PRINT: Write a program to find the sum of two numbers 15 and 20. PYTHON
- Q5 PRINT: Write a program to convert length given in kilometers into meters. PYTHON
- Q6 PRINT: Write a program to print the table of 5 up to five terms. PYTHON
- Q7 PRINT: Write a program to calculate Simple Interest if principle_amount = 2000, rate_of_interest = 4.5 and time = 10. PYTHON
- Q8 INPUT: Write a program to calculate the Area and Perimeter of a rectangle. PYTHON
- Q9 INPUT: Write a program to calculate the Area of a triangle with Base and Height. PYTHON
- Q10 INPUT: Write a program to calculate the average marks of 3 subjects. PYTHON
- Q11 INPUT: Write a program to calculate the discounted amount with discount %. PYTHON
- Q12 INPUT: Write a program to calculate the Surface Area and Volume of a Cuboid. PYTHON
- 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
- 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
- Q15 LIST: Create a list of first 10 even numbers, add 1 to each list item and print the final list. PYTHON
- 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
- Q17 IF: Write a program to check if a person can vote. PYTHON
- Q18 IF: Write a program to check the grade of a student. PYTHON
- Q19 IF: Input a number and check if the number is positive, negative or zero and display an appropriate message. PYTHON
- Q20 FOR: Write a program to print the first 10 natural numbers. PYTHON
- Q21 FOR: Write a program to print the first 10 even numbers. PYTHON
- Q22 WHILE: Write a program to print odd numbers from 1 to n. PYTHON
- Q23 FOR: Write a program to print the sum of first 10 natural numbers. PYTHON
- Q24 LIST + FOR: Write a program to find the sum of all numbers stored in a list. PYTHON
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- Q1 Write a program to print your Bio-Data. PYTHON
- Q2 Write a program to convert temperature from Celsius to Fahrenheit. PYTHON
- Q3 Write a program to check if a number is even or odd. PYTHON
- Q4 Write a simple menu-driven calculator program. PYTHON
- Q5 Write a program to print a name 5 times. PYTHON
- Q6 Write a program to calculate the LCM and HCF of two numbers. PYTHON
- Q7 Write a program to print a right-angled triangle pattern. PYTHON
- Q8 Write a program to count vowels and consonants in a string. PYTHON
- Q9 Write a menu-driven program to insert and delete elements in a list. PYTHON
- Q10 Write a program to add the elements of the two lists. PYTHON
- Q11 Write a program to calculate the mean of a given list. PYTHON
- Q12 Write a program to create a 2D array using NumPy. PYTHON
- Q13 Write a program to convert a Python list to a NumPy array. PYTHON
- Q14 Write a program to create a 3x3 matrix with values from 11 to 19. PYTHON
- Q15 Write a program to calculate mean, median and mode using NumPy. PYTHON
- Q16 Write a menu-driven program to calculate mean, mode and median using the statistics module. PYTHON
- Q17 Write a program to calculate variance and standard deviation. PYTHON
- Q18 Write a program to create a DataFrame to store data of candidates who appeared in interviews. PYTHON
- Q19 Write a program to create a DataFrame of players and filter the players who scored more than 1000 runs. PYTHON
- Q20 Write a program to display a line chart from (2,5) to (9,10). PYTHON
- Q21 Write a program to display a scatter chart for the points (2,5), (9,10), (8,3), (5,7), (6,18). PYTHON
- Q22 Write a program to represent mobile game ratings on a bar chart. PYTHON
- Q23 Plot monthly sales data for garments on a line chart. PYTHON
- Q24 Read the CSV file saved in your system and display 10 rows. PYTHON
- Q25 Read the CSV file saved in your system and display its information. PYTHON
- Q26 Write a program to read an image and display it using Python. PYTHON
- Q27 Write a program to read an image and identify its shape using Python. PYTHON
- 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
- 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
- Q30 Unit 5 - Computer Vision: Apply the convolution operator (kernel) on an image matrix using NumPy. PYTHON
- 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
- Q32 ACTIVITY (Unit 5): Visit an RGB colour tool (https://www.w3schools.com/colors/colors_rgb.asp) and answer the colour-mixing questions. ACTIVITY
- Q33 ACTIVITY (Unit 5): Create your own pixel art / animated GIF using Piskel (www.piskelapp.com). ACTIVITY
- 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
- Q1 Unit 1: Categorize the given applications into the three domains of AI - Data Statistics, Computer Vision and Natural Language Processing. THEORY
- Q2 Unit 2: Identify ten companies currently hiring employees for specific AI positions. THEORY
- Q3 Unit 2: Note down the technical skills and soft skills listed by any two companies for a specific AI position. THEORY
- 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
- Q5 Python Level 1: Write a program to input marks of 5 subjects and display total, percentage and grade. PYTHON
- 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
- Q7 Python Level 1: Write a program to print the multiplication table of a number and find its factorial (for loop). PYTHON
- 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
- Q9 Python Level 2 (NumPy): Create NumPy arrays and perform arithmetic, statistical and indexing operations. PYTHON
- Q10 Python Level 2 (NumPy - Matrices): Create two 3x3 matrices and find their sum, product, transpose and determinant. PYTHON
- Q11 Python Level 2 (Pandas): Create a DataFrame of students, add a new column and display statistics. PYTHON
- Q12 Python Level 2 (Pandas + CSV): Read rainfall.csv into a DataFrame and analyse it (head, shape, mean, maximum and minimum rainfall month). PYTHON
- 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
- Q14 Unit 5: Identification of the level of measurement (Nominal, Ordinal, Interval, Ratio) of given data. THEORY
- Q15 Unit 5: Python program to demonstrate the use of mean, median, mode, standard deviation and variance. PYTHON
- Q16 Unit 5: Python program to visualise data using a LINE graph (monthly rainfall from rainfall.csv). PYTHON
- Q17 Unit 5: Python program to visualise data using a BAR graph. PYTHON
- Q18 Unit 5: Python program to visualise data using a HISTOGRAM. PYTHON
- Q19 Unit 5: Python program to visualise data using a SCATTER graph. PYTHON
- Q20 Unit 5: Python program to visualise data using a PIE chart. PYTHON
- 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
- Q22 Unit 4: Project Abstract Creation using the Design Thinking Framework (5W1H and SDG alignment). THEORY
- Q23 Unit 6: Calculation of Pearson's correlation coefficient in MS Excel. ACTIVITY
- Q24 Unit 6: Demonstration of Linear Regression in MS Excel. ACTIVITY
- Q25 Unit 6 (Advanced learners): Demonstration of Linear Regression using a Python program. PYTHON
- Q26 Unit 6 (Advanced learners): Demonstration of k-Nearest Neighbour (KNN) classification using a Python program. PYTHON
- Q27 Unit 6 (Advanced learners): Demonstration of k-Means clustering using a Python program. PYTHON
- Q28 Unit 7: Create a chatbot for ordering ice-creams using Google Dialogflow (or Botsify / Botpress). ACTIVITY
- Q29 Unit 7 (Advanced learners): Creating a simple rule-based chatbot using Python. PYTHON
- Q30 Unit 7 (Advanced learners): Program to print the POS (Parts of Speech) tags of a statement. PYTHON
- Q31 Unit 7: Write an article on 'IBM Project Debater - Interesting facts'. THEORY
- Q32 Unit 8: Summarize your insights and interpretations from the video 'Humans Need Not Apply'. THEORY
- Q33 Unit 8: Comparative study of AI policies (guidelines and principles) established by various organisations and regulatory bodies. THEORY
- 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
- 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
- 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
- Q3 Python 3: Import data from a CSV file into a DataFrame, process it and export the result to a new CSV file. PYTHON
- Q4 Python 4: Handle missing values in a dataset using dropna(), fillna() and interpolate(). PYTHON
- Q5 Python 5: Python code to evaluate a classification model - confusion matrix, accuracy, precision, recall and F1 score. PYTHON
- Q6 Python 6: Python code to evaluate a regression model using MAE, MSE, RMSE and R-squared. PYTHON
- Q7 Python 7 (Optional): Demonstration of train-test split in Linear Regression using Python. PYTHON
- Q8 Python 8: Build a TensorFlow model to convert Celsius to Fahrenheit (a single-neuron neural network that learns the formula from data). PYTHON
- Q9 Python 9 (Advanced learners): Working with OpenCV to load, display and resize images. PYTHON
- Q10 Unit 3 Activity: Binary Art - recreate an image with 0s and 1s using Python. PYTHON
- Q11 Python 10 (Advanced learners): Write Python code to initialise the Gemini API and create a chatbot. PYTHON
- Q12 Unit 2 Activity: Calculate MSE and RMSE values for the given data using MS Excel. ACTIVITY
- Q13 Unit 2 Activity: Calculate Precision, Recall, F1 score and Accuracy from the given confusion matrix. ACTIVITY
- 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
- Q15 Orange 2: Perform Classification with the Orange Data Mining tool. ACTIVITY
- Q16 Orange 3: Evaluate the Classification Model with Orange (Test and Score, Confusion Matrix). ACTIVITY
- Q17 Orange 4: Perform Image Analytics using the Orange Data Mining tool. ACTIVITY
- Q18 Orange 5: Write down the steps to visualise word frequencies with a Word Cloud using the Orange Data Mining tool. ACTIVITY
- Q19 Orange 6 (Unit 5): Perform Big Data analytics with the Orange Data Mining tool. ACTIVITY
- Q20 Unit 6 Activity: Explore Machine Learning for Kids to create a neural network for identifying animals and birds. ACTIVITY
- Q21 Unit 6 Activity: Classification problem using TensorFlow Playground. ACTIVITY
- Q22 Unit 6 Activity: Regression problem using TensorFlow Playground. ACTIVITY
- 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
- Q24 Unit 3 Activity: Creating a website containing an ML model (Teachable Machine + website). ACTIVITY
- 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)
Class XI Computer Science โ 10 Live Mini-Projects
- 1. Personal Expense Tracker (Console) PYTHON
- 2. School Grade Calculator PYTHON
- 3. Number Pattern & Math Puzzle Generator PYTHON
- 4. Simple Library Catalogue (In-Memory) PYTHON
- 5. Word & Text Analyzer Tool PYTHON
- 6. Contact Book Manager PYTHON
- 7. Tic-Tac-Toe (Two Player Game) PYTHON
- 8. Hangman Word Game PYTHON
- 9. Student Attendance Register PYTHON
- 10. Password Strength Checker & Generator PYTHON
Class XI Informatics Practices โ 10 Live Mini-Projects
- 1. Loan/EMI Comparison Calculator PYTHON
- 2. Shop Billing & GST Calculator PYTHON
- 3. Class Result Dictionary System PYTHON
- 4. School Student Database (SQL) MySQL
- 5. Geography Quiz โ States & Capitals PYTHON
- 6. Electricity Bill Calculator PYTHON
- 7. BMI & Health Tracker PYTHON
- 8. Hospital Patient Records (SQL Database) MySQL
- 9. Employee Payroll Database (SQL) MySQL
- 10. ATM Simulator PYTHON
Class XII Computer Science โ 10 Live Board Projects
- 1. Library Management System PYTHON
- 2. Bank Management System (with MySQL) PYTHON
- 3. Hospital Patient Management System PYTHON
- 4. Quiz / Online Exam System PYTHON
- 5. GST Invoice / Book-Shop Billing System PYTHON
- 6. Student Management System (Python + MySQL) PYTHON
- 7. Employee Payroll System (Binary File) PYTHON
- 8. Railway Reservation System (Python + MySQL) PYTHON
- 9. Browser History Manager (Stack) PYTHON
- 10. Hotel Management System (Python + MySQL) PYTHON
Class XII Informatics Practices โ 10 Live Data Projects
- 1. School Result Analytics Dashboard PYTHON
- 2. Household / Shop Expenditure Analyzer PYTHON
- 3. Open Government Data Explorer PYTHON
- 4. Student Database + SQL Analytics Combo PYTHON
- 5. Inventory / Stock Price Tracker PYTHON
- 6. Weather Data Analysis (Delhi) PYTHON
- 7. Retail Sales Analysis (CSV) PYTHON
- 8. Employee Payroll Analytics (MySQL + Pandas) PYTHON
- 9. Cricket Player Statistics Analyzer PYTHON
- 10. Air Quality Index (AQI) Analyzer PYTHON
Class IX Artificial Intelligence (417) โ 10 SDG Python Projects
- 1. Smart Water Usage Tracker (SDG 6) PYTHON
- 2. Home Electricity Saver (SDG 7) PYTHON
- 3. Car Spotting and Tabulating - Probability Analyser PYTHON
- 4. Rule-Based Crop Advisor for Farmers (SDG 2) PYTHON
- 5. Personalised Learning Quiz - AI Project Cycle (SDG 4) PYTHON
- 6. Preventable Blindness Screening - Model Evaluator (SDG 3) PYTHON
- 7. Top 10 Songs Data Explorer PYTHON
- 8. Family Health & BMI Advisor (SDG 3) PYTHON
- 9. Smart Waste Segregation Guide (SDG 12) PYTHON
- 10. Class Attendance Analyser and Predictor (SDG 4) PYTHON
Class X Artificial Intelligence (417) โ 10 AI Projects (incl. 3 CBSE sample projects)
- 1. Palmer Penguin Species Predictor (Statistical Data) PYTHON
- 2. Coral Bleaching Early Detector (Computer Vision) PYTHON
- 3. School Canteen Review Sentiment Analyser (NLP) PYTHON
- 4. Delhi Air Quality (AQI) Statistical Analyser (SDG 11) PYTHON
- 5. Study Hours vs Marks - Regression Predictor PYTHON
- 6. Image Filter Studio - Convolution in Action (Computer Vision) PYTHON
- 7. School Helpdesk Chatbot (Script Bot) PYTHON
- 8. Rainfall and Temperature Explorer (SDG 13) PYTHON
- 9. Smart Waste Bin Fill-Level Monitor (SDG 11) PYTHON
- 10. Crop Yield Data Insights (SDG 2) PYTHON
Class XI Artificial Intelligence (843) โ 10 Machine Learning Projects
- 1. Rainfall Data Analysis and Visualisation (rainfall.csv) PYTHON
- 2. House Price Predictor - Linear Regression (SDG 11) PYTHON
- 3. Iris Flower Classifier using k-Nearest Neighbour PYTHON
- 4. Customer Segmentation using k-Means Clustering (SDG 8) PYTHON
- 5. Ice-Cream Ordering Chatbot with Intent Matching PYTHON
- 6. Student Performance Correlation Study (SDG 4) PYTHON
- 7. SMS Spam Detector using Naive Bayes (SDG 16) PYTHON
- 8. Crop Recommendation System using KNN (SDG 2) PYTHON
- 9. Household Energy Consumption Forecaster (SDG 7) PYTHON
- 10. AI Bias Audit of a Loan-Approval Model (SDG 10) PYTHON
Class XII Artificial Intelligence (843) โ 10 Capstone Projects
- 1. Breast Cancer Diagnosis Assistant - Classification & Evaluation (SDG 3) PYTHON
- 2. Diabetes Progression Predictor - Regression with Cross-Validation (SDG 3) PYTHON
- 3. Handwritten Digit Recogniser using a Neural Network PYTHON
- 4. Celsius to Fahrenheit Neural Network with TensorFlow-Keras PYTHON
- 5. School Health Records - Data Cleaning & CSV Pipeline (SDG 3) PYTHON
- 6. Smart Object Counter & Shape Detector with OpenCV (Computer Vision) PYTHON
- 7. Traffic Sensor Data-Stream Analytics (Big Data, SDG 11) PYTHON
- 8. Product Review Sentiment Classifier - TF-IDF + Logistic Regression (SDG 12) PYTHON
- 9. Crop Yield Prediction using the Data Science Methodology (SDG 2) PYTHON
- 10. Student Dropout Early-Warning System with Data Story (SDG 4) PYTHON
๐ 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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.
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).
(Diagram-based theory answer โ no program output; draw the diagram neatly in the practical file.)
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
(Theory answer โ no program output; write in practical file for viva preparation.)
Write a python program to Input a welcome message and display it.
msg = input("Enter your welcome message: ")
print(msg)
Enter your welcome message: Welcome to KV Shalimar Bagh!
Welcome to KV Shalimar Bagh!
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
msg๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q3.py. - Press F5 (Run โ Run Module).
- When the program asks, type Welcome to KV Shalimar Bagh! (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | msg = input("Enter your welcome message: ") | msg = 'Welcome to KV Shalimar Bagh!' | Enter your welcome message: Welcome to KV Shalimar Bagh! |
| 2 | 2 | print(msg) | Welcome to KV Shalimar Bagh! |
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")
Enter first number: 45
Enter second number: 78
78 is larger and 45 is smaller
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
a, b๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q4.py. - Press F5 (Run โ Run Module).
- When the program asks, type 45, 78 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | a = int(input("Enter first number: ")) | a = 45 | Enter first number: 45 |
| 2 | 2 | b = int(input("Enter second number: ")) | b = 78 | Enter second number: 78 |
| 3 | 4 | if a > b: condition is FALSE โ skips this block | ||
| 4 | 6 | elif b > a: condition is TRUE โ enters the block | ||
| 5 | 7 | print(b, "is larger and", a, "is smaller") | 78 is larger and 45 is smaller |
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)
Enter first number: 12
Enter second number: 45
Enter third number: 30
Largest number = 45
Smallest number = 12
Largest (manual method) = 45
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
a, b, c๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q5.py. - Press F5 (Run โ Run Module).
- When the program asks, type 12, 45, 30 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | a = int(input("Enter first number: ")) | a = 12 | Enter first number: 12 |
| 2 | 2 | b = int(input("Enter second number: ")) | b = 45 | Enter second number: 45 |
| 3 | 3 | c = int(input("Enter third number: ")) | c = 30 | Enter third number: 30 |
| 4 | 5 | largest = max(a, b, c) | largest = 45 | |
| 5 | 6 | smallest = min(a, b, c) | smallest = 12 | |
| 6 | 7 | print("Largest number =", largest) | Largest number = 45 | |
| 7 | 8 | print("Smallest number =", smallest) | Smallest number = 12 | |
| 8 | 11 | if a >= b and a >= c: condition is FALSE โ skips this block | ||
| 9 | 13 | elif b >= a and b >= c: condition is TRUE โ enters the block | ||
| 10 | 14 | largest = b | ||
| 11 | 17 | print("Largest (manual method) =", largest) | Largest (manual method) = 45 |
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)
Enter value of x: 2
Enter value of n: 5
x^n using ** operator = 32
x^n using loop = 32
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
x, n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q6.py. - Press F5 (Run โ Run Module).
- When the program asks, type 2, 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | x = int(input("Enter value of x: ")) | x = 2 | Enter value of x: 2 |
| 2 | 2 | n = int(input("Enter value of n: ")) | n = 5 | Enter value of n: 5 |
| 3 | 5 | print("x^n using ** operator =", x ** n) | x^n using ** operator = 32 | |
| 4 | 8 | result = 1 | result = 1 | |
| 5 | 9 | for i in range(n): next item taken | i = 0 | |
| 6 | 10 | result = result * x | result = 2 | |
| 7 | 9 | for i in range(n): next item taken | i = 1 | |
| 8 | 10 | result = result * x | result = 4 | |
| 9 | 9 | for i in range(n): next item taken | i = 2 | |
| 10 | 10 | result = result * x | result = 8 | |
| 11 | 9 | for i in range(n): next item taken | i = 3 | |
| 12 | 10 | result = result * x | result = 16 | |
| 13 | 9 | for i in range(n): next item taken | i = 4 | |
| 14 | 10 | result = result * x | result = 32 | |
| 15 | 9 | for i in range(n): no items left โ loop ends | ||
| 16 | 11 | print("x^n using loop =", result) | x^n using loop = 32 |
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)
Enter number of rows: 4
*
**
***
****
1
1 2
1 2 3
1 2 3 4
****
***
**
*
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q7.py. - Press F5 (Run โ Run Module).
- When the program asks, type 4 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("Enter number of rows: ")) | n = 4 | Enter number of rows: 4 |
| 2 | 4 | for i in range(1, n + 1): next item taken | i = 1 | |
| 3 | 5 | print("*" * i) | * | |
| 4 | 4 | for i in range(1, n + 1): next item taken | i = 2 | |
| 5 | 5 | print("*" * i) | ** | |
| 6 | 4 | for i in range(1, n + 1): next item taken | i = 3 | |
| 7 | 5 | print("*" * i) | *** | |
| 8 | 4 | for i in range(1, n + 1): next item taken | i = 4 | |
| 9 | 5 | print("*" * i) | **** | |
| 10 | 4 | for i in range(1, n + 1): no items left โ loop ends | ||
| 11 | 7 | print() | ||
| 12 | 9 | for i in range(1, n + 1): next item taken | i = 1 | |
| 13 | 10 | for j in range(1, i + 1): next item taken | j = 1 | |
| 14 | 11 | print(j, end=" ") | 1 | |
| 15 | 10 | for j in range(1, i + 1): no items left โ loop ends | ||
| 16 | 12 | print() | ||
| 17 | 9 | for i in range(1, n + 1): next item taken | i = 2 | |
| 18 | 10 | for j in range(1, i + 1): next item taken | ||
| 19 | 11 | print(j, end=" ") | 1 | |
| 20 | 10 | for j in range(1, i + 1): next item taken | j = 2 | |
| 21 | 11 | print(j, end=" ") | 2 | |
| 22 | 10 | for j in range(1, i + 1): no items left โ loop ends | ||
| 23 | 12 | print() | ||
| 24 | 9 | for i in range(1, n + 1): next item taken | i = 3 | |
| 25 | 10 | for j in range(1, i + 1): next item taken | j = 1 | |
| 26 | 11 | print(j, end=" ") | 1 | |
| 27 | 10 | for j in range(1, i + 1): next item taken | j = 2 | |
| 28 | 11 | print(j, end=" ") | 2 | |
| 29 | 10 | for j in range(1, i + 1): next item taken | j = 3 | |
| 30 | 11 | print(j, end=" ") | 3 | |
| 31 | 10 | for j in range(1, i + 1): no items left โ loop ends | ||
| 32 | 12 | print() |
โฆ Python runs 22 more line-steps in the same way (loops repeat the same lines). Final values: n = 4, i = 1, j = 4
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)
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
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
x, n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q8.py. - Press F5 (Run โ Run Module).
- When the program asks, type 2, 3 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import math | ||
| 2 | 3 | x = float(input("Enter value of x: ")) | x = 2.0 | Enter value of x: 2 |
| 3 | 4 | n = int(input("Enter value of n: ")) | n = 3 | Enter value of n: 3 |
| 4 | 7 | s1 = 0 | s1 = 0 | |
| 5 | 8 | for i in range(0, n + 1): next item taken | i = 0 | |
| 6 | 9 | s1 += x ** i | s1 = 1.0 | |
| 7 | 8 | for i in range(0, n + 1): next item taken | i = 1 | |
| 8 | 9 | s1 += x ** i | s1 = 3.0 | |
| 9 | 8 | for i in range(0, n + 1): next item taken | i = 2 | |
| 10 | 9 | s1 += x ** i | s1 = 7.0 | |
| 11 | 8 | for i in range(0, n + 1): next item taken | i = 3 | |
| 12 | 9 | s1 += x ** i | s1 = 15.0 | |
| 13 | 8 | for i in range(0, n + 1): no items left โ loop ends | ||
| 14 | 10 | print("(i) Sum =", s1) | (i) Sum = 15.0 | |
| 15 | 13 | s2 = 0 | s2 = 0 | |
| 16 | 14 | sign = 1 | sign = 1 | |
| 17 | 15 | for i in range(0, n + 1): next item taken | i = 0 | |
| 18 | 16 | s2 += sign * (x ** i) | s2 = 1.0 | |
| 19 | 17 | sign *= -1 | sign = -1 | |
| 20 | 15 | for i in range(0, n + 1): next item taken | i = 1 | |
| 21 | 16 | s2 += sign * (x ** i) | s2 = -1.0 | |
| 22 | 17 | sign *= -1 | sign = 1 | |
| 23 | 15 | for i in range(0, n + 1): next item taken | i = 2 | |
| 24 | 16 | s2 += sign * (x ** i) | s2 = 3.0 | |
| 25 | 17 | sign *= -1 | sign = -1 | |
| 26 | 15 | for i in range(0, n + 1): next item taken | i = 3 | |
| 27 | 16 | s2 += sign * (x ** i) | s2 = -5.0 | |
| 28 | 17 | sign *= -1 | sign = 1 | |
| 29 | 15 | for i in range(0, n + 1): no items left โ loop ends | ||
| 30 | 18 | print("(ii) Sum =", s2) | (ii) Sum = -5.0 | |
| 31 | 21 | s3 = 0 | s3 = 0 | |
| 32 | 22 | 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
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")
Enter a number: 153
153 is NOT a Perfect number
153 is an Armstrong number
153 is NOT a Palindrome
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q9.py. - Press F5 (Run โ Run Module).
- When the program asks, type 153 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("Enter a number: ")) | n = 153 | Enter a number: 153 |
| 2 | 2 | orig = n | orig = 153 | |
| 3 | 5 | s = 0 | s = 0 | |
| 4 | 6 | for i in range(1, n): next item taken | i = 1 | |
| 5 | 7 | if n % i == 0: condition is TRUE โ enters the block | ||
| 6 | 8 | s += i | s = 1 | |
| 7 | 6 | for i in range(1, n): next item taken | i = 2 | |
| 8 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 9 | 6 | for i in range(1, n): next item taken | i = 3 | |
| 10 | 7 | if n % i == 0: condition is TRUE โ enters the block | ||
| 11 | 8 | s += i | s = 4 | |
| 12 | 6 | for i in range(1, n): next item taken | i = 4 | |
| 13 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 14 | 6 | for i in range(1, n): next item taken | i = 5 | |
| 15 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 16 | 6 | for i in range(1, n): next item taken | i = 6 | |
| 17 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 18 | 6 | for i in range(1, n): next item taken | i = 7 | |
| 19 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 20 | 6 | for i in range(1, n): next item taken | i = 8 | |
| 21 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 22 | 6 | for i in range(1, n): next item taken | i = 9 | |
| 23 | 7 | if n % i == 0: condition is TRUE โ enters the block | ||
| 24 | 8 | s += i | s = 13 | |
| 25 | 6 | for i in range(1, n): next item taken | i = 10 | |
| 26 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 27 | 6 | for i in range(1, n): next item taken | i = 11 | |
| 28 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 29 | 6 | for i in range(1, n): next item taken | i = 12 | |
| 30 | 7 | if n % i == 0: condition is FALSE โ skips this block | ||
| 31 | 6 | for i in range(1, n): next item taken | i = 13 | |
| 32 | 7 | 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
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")
Enter a number: 17
17 is a Prime number
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q10.py. - Press F5 (Run โ Run Module).
- When the program asks, type 17 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("Enter a number: ")) | n = 17 | Enter a number: 17 |
| 2 | 2 | is_prime = True | is_prime = True | |
| 3 | 4 | if n <= 1: condition is FALSE โ skips this block | ||
| 4 | 7 | for i in range(2, int(n ** 0.5) + 1): next item taken | i = 2 | |
| 5 | 8 | if n % i == 0: condition is FALSE โ skips this block | ||
| 6 | 7 | for i in range(2, int(n ** 0.5) + 1): next item taken | i = 3 | |
| 7 | 8 | if n % i == 0: condition is FALSE โ skips this block | ||
| 8 | 7 | for i in range(2, int(n ** 0.5) + 1): next item taken | i = 4 | |
| 9 | 8 | if n % i == 0: condition is FALSE โ skips this block | ||
| 10 | 7 | for i in range(2, int(n ** 0.5) + 1): no items left โ loop ends | ||
| 11 | 12 | if is_prime: condition is TRUE โ enters the block | ||
| 12 | 13 | print(n, "is a Prime number") | 17 is a Prime number |
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
Enter number of terms: 7
Fibonacci Series:
0 1 1 2 3 5 8
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q11.py. - Press F5 (Run โ Run Module).
- When the program asks, type 7 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("Enter number of terms: ")) | n = 7 | Enter number of terms: 7 |
| 2 | 2 | a, b = 0, 1 | a = 0, b = 1 | |
| 3 | 3 | print("Fibonacci Series:") | Fibonacci Series: | |
| 4 | 4 | for i in range(n): next item taken | i = 0 | |
| 5 | 5 | print(a, end=" ") | 0 | |
| 6 | 6 | a, b = b, a + b | a = 1 | |
| 7 | 4 | for i in range(n): next item taken | i = 1 | |
| 8 | 5 | print(a, end=" ") | 1 | |
| 9 | 6 | a, b = b, a + b | b = 2 | |
| 10 | 4 | for i in range(n): next item taken | i = 2 | |
| 11 | 5 | print(a, end=" ") | 1 | |
| 12 | 6 | a, b = b, a + b | a = 2, b = 3 | |
| 13 | 4 | for i in range(n): next item taken | i = 3 | |
| 14 | 5 | print(a, end=" ") | 2 | |
| 15 | 6 | a, b = b, a + b | a = 3, b = 5 | |
| 16 | 4 | for i in range(n): next item taken | i = 4 | |
| 17 | 5 | print(a, end=" ") | 3 | |
| 18 | 6 | a, b = b, a + b | a = 5, b = 8 | |
| 19 | 4 | for i in range(n): next item taken | i = 5 | |
| 20 | 5 | print(a, end=" ") | 5 | |
| 21 | 6 | a, b = b, a + b | a = 8, b = 13 | |
| 22 | 4 | for i in range(n): next item taken | i = 6 | |
| 23 | 5 | print(a, end=" ") | 8 | |
| 24 | 6 | a, b = b, a + b | a = 13, b = 21 | |
| 25 | 4 | for i in range(n): no items left โ loop ends |
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)
Enter first number: 12
Enter second number: 18
GCD/HCF = 6
LCM = 36
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
a, b๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q12.py. - Press F5 (Run โ Run Module).
- When the program asks, type 12, 18 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | a = int(input("Enter first number: ")) | a = 12 | Enter first number: 12 |
| 2 | 2 | b = int(input("Enter second number: ")) | b = 18 | Enter second number: 18 |
| 3 | 4 | x, y = a, b | x = 12, y = 18 | |
| 4 | 5 | while y: condition is TRUE โ enters the block | ||
| 5 | 6 | x, y = y, x % y | x = 18, y = 12 | |
| 6 | 5 | while y: condition is TRUE โ enters the block | ||
| 7 | 6 | x, y = y, x % y | x = 12, y = 6 | |
| 8 | 5 | while y: condition is TRUE โ enters the block | ||
| 9 | 6 | x, y = y, x % y | x = 6, y = 0 | |
| 10 | 5 | while y: condition is FALSE โ loop ends | ||
| 11 | 7 | gcd = x | gcd = 6 | |
| 12 | 8 | lcm = (a * b) // gcd | lcm = 36 | |
| 13 | 10 | print("GCD/HCF =", gcd) | GCD/HCF = 6 | |
| 14 | 11 | print("LCM =", lcm) | LCM = 36 |
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)
Enter a string: Hello World 123
Vowels : 3
Consonants : 7
Uppercase : 2
Lowercase : 8
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
s๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q13.py. - Press F5 (Run โ Run Module).
- When the program asks, type Hello World 123 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | s = input("Enter a string: ") | s = 'Hello World 123' | Enter a string: Hello World 123 |
| 2 | 2 | vowels = consonants = upper = lower = 0 | vowels = 0, consonants = 0, upper = 0, lower = 0 | |
| 3 | 4 | for ch in s: next item taken | ch = 'H' | |
| 4 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 5 | 6 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 6 | 9 | consonants += 1 | consonants = 1 | |
| 7 | 10 | if ch.isupper(): condition is TRUE โ enters the block | ||
| 8 | 11 | upper += 1 | upper = 1 | |
| 9 | 4 | for ch in s: next item taken | ch = 'e' | |
| 10 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 11 | 6 | if ch.lower() in 'aeiou': condition is TRUE โ enters the block | ||
| 12 | 7 | vowels += 1 | vowels = 1 | |
| 13 | 10 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 14 | 12 | elif ch.islower(): condition is TRUE โ enters the block | ||
| 15 | 13 | lower += 1 | lower = 1 | |
| 16 | 4 | for ch in s: next item taken | ch = 'l' | |
| 17 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 18 | 6 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 19 | 9 | consonants += 1 | consonants = 2 | |
| 20 | 10 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 21 | 12 | elif ch.islower(): condition is TRUE โ enters the block | ||
| 22 | 13 | lower += 1 | lower = 2 | |
| 23 | 4 | for ch in s: next item taken | ||
| 24 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 25 | 6 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 26 | 9 | consonants += 1 | consonants = 3 | |
| 27 | 10 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 28 | 12 | elif ch.islower(): condition is TRUE โ enters the block | ||
| 29 | 13 | lower += 1 | lower = 3 | |
| 30 | 4 | for ch in s: next item taken | ch = 'o' | |
| 31 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 32 | 6 | 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'
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())
Enter a string: madam
madam is a Palindrome
UPPER CASE : MADAM
lower case : madam
Swap Case : MADAM
Title Case : Madam
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
s๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q14.py. - Press F5 (Run โ Run Module).
- When the program asks, type madam (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | s = input("Enter a string: ") | s = 'madam' | Enter a string: madam |
| 2 | 3 | if s == s[::-1]: condition is TRUE โ enters the block | ||
| 3 | 4 | print(s, "is a Palindrome") | madam is a Palindrome | |
| 4 | 9 | print("UPPER CASE :", s.upper()) | UPPER CASE : MADAM | |
| 5 | 10 | print("lower case :", s.lower()) | lower case : madam | |
| 6 | 11 | print("Swap Case :", s.swapcase()) | Swap Case : MADAM | |
| 7 | 12 | print("Title Case :", s.title()) | Title Case : Madam |
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))
Enter numbers separated by space: 12 45 3 78 22
Largest number : 78 at position 3
Smallest number : 3 at position 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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q15.py. - Press F5 (Run โ Run Module).
- When the program asks, type 12 45 3 78 22 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 3 | largest = max(lst) | largest = 78 | |
| 3 | 4 | smallest = min(lst) | smallest = 3 | |
| 4 | 6 | print("Largest number :", largest, "at position", lst.index(largest)) | Largest number : 78 at position 3 | |
| 5 | 7 | print("Smallest number :", smallest, "at position", lst.index(smallest)) | Smallest number : 3 at position 2 |
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)
Enter numbers separated by space: 10 20 30 40 50
List after swapping: [20, 10, 40, 30, 50]
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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q16.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10 20 30 40 50 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 3 | for i in range(0, len(lst) - 1, 2): next item taken | i = 0 | |
| 3 | 4 | lst[i], lst[i + 1] = lst[i + 1], lst[i] | lst = [20, 10, 30, 40, 50] | |
| 4 | 3 | for i in range(0, len(lst) - 1, 2): next item taken | i = 2 | |
| 5 | 4 | lst[i], lst[i + 1] = lst[i + 1], lst[i] | lst = [20, 10, 40, 30, 50] | |
| 6 | 3 | for i in range(0, len(lst) - 1, 2): no items left โ loop ends | ||
| 7 | 6 | print("List after swapping:", lst) | List after swapping: [20, 10, 40, 30, 50] |
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")
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]
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
lst, n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q17.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10 20 30 20 10, 20 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 2 | n = int(input("Enter number to search: ")) | n = 20 | Enter number to search: 20 |
| 3 | 4 | count = lst.count(n) | count = 2 | |
| 4 | 5 | if count > 0: condition is TRUE โ enters the block | ||
| 5 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | ||
| 6 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | ||
| 7 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | ||
| 8 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | ||
| 9 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | ||
| 10 | 6 | positions = [i for i in range(len(lst)) if lst[i] == n] | positions = [1, 3] | |
| 11 | 7 | print(n, "found", count, "time(s) at position(s):", positions) | 20 found 2 time(s) at position(s): [1, 3] |
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")
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
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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q18.py. - Press F5 (Run โ Run Module).
- When the program asks, type 153 370 20 371 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 2 | special = [] | special = [] | |
| 3 | 4 | for num in lst: next item taken | num = 153 | |
| 4 | 5 | temp = num | temp = 153 | |
| 5 | 6 | s = 0 | s = 0 | |
| 6 | 7 | while temp > 0: condition is TRUE โ enters the block | ||
| 7 | 8 | d = temp % 10 | d = 3 | |
| 8 | 9 | s += d ** 3 | s = 27 | |
| 9 | 10 | temp //= 10 | temp = 15 | |
| 10 | 7 | while temp > 0: condition is TRUE โ enters the block | ||
| 11 | 8 | d = temp % 10 | d = 5 | |
| 12 | 9 | s += d ** 3 | s = 152 | |
| 13 | 10 | temp //= 10 | temp = 1 | |
| 14 | 7 | while temp > 0: condition is TRUE โ enters the block | ||
| 15 | 8 | d = temp % 10 | d = 1 | |
| 16 | 9 | s += d ** 3 | s = 153 | |
| 17 | 10 | temp //= 10 | temp = 0 | |
| 18 | 7 | while temp > 0: condition is FALSE โ loop ends | ||
| 19 | 11 | if s == num: condition is TRUE โ enters the block | ||
| 20 | 12 | special.append(num) | special = [153] | |
| 21 | 4 | for num in lst: next item taken | num = 370 | |
| 22 | 5 | temp = num | temp = 370 | |
| 23 | 6 | s = 0 | s = 0 | |
| 24 | 7 | while temp > 0: condition is TRUE โ enters the block | ||
| 25 | 8 | d = temp % 10 | d = 0 | |
| 26 | 9 | s += d ** 3 | ||
| 27 | 10 | temp //= 10 | temp = 37 | |
| 28 | 7 | while temp > 0: condition is TRUE โ enters the block | ||
| 29 | 8 | d = temp % 10 | d = 7 | |
| 30 | 9 | s += d ** 3 | s = 343 | |
| 31 | 10 | temp //= 10 | temp = 3 | |
| 32 | 7 | 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
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)
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
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
n, roll, name, marks๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q19.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | students = {} | students = {} | |
| 2 | 2 | n = int(input("How many students? ")) | n = 3 | How many students? 3 |
| 3 | 4 | for i in range(n): next item taken | i = 0 | |
| 4 | 5 | roll = int(input("Enter roll number: ")) | roll = 1 | Enter roll number: 1 |
| 5 | 6 | name = input("Enter name: ") | name = 'Amit' | Enter name: Amit |
| 6 | 7 | marks = float(input("Enter marks: ")) | marks = 88.0 | Enter marks: 88 |
| 7 | 8 | students[roll] = (name, marks) | students = {1: ('Amit', 88.0)} | |
| 8 | 4 | for i in range(n): next item taken | i = 1 | |
| 9 | 5 | roll = int(input("Enter roll number: ")) | roll = 2 | Enter roll number: 2 |
| 10 | 6 | name = input("Enter name: ") | name = 'Sara' | Enter name: Sara |
| 11 | 7 | marks = float(input("Enter marks: ")) | marks = 92.0 | Enter marks: 92 |
| 12 | 8 | students[roll] = (name, marks) | students = {1: ('Amit', 88.0), 2: ('Sara', 92.0)} | |
| 13 | 4 | for i in range(n): next item taken | i = 2 | |
| 14 | 5 | roll = int(input("Enter roll number: ")) | roll = 3 | Enter roll number: 3 |
| 15 | 6 | name = input("Enter name: ") | name = 'Rahul' | Enter name: Rahul |
| 16 | 7 | marks = float(input("Enter marks: ")) | marks = 65.0 | Enter marks: 65 |
| 17 | 8 | students[roll] = (name, marks) | students = {1: ('Amit', 88.0), 2: ('Sara', 92.0), 3: ('Rahul', 65.0)} | |
| 18 | 4 | for i in range(n): no items left โ loop ends | ||
| 19 | 10 | print("\nStudents scoring above 75:") | Students scoring above 75: | |
| 20 | 11 | for roll, (name, marks) in students.items(): next item taken | roll = 1, name = 'Amit', marks = 88.0 | |
| 21 | 12 | if marks > 75: condition is TRUE โ enters the block | ||
| 22 | 13 | print("Roll:", roll, "Name:", name, "Marks:", marks) | Roll: 1 Name: Amit Marks: 88.0 | |
| 23 | 11 | for roll, (name, marks) in students.items(): next item taken | roll = 2, name = 'Sara', marks = 92.0 | |
| 24 | 12 | if marks > 75: condition is TRUE โ enters the block | ||
| 25 | 13 | print("Roll:", roll, "Name:", name, "Marks:", marks) | Roll: 2 Name: Sara Marks: 92.0 | |
| 26 | 11 | for roll, (name, marks) in students.items(): next item taken | roll = 3, name = 'Rahul', marks = 65.0 | |
| 27 | 12 | if marks > 75: condition is FALSE โ skips this block | ||
| 28 | 11 | for roll, (name, marks) in students.items(): no items left โ loop ends |
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"])
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
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
empid, empname, empsal, empmobile๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q20.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | employees = {} | employees = {} | |
| 2 | 3 | for i in range(5): next item taken | i = 0 | |
| 3 | 4 | empid = int(input("Enter Employee ID: ")) | empid = 201 | Enter Employee ID: 201 |
| 4 | 5 | empname = input("Enter Employee Name: ") | empname = 'Rahul' | Enter Employee Name: Rahul |
| 5 | 6 | empsal = float(input("Enter Salary: ")) | empsal = 45000.0 | Enter Salary: 45000 |
| 6 | 7 | empmobile = input("Enter Mobile: ") | empmobile = '9876543210' | Enter Mobile: 9876543210 |
| 7 | 8 | employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile} | employees = {201: {'name': 'Rahul', 'salary': 45000.0, 'mobile': '9876543210'}} | |
| 8 | 3 | for i in range(5): next item taken | i = 1 | |
| 9 | 4 | empid = int(input("Enter Employee ID: ")) | empid = 202 | Enter Employee ID: 202 |
| 10 | 5 | empname = input("Enter Employee Name: ") | empname = 'Priya' | Enter Employee Name: Priya |
| 11 | 6 | empsal = float(input("Enter Salary: ")) | empsal = 62000.0 | Enter Salary: 62000 |
| 12 | 7 | empmobile = input("Enter Mobile: ") | empmobile = '9811122233' | Enter Mobile: 9811122233 |
| 13 | 8 | employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile} | employees = {201: {'name': 'Rahul', 'salary': 45000.0, 'mobile': '9876543210'},โฆ | |
| 14 | 3 | for i in range(5): next item taken | i = 2 | |
| 15 | 4 | empid = int(input("Enter Employee ID: ")) | empid = 203 | Enter Employee ID: 203 |
| 16 | 5 | empname = input("Enter Employee Name: ") | empname = 'Karan' | Enter Employee Name: Karan |
| 17 | 6 | empsal = float(input("Enter Salary: ")) | empsal = 38000.0 | Enter Salary: 38000 |
| 18 | 7 | empmobile = input("Enter Mobile: ") | empmobile = '9899001122' | Enter Mobile: 9899001122 |
| 19 | 8 | employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile} | ||
| 20 | 3 | for i in range(5): next item taken | i = 3 | |
| 21 | 4 | empid = int(input("Enter Employee ID: ")) | empid = 204 | Enter Employee ID: 204 |
| 22 | 5 | empname = input("Enter Employee Name: ") | empname = 'Neha' | Enter Employee Name: Neha |
| 23 | 6 | empsal = float(input("Enter Salary: ")) | empsal = 75000.0 | Enter Salary: 75000 |
| 24 | 7 | empmobile = input("Enter Mobile: ") | empmobile = '9810098100' | Enter Mobile: 9810098100 |
| 25 | 8 | employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile} | ||
| 26 | 3 | for i in range(5): next item taken | i = 4 | |
| 27 | 4 | empid = int(input("Enter Employee ID: ")) | empid = 205 | Enter Employee ID: 205 |
| 28 | 5 | empname = input("Enter Employee Name: ") | empname = 'Vivek' | Enter Employee Name: Vivek |
| 29 | 6 | empsal = float(input("Enter Salary: ")) | empsal = 50000.0 | Enter Salary: 50000 |
| 30 | 7 | empmobile = input("Enter Mobile: ") | empmobile = '9876501234' | Enter Mobile: 9876501234 |
| 31 | 8 | employees[empid] = {"name": empname, "salary": empsal, "mobile": empmobile} | ||
| 32 | 3 | 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'}
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")
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!
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
search_name, bookid, bookname, bookprice, bookauthor, new_price๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q21.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | library = {} | library = {} | |
| 2 | 3 | for i in range(5): next item taken | i = 0 | |
| 3 | 4 | bookid = int(input("Enter Book ID: ")) | bookid = 1 | Enter Book ID: 1 |
| 4 | 5 | bookname = input("Enter Book Name: ") | bookname = 'Python Basics' | Enter Book Name: Python Basics |
| 5 | 6 | bookprice = float(input("Enter Book Price: ")) | bookprice = 350.0 | Enter Book Price: 350 |
| 6 | 7 | bookauthor = input("Enter Author: ") | bookauthor = 'Sumita Arora' | Enter Author: Sumita Arora |
| 7 | 8 | library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor} | library = {1: {'name': 'Python Basics', 'price': 350.0, 'author': 'Sumita Aroโฆ | |
| 8 | 3 | for i in range(5): next item taken | i = 1 | |
| 9 | 4 | bookid = int(input("Enter Book ID: ")) | bookid = 2 | Enter Book ID: 2 |
| 10 | 5 | bookname = input("Enter Book Name: ") | bookname = 'Data Structures' | Enter Book Name: Data Structures |
| 11 | 6 | bookprice = float(input("Enter Book Price: ")) | bookprice = 420.0 | Enter Book Price: 420 |
| 12 | 7 | bookauthor = input("Enter Author: ") | bookauthor = 'Reema Thareja' | Enter Author: Reema Thareja |
| 13 | 8 | library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor} | ||
| 14 | 3 | for i in range(5): next item taken | i = 2 | |
| 15 | 4 | bookid = int(input("Enter Book ID: ")) | bookid = 3 | Enter Book ID: 3 |
| 16 | 5 | bookname = input("Enter Book Name: ") | bookname = 'Let Us C' | Enter Book Name: Let Us C |
| 17 | 6 | bookprice = float(input("Enter Book Price: ")) | bookprice = 300.0 | Enter Book Price: 300 |
| 18 | 7 | bookauthor = input("Enter Author: ") | bookauthor = 'Y. Kanetkar' | Enter Author: Y. Kanetkar |
| 19 | 8 | library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor} | ||
| 20 | 3 | for i in range(5): next item taken | i = 3 | |
| 21 | 4 | bookid = int(input("Enter Book ID: ")) | bookid = 4 | Enter Book ID: 4 |
| 22 | 5 | bookname = input("Enter Book Name: ") | bookname = 'AI for All' | Enter Book Name: AI for All |
| 23 | 6 | bookprice = float(input("Enter Book Price: ")) | bookprice = 280.0 | Enter Book Price: 280 |
| 24 | 7 | bookauthor = input("Enter Author: ") | bookauthor = 'NITI Aayog' | Enter Author: NITI Aayog |
| 25 | 8 | library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor} | ||
| 26 | 3 | for i in range(5): next item taken | i = 4 | |
| 27 | 4 | bookid = int(input("Enter Book ID: ")) | bookid = 5 | Enter Book ID: 5 |
| 28 | 5 | bookname = input("Enter Book Name: ") | bookname = 'Computer Networks' | Enter Book Name: Computer Networks |
| 29 | 6 | bookprice = float(input("Enter Book Price: ")) | bookprice = 510.0 | Enter Book Price: 510 |
| 30 | 7 | bookauthor = input("Enter Author: ") | bookauthor = 'A. Tanenbaum' | Enter Author: A. Tanenbaum |
| 31 | 8 | library[bookid] = {"name": bookname, "price": bookprice, "author": bookauthor} | ||
| 32 | 3 | 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
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)
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}
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
del_id๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q22.py. - Press F5 (Run โ Run Module).
- When the program asks, type 102 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | 101: {"client": "Amit", "date": "01-07-2026", "room": 201}, | ||
| 2 | 3 | 102: {"client": "Sara", "date": "02-07-2026", "room": 105}, | ||
| 3 | 4 | 103: {"client": "Rahul", "date": "03-07-2026", "room": 310}, | ||
| 4 | 1 | hotel = { | hotel = {101: {'client': 'Amit', 'date': '01-07-2026', 'room': 201}, 102: {โฆ | |
| 5 | 7 | print("Booking records:") | Booking records: | |
| 6 | 8 | for bid, info in hotel.items(): next item taken | bid = 101, info = {'client': 'Amit', 'date': '01-07-2026', 'room': 201} | |
| 7 | 9 | print(bid, info) | 101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201} | |
| 8 | 8 | for bid, info in hotel.items(): next item taken | bid = 102, info = {'client': 'Sara', 'date': '02-07-2026', 'room': 105} | |
| 9 | 9 | print(bid, info) | 102 {'client': 'Sara', 'date': '02-07-2026', 'room': 105} | |
| 10 | 8 | for bid, info in hotel.items(): next item taken | bid = 103, info = {'client': 'Rahul', 'date': '03-07-2026', 'room': 310} | |
| 11 | 9 | print(bid, info) | 103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310} | |
| 12 | 8 | for bid, info in hotel.items(): no items left โ loop ends | ||
| 13 | 11 | del_id = int(input("\nEnter Booking ID to cancel/delete: ")) | del_id = 102 | Enter Booking ID to cancel/delete: 102 |
| 14 | 12 | if del_id in hotel: condition is TRUE โ enters the block | ||
| 15 | 13 | del hotel[del_id] | hotel = {101: {'client': 'Amit', 'date': '01-07-2026', 'room': 201}, 103: {โฆ | |
| 16 | 14 | print("Booking", del_id, "deleted successfully") | Booking 102 deleted successfully | |
| 17 | 18 | print("\nRecords after deletion:") | Records after deletion: | |
| 18 | 19 | for bid, info in hotel.items(): next item taken | bid = 101, info = {'client': 'Amit', 'date': '01-07-2026', 'room': 201} | |
| 19 | 20 | print(bid, info) | 101 {'client': 'Amit', 'date': '01-07-2026', 'room': 201} | |
| 20 | 19 | for bid, info in hotel.items(): next item taken | bid = 103, info = {'client': 'Rahul', 'date': '03-07-2026', 'room': 310} | |
| 21 | 20 | print(bid, info) | 103 {'client': 'Rahul', 'date': '03-07-2026', 'room': 310} | |
| 22 | 19 | for bid, info in hotel.items(): no items left โ loop ends |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q23.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import math | ||
| 2 | 3 | print("Value of pi :", math.pi) | Value of pi : 3.141592653589793 | |
| 3 | 4 | print("Value of e :", math.e) | Value of e : 2.718281828459045 | |
| 4 | 5 | print("sqrt(25) :", math.sqrt(25)) | sqrt(25) : 5.0 | |
| 5 | 6 | print("ceil(4.2) :", math.ceil(4.2)) | ceil(4.2) : 5 | |
| 6 | 7 | print("floor(4.8) :", math.floor(4.8)) | floor(4.8) : 4 | |
| 7 | 8 | print("pow(2,3) :", math.pow(2, 3)) | pow(2,3) : 8.0 | |
| 8 | 9 | print("fabs(-7.5) :", math.fabs(-7.5)) | fabs(-7.5) : 7.5 | |
| 9 | 10 | print("sin(0) :", math.sin(0)) | sin(0) : 0.0 | |
| 10 | 11 | print("cos(0) :", math.cos(0)) | cos(0) : 1.0 | |
| 11 | 12 | print("tan(0) :", math.tan(0)) | tan(0) : 0.0 |
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
random() : 0.11911988496396309
randint(1,6) : 5
randrange(0,10,2) : 8
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q24.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import random | ||
| 2 | 3 | print("random() :", random.random()) # float between 0 and 1 | random() : 0.11911988496396309 | |
| 3 | 4 | print("randint(1,6) :", random.randint(1, 6)) # dice simulation, both ends inclu | randint(1,6) : 5 | |
| 4 | 5 | print("randrange(0,10,2) :", random.randrange(0, 10, 2)) # even numbers 0,2,4,6,8 | randrange(0,10,2) : 8 |
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))
Data : [10, 20, 20, 30, 40, 20, 50]
Mean : 27.142857142857142
Median: 20
Mode : 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q25.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import statistics as st | ||
| 2 | 3 | data = [10, 20, 20, 30, 40, 20, 50] | data = [10, 20, 20, 30, 40, 20, 50] | |
| 3 | 5 | print("Data :", data) | Data : [10, 20, 20, 30, 40, 20, 50] | |
| 4 | 6 | print("Mean :", st.mean(data)) | Mean : 27.142857142857142 | |
| 5 | 7 | print("Median:", st.median(data)) | Median: 20 | |
| 6 | 8 | print("Mode :", st.mode(data)) | Mode : 20 |
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))
Enter a positive number: 6
Factorial of 6 is 720
Using math.factorial(): 720
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q26.py. - Press F5 (Run โ Run Module).
- When the program asks, type 6 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("Enter a positive number: ")) | n = 6 | Enter a positive number: 6 |
| 2 | 3 | if n < 0: condition is FALSE โ skips this block | ||
| 3 | 6 | fact = 1 | fact = 1 | |
| 4 | 7 | for i in range(1, n + 1): next item taken | i = 1 | |
| 5 | 8 | fact = fact * i | ||
| 6 | 7 | for i in range(1, n + 1): next item taken | i = 2 | |
| 7 | 8 | fact = fact * i | fact = 2 | |
| 8 | 7 | for i in range(1, n + 1): next item taken | i = 3 | |
| 9 | 8 | fact = fact * i | fact = 6 | |
| 10 | 7 | for i in range(1, n + 1): next item taken | i = 4 | |
| 11 | 8 | fact = fact * i | fact = 24 | |
| 12 | 7 | for i in range(1, n + 1): next item taken | i = 5 | |
| 13 | 8 | fact = fact * i | fact = 120 | |
| 14 | 7 | for i in range(1, n + 1): next item taken | i = 6 | |
| 15 | 8 | fact = fact * i | fact = 720 | |
| 16 | 7 | for i in range(1, n + 1): no items left โ loop ends | ||
| 17 | 9 | print("Factorial of", n, "is", fact) | Factorial of 6 is 720 | |
| 18 | 11 | import math | ||
| 19 | 12 | print("Using math.factorial():", math.factorial(n)) | Using math.factorial(): 720 |
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))
Enter a number: -17.5
Absolute value (if-else) : 17.5
Absolute value (abs()) : 17.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
num๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q27.py. - Press F5 (Run โ Run Module).
- When the program asks, type -17.5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | num = float(input("Enter a number: ")) | num = -17.5 | Enter a number: -17.5 |
| 2 | 4 | if num < 0: condition is TRUE โ enters the block | ||
| 3 | 5 | absolute = -num | absolute = 17.5 | |
| 4 | 8 | print("Absolute value (if-else) :", absolute) | Absolute value (if-else) : 17.5 | |
| 5 | 11 | print("Absolute value (abs()) :", abs(num)) | Absolute value (abs()) : 17.5 |
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])
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]
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
a, b๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q28.py. - Press F5 (Run โ Run Module).
- When the program asks, type 84, 7 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | a = int(input("Enter the number : ")) | a = 84 | Enter the number : 84 |
| 2 | 2 | b = int(input("Enter the divisor : ")) | b = 7 | Enter the divisor : 7 |
| 3 | 4 | if b == 0: condition is FALSE โ skips this block | ||
| 4 | 6 | elif a % b == 0: condition is TRUE โ enters the block | ||
| 5 | 7 | print(a, "is divisible by", b, "| Quotient =", a // b) | 84 is divisible by 7 | Quotient = 12 | |
| 6 | 12 | print("Numbers from 1 to 50 divisible by", b, ":") | Numbers from 1 to 50 divisible by 7 : | |
| 7 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 8 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 9 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 10 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 11 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 12 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 13 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 14 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 15 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 16 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 17 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 18 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 19 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 20 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 21 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 22 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 23 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 24 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 25 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 26 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 27 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 28 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 29 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 30 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 31 | 13 | print([x for x in range(1, 51) if x % b == 0]) | ||
| 32 | 13 | 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
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")
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
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
text๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_cs_q29.py. - Press F5 (Run โ Run Module).
- When the program asks, type hello world (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | text = input("Enter a string: ") | text = 'hello world' | Enter a string: hello world |
| 2 | 3 | freq = {} # empty dictionary | freq = {} | |
| 3 | 4 | for ch in text: next item taken | ch = 'h' | |
| 4 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 5 | 8 | freq[ch] = 1 | freq = {'h': 1} | |
| 6 | 4 | for ch in text: next item taken | ch = 'e' | |
| 7 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 8 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1} | |
| 9 | 4 | for ch in text: next item taken | ch = 'l' | |
| 10 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 11 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1, 'l': 1} | |
| 12 | 4 | for ch in text: next item taken | ||
| 13 | 5 | if ch in freq: condition is TRUE โ enters the block | ||
| 14 | 6 | freq[ch] = freq[ch] + 1 | freq = {'h': 1, 'e': 1, 'l': 2} | |
| 15 | 4 | for ch in text: next item taken | ch = 'o' | |
| 16 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 17 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1} | |
| 18 | 4 | for ch in text: next item taken | ch = ' ' | |
| 19 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 20 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1, ' ': 1} | |
| 21 | 4 | for ch in text: next item taken | ch = 'w' | |
| 22 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 23 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1, ' ': 1, 'w': 1} | |
| 24 | 4 | for ch in text: next item taken | ch = 'o' | |
| 25 | 5 | if ch in freq: condition is TRUE โ enters the block | ||
| 26 | 6 | freq[ch] = freq[ch] + 1 | freq = {'h': 1, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'w': 1} | |
| 27 | 4 | for ch in text: next item taken | ch = 'r' | |
| 28 | 5 | if ch in freq: condition is FALSE โ skips this block | ||
| 29 | 8 | freq[ch] = 1 | freq = {'h': 1, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'w': 1, 'r': 1} | |
| 30 | 4 | for ch in text: next item taken | ch = 'l' | |
| 31 | 5 | if ch in freq: condition is TRUE โ enters the block | ||
| 32 | 6 | 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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.
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)
(Theory answer โ draw diagram in file for viva marks.)
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
(Theory answer โ write in practical file for viva preparation.)
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")
Enter first number: 20
Enter second number: 4
Enter operator (+,-,*,/,%,//): *
Result = 80.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
a, b, op๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q3.py. - Press F5 (Run โ Run Module).
- When the program asks, type 20, 4, * (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | a = float(input("Enter first number: ")) | a = 20.0 | Enter first number: 20 |
| 2 | 2 | b = float(input("Enter second number: ")) | b = 4.0 | Enter second number: 4 |
| 3 | 3 | op = input("Enter operator (+,-,*,/,%,//): ") | op = '*' | Enter operator (+,-,*,/,%,//): * |
| 4 | 5 | if op == '+': condition is FALSE โ skips this block | ||
| 5 | 7 | elif op == '-': condition is FALSE โ skips this block | ||
| 6 | 9 | elif op == '*': condition is TRUE โ enters the block | ||
| 7 | 10 | print("Result =", a * b) | Result = 80.0 |
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")
1.Triangle 2.Rectangle 3.Square 4.Circle
Choose shape: 4
Radius: 7
Circumference = 43.982297150257104 Area = 153.93804002589985
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
ch, a, b, c, l, w, side, r๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q4.py. - Press F5 (Run โ Run Module).
- When the program asks, type 4, 7 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import math | ||
| 2 | 3 | print("1.Triangle 2.Rectangle 3.Square 4.Circle") | 1.Triangle 2.Rectangle 3.Square 4.Circle | |
| 3 | 4 | ch = int(input("Choose shape: ")) | ch = 4 | Choose shape: 4 |
| 4 | 6 | if ch == 1: condition is FALSE โ skips this block | ||
| 5 | 11 | elif ch == 2: condition is FALSE โ skips this block | ||
| 6 | 14 | elif ch == 3: condition is FALSE โ skips this block | ||
| 7 | 17 | elif ch == 4: condition is TRUE โ enters the block | ||
| 8 | 18 | r = float(input("Radius: ")) | r = 7.0 | Radius: 7 |
| 9 | 19 | print("Circumference =", 2 * math.pi * r, " Area =", math.pi * r ** 2) | Circumference = 43.982297150257104 Area = 153.93804002589985 |
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))
Enter Principal: 10000
Enter Rate of Interest: 8
Enter Time (years): 2
Simple Interest = Rs. 1600.0
Compound Interest = Rs. 1664.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
p, r, t๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q5.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10000, 8, 2 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | p = float(input("Enter Principal: ")) | p = 10000.0 | Enter Principal: 10000 |
| 2 | 2 | r = float(input("Enter Rate of Interest: ")) | r = 8.0 | Enter Rate of Interest: 8 |
| 3 | 3 | t = float(input("Enter Time (years): ")) | t = 2.0 | Enter Time (years): 2 |
| 4 | 5 | si = (p * r * t) / 100 | si = 1600.0 | |
| 5 | 6 | ci = p * ((1 + r / 100) ** t) - p | ci = 1664.0000000000018 | |
| 6 | 8 | print("Simple Interest = Rs.", round(si, 2)) | Simple Interest = Rs. 1600.0 | |
| 7 | 9 | print("Compound Interest = Rs.", round(ci, 2)) | Compound Interest = Rs. 1664.0 |
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)
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
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
subjects, marks๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q6.py. - Press F5 (Run โ Run Module).
- When the program asks, type 3, 80, 90, 85 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | subjects = int(input("Enter number of subjects: ")) | subjects = 3 | Enter number of subjects: 3 |
| 2 | 2 | total = 0 | total = 0 | |
| 3 | 4 | for i in range(subjects): next item taken | i = 0 | |
| 4 | 5 | marks = float(input(f"Enter marks of subject {i+1}: ")) | marks = 80.0 | Enter marks of subject 1: 80 |
| 5 | 6 | total += marks | total = 80.0 | |
| 6 | 4 | for i in range(subjects): next item taken | i = 1 | |
| 7 | 5 | marks = float(input(f"Enter marks of subject {i+1}: ")) | marks = 90.0 | Enter marks of subject 2: 90 |
| 8 | 6 | total += marks | total = 170.0 | |
| 9 | 4 | for i in range(subjects): next item taken | i = 2 | |
| 10 | 5 | marks = float(input(f"Enter marks of subject {i+1}: ")) | marks = 85.0 | Enter marks of subject 3: 85 |
| 11 | 6 | total += marks | total = 255.0 | |
| 12 | 4 | for i in range(subjects): no items left โ loop ends | ||
| 13 | 8 | avg = total / subjects | avg = 85.0 | |
| 14 | 9 | print("Average =", avg) | Average = 85.0 | |
| 15 | 11 | if avg >= 90: condition is FALSE โ skips this block | ||
| 16 | 13 | elif avg >= 75: condition is TRUE โ enters the block | ||
| 17 | 14 | grade = 'A' | grade = 'A' | |
| 18 | 21 | print("Grade =", grade) | Grade = A |
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)
Enter Cost Price: 1000
Enter Discount %: 20
Discount Amount = 200.0
Sale Price = 800.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
cost, discount๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q7.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1000, 20 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | cost = float(input("Enter Cost Price: ")) | cost = 1000.0 | Enter Cost Price: 1000 |
| 2 | 2 | discount = float(input("Enter Discount %: ")) | discount = 20.0 | Enter Discount %: 20 |
| 3 | 4 | discount_amt = (cost * discount) / 100 | discount_amt = 200.0 | |
| 4 | 5 | sale_price = cost - discount_amt | sale_price = 800.0 | |
| 5 | 7 | print("Discount Amount =", discount_amt) | Discount Amount = 200.0 | |
| 6 | 8 | print("Sale Price =", sale_price) | Sale Price = 800.0 |
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")
Enter Cost Price: 500
Enter Selling Price: 650
Profit = 150.0 ( 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
cp, sp๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q8.py. - Press F5 (Run โ Run Module).
- When the program asks, type 500, 650 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | cp = float(input("Enter Cost Price: ")) | cp = 500.0 | Enter Cost Price: 500 |
| 2 | 2 | sp = float(input("Enter Selling Price: ")) | sp = 650.0 | Enter Selling Price: 650 |
| 3 | 4 | if sp > cp: condition is TRUE โ enters the block | ||
| 4 | 5 | profit = sp - cp | profit = 150.0 | |
| 5 | 6 | print("Profit =", profit, " (", round((profit/cp)*100, 2), "% )") | Profit = 150.0 ( 30.0 % ) |
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))
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
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
p, annual_rate, years๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q9.py. - Press F5 (Run โ Run Module).
- When the program asks, type 500000, 9, 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | p = float(input("Enter Loan Amount (P): ")) | p = 500000.0 | Enter Loan Amount (P): 500000 |
| 2 | 2 | annual_rate = float(input("Enter Annual Interest Rate %: ")) | annual_rate = 9.0 | Enter Annual Interest Rate %: 9 |
| 3 | 3 | years = int(input("Enter Loan Period (years): ")) | years = 5 | Enter Loan Period (years): 5 |
| 4 | 5 | mr = annual_rate / (12 * 100) # monthly interest rate | mr = 0.0075 | |
| 5 | 6 | n = years * 12 # number of monthly installments | n = 60 | |
| 6 | 8 | emi = (p * mr * (1 + mr) ** n) / (((1 + mr) ** n) - 1) | emi = 10379.177613176937 | |
| 7 | 9 | print("Monthly EMI = Rs.", round(emi, 2)) | Monthly EMI = Rs. 10379.18 | |
| 8 | 10 | print("Total Payment = Rs.", round(emi * n, 2)) | Total Payment = Rs. 622750.66 |
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")
1. GST 2. Income Tax
Choose: 1
Enter amount: 1000
Enter GST rate %: 18
GST = 180.0 Total Amount = 1180.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
ch, amount, rate, income๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q10.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1, 1000, 18 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | print("1. GST 2. Income Tax") | 1. GST 2. Income Tax | |
| 2 | 2 | ch = int(input("Choose: ")) | ch = 1 | Choose: 1 |
| 3 | 4 | if ch == 1: condition is TRUE โ enters the block | ||
| 4 | 5 | amount = float(input("Enter amount: ")) | amount = 1000.0 | Enter amount: 1000 |
| 5 | 6 | rate = float(input("Enter GST rate %: ")) | rate = 18.0 | Enter GST rate %: 18 |
| 6 | 7 | gst = amount * rate / 100 | gst = 180.0 | |
| 7 | 8 | print("GST =", gst, " Total Amount =", amount + gst) | GST = 180.0 Total Amount = 1180.0 |
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))
Enter numbers separated by space: 34 12 89 5 67
Largest : 89
Smallest : 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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q11.py. - Press F5 (Run โ Run Module).
- When the program asks, type 34 12 89 5 67 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 2 | print("Largest :", max(lst)) | Largest : 89 | |
| 3 | 3 | print("Smallest :", min(lst)) | Smallest : 5 |
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])
Enter numbers separated by space: 10 40 20 40 30
Third Largest : 20
Third Smallest : 30
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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q12.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10 40 20 40 30 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | 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 |
| 2 | 2 | unique_sorted_desc = sorted(set(lst), reverse=True) | unique_sorted_desc = [40, 30, 20, 10] | |
| 3 | 3 | unique_sorted_asc = sorted(set(lst)) | unique_sorted_asc = [10, 20, 30, 40] | |
| 4 | 5 | print("Third Largest :", unique_sorted_desc[2]) | Third Largest : 20 | |
| 5 | 6 | print("Third Smallest :", unique_sorted_asc[2]) | Third Smallest : 30 |
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)
Sum of squares of first 100 natural numbers = 338350
Using formula = 338350
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q13.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | total = 0 | total = 0 | |
| 2 | 2 | for i in range(1, 101): next item taken | i = 1 | |
| 3 | 3 | total += i ** 2 | total = 1 | |
| 4 | 2 | for i in range(1, 101): next item taken | i = 2 | |
| 5 | 3 | total += i ** 2 | total = 5 | |
| 6 | 2 | for i in range(1, 101): next item taken | i = 3 | |
| 7 | 3 | total += i ** 2 | total = 14 | |
| 8 | 2 | for i in range(1, 101): next item taken | i = 4 | |
| 9 | 3 | total += i ** 2 | total = 30 | |
| 10 | 2 | for i in range(1, 101): next item taken | i = 5 | |
| 11 | 3 | total += i ** 2 | total = 55 | |
| 12 | 2 | for i in range(1, 101): next item taken | i = 6 | |
| 13 | 3 | total += i ** 2 | total = 91 | |
| 14 | 2 | for i in range(1, 101): next item taken | i = 7 | |
| 15 | 3 | total += i ** 2 | total = 140 | |
| 16 | 2 | for i in range(1, 101): next item taken | i = 8 | |
| 17 | 3 | total += i ** 2 | total = 204 | |
| 18 | 2 | for i in range(1, 101): next item taken | i = 9 | |
| 19 | 3 | total += i ** 2 | total = 285 | |
| 20 | 2 | for i in range(1, 101): next item taken | i = 10 | |
| 21 | 3 | total += i ** 2 | total = 385 | |
| 22 | 2 | for i in range(1, 101): next item taken | i = 11 | |
| 23 | 3 | total += i ** 2 | total = 506 | |
| 24 | 2 | for i in range(1, 101): next item taken | i = 12 | |
| 25 | 3 | total += i ** 2 | total = 650 | |
| 26 | 2 | for i in range(1, 101): next item taken | i = 13 | |
| 27 | 3 | total += i ** 2 | total = 819 | |
| 28 | 2 | for i in range(1, 101): next item taken | i = 14 | |
| 29 | 3 | total += i ** 2 | total = 1015 | |
| 30 | 2 | for i in range(1, 101): next item taken | i = 15 | |
| 31 | 3 | total += i ** 2 | total = 1240 | |
| 32 | 2 | 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
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)
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
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
num, n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q14.py. - Press F5 (Run โ Run Module).
- When the program asks, type 7, 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | num = int(input("Enter a number: ")) | num = 7 | Enter a number: 7 |
| 2 | 2 | n = int(input("How many multiples? ")) | n = 5 | How many multiples? 5 |
| 3 | 4 | for i in range(1, n + 1): next item taken | i = 1 | |
| 4 | 5 | print(num, "x", i, "=", num * i) | 7 x 1 = 7 | |
| 5 | 4 | for i in range(1, n + 1): next item taken | i = 2 | |
| 6 | 5 | print(num, "x", i, "=", num * i) | 7 x 2 = 14 | |
| 7 | 4 | for i in range(1, n + 1): next item taken | i = 3 | |
| 8 | 5 | print(num, "x", i, "=", num * i) | 7 x 3 = 21 | |
| 9 | 4 | for i in range(1, n + 1): next item taken | i = 4 | |
| 10 | 5 | print(num, "x", i, "=", num * i) | 7 x 4 = 28 | |
| 11 | 4 | for i in range(1, n + 1): next item taken | i = 5 | |
| 12 | 5 | print(num, "x", i, "=", num * i) | 7 x 5 = 35 | |
| 13 | 4 | for i in range(1, n + 1): no items left โ loop ends |
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)
Enter a string: Computer Education
Number of vowels = 8
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
s๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q15.py. - Press F5 (Run โ Run Module).
- When the program asks, type Computer Education (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | s = input("Enter a string: ") | s = 'Computer Education' | Enter a string: Computer Education |
| 2 | 2 | count = 0 | count = 0 | |
| 3 | 3 | for ch in s.lower(): next item taken | ch = 'c' | |
| 4 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 5 | 3 | for ch in s.lower(): next item taken | ch = 'o' | |
| 6 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 7 | 5 | count += 1 | count = 1 | |
| 8 | 3 | for ch in s.lower(): next item taken | ch = 'm' | |
| 9 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 10 | 3 | for ch in s.lower(): next item taken | ch = 'p' | |
| 11 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 12 | 3 | for ch in s.lower(): next item taken | ch = 'u' | |
| 13 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 14 | 5 | count += 1 | count = 2 | |
| 15 | 3 | for ch in s.lower(): next item taken | ch = 't' | |
| 16 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 17 | 3 | for ch in s.lower(): next item taken | ch = 'e' | |
| 18 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 19 | 5 | count += 1 | count = 3 | |
| 20 | 3 | for ch in s.lower(): next item taken | ch = 'r' | |
| 21 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 22 | 3 | for ch in s.lower(): next item taken | ch = ' ' | |
| 23 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 24 | 3 | for ch in s.lower(): next item taken | ch = 'e' | |
| 25 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 26 | 5 | count += 1 | count = 4 | |
| 27 | 3 | for ch in s.lower(): next item taken | ch = 'd' | |
| 28 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 29 | 3 | for ch in s.lower(): next item taken | ch = 'u' | |
| 30 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 31 | 5 | count += 1 | count = 5 | |
| 32 | 3 | 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'
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)
Enter a sentence: Amit Angad Rahul Anjali
Enter starting alphabet: a
Words starting with 'a':
Amit
Angad
Anjali
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
s, letter๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q16.py. - Press F5 (Run โ Run Module).
- When the program asks, type Amit Angad Rahul Anjali, a (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | s = input("Enter a sentence: ") | s = 'Amit Angad Rahul Anjali' | Enter a sentence: Amit Angad Rahul Anjali |
| 2 | 2 | letter = input("Enter starting alphabet: ").lower() | letter = 'a' | Enter starting alphabet: a |
| 3 | 4 | words = s.split() | words = ['Amit', 'Angad', 'Rahul', 'Anjali'] | |
| 4 | 5 | print("Words starting with '" + letter + "':") | Words starting with 'a': | |
| 5 | 6 | for w in words: next item taken | w = 'Amit' | |
| 6 | 7 | if w.lower().startswith(letter): condition is TRUE โ enters the block | ||
| 7 | 8 | print(w) | Amit | |
| 8 | 6 | for w in words: next item taken | w = 'Angad' | |
| 9 | 7 | if w.lower().startswith(letter): condition is TRUE โ enters the block | ||
| 10 | 8 | print(w) | Angad | |
| 11 | 6 | for w in words: next item taken | w = 'Rahul' | |
| 12 | 7 | if w.lower().startswith(letter): condition is FALSE โ skips this block | ||
| 13 | 6 | for w in words: next item taken | w = 'Anjali' | |
| 14 | 7 | if w.lower().startswith(letter): condition is TRUE โ enters the block | ||
| 15 | 8 | print(w) | Anjali | |
| 16 | 6 | for w in words: no items left โ loop ends |
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))
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
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
n, letter, s๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q17.py. - Press F5 (Run โ Run Module).
- When the program asks, type 2, a, banana, apple (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | n = int(input("How many strings? ")) | n = 2 | How many strings? 2 |
| 2 | 2 | letter = input("Enter alphabet to search: ").lower() | letter = 'a' | Enter alphabet to search: a |
| 3 | 4 | for i in range(n): next item taken | i = 0 | |
| 4 | 5 | s = input(f"Enter string {i+1}: ") | s = 'banana' | Enter string 1: banana |
| 5 | 6 | print("Occurrences of '" + letter + "' :", s.lower().count(letter)) | Occurrences of 'a' : 3 | |
| 6 | 4 | for i in range(n): next item taken | i = 1 | |
| 7 | 5 | s = input(f"Enter string {i+1}: ") | s = 'apple' | Enter string 2: apple |
| 8 | 6 | print("Occurrences of '" + letter + "' :", s.lower().count(letter)) | Occurrences of 'a' : 1 | |
| 9 | 4 | for i in range(n): no items left โ loop ends |
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")
Delhi -> New Delhi
Maharashtra -> Mumbai
Rajasthan -> Jaipur
Punjab -> Chandigarh
Kerala -> Thiruvananthapuram
Enter state name to find capital: Punjab
Capital of Punjab is Chandigarh
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
query๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q18.py. - Press F5 (Run โ Run Module).
- When the program asks, type Punjab (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | "Delhi": "New Delhi", | ||
| 2 | 3 | "Maharashtra": "Mumbai", | ||
| 3 | 4 | "Rajasthan": "Jaipur", | ||
| 4 | 5 | "Punjab": "Chandigarh", | ||
| 5 | 6 | "Kerala": "Thiruvananthapuram" | ||
| 6 | 1 | states = { | states = {'Delhi': 'New Delhi', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipuโฆ | |
| 7 | 9 | for state, capital in states.items(): next item taken | state = 'Delhi', capital = 'New Delhi' | |
| 8 | 10 | print(state, "->", capital) | Delhi -> New Delhi | |
| 9 | 9 | for state, capital in states.items(): next item taken | state = 'Maharashtra', capital = 'Mumbai' | |
| 10 | 10 | print(state, "->", capital) | Maharashtra -> Mumbai | |
| 11 | 9 | for state, capital in states.items(): next item taken | state = 'Rajasthan', capital = 'Jaipur' | |
| 12 | 10 | print(state, "->", capital) | Rajasthan -> Jaipur | |
| 13 | 9 | for state, capital in states.items(): next item taken | state = 'Punjab', capital = 'Chandigarh' | |
| 14 | 10 | print(state, "->", capital) | Punjab -> Chandigarh | |
| 15 | 9 | for state, capital in states.items(): next item taken | state = 'Kerala', capital = 'Thiruvananthapuram' | |
| 16 | 10 | print(state, "->", capital) | Kerala -> Thiruvananthapuram | |
| 17 | 9 | for state, capital in states.items(): no items left โ loop ends | ||
| 18 | 12 | query = input("\nEnter state name to find capital: ") | query = 'Punjab' | Enter state name to find capital: Punjab |
| 19 | 13 | if query in states: condition is TRUE โ enters the block | ||
| 20 | 14 | print("Capital of", query, "is", states[query]) | Capital of Punjab is Chandigarh |
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)
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
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
n, name, m๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q19.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | students = {} | students = {} | |
| 2 | 2 | n = int(input("Number of students: ")) | n = 2 | Number of students: 2 |
| 3 | 4 | for i in range(n): next item taken | i = 0 | |
| 4 | 5 | name = input("Enter student name: ") | name = 'Amit' | Enter student name: Amit |
| 5 | 6 | marks = [] | marks = [] | |
| 6 | 7 | for s in range(5): next item taken | s = 0 | |
| 7 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 80.0 | Marks in subject 1: 80 |
| 8 | 9 | marks.append(m) | marks = [80.0] | |
| 9 | 7 | for s in range(5): next item taken | s = 1 | |
| 10 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 85.0 | Marks in subject 2: 85 |
| 11 | 9 | marks.append(m) | marks = [80.0, 85.0] | |
| 12 | 7 | for s in range(5): next item taken | s = 2 | |
| 13 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 90.0 | Marks in subject 3: 90 |
| 14 | 9 | marks.append(m) | marks = [80.0, 85.0, 90.0] | |
| 15 | 7 | for s in range(5): next item taken | s = 3 | |
| 16 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 78.0 | Marks in subject 4: 78 |
| 17 | 9 | marks.append(m) | marks = [80.0, 85.0, 90.0, 78.0] | |
| 18 | 7 | for s in range(5): next item taken | s = 4 | |
| 19 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 92.0 | Marks in subject 5: 92 |
| 20 | 9 | marks.append(m) | marks = [80.0, 85.0, 90.0, 78.0, 92.0] | |
| 21 | 7 | for s in range(5): no items left โ loop ends | ||
| 22 | 10 | students[name] = marks | students = {'Amit': [80.0, 85.0, 90.0, 78.0, 92.0]} | |
| 23 | 4 | for i in range(n): next item taken | i = 1 | |
| 24 | 5 | name = input("Enter student name: ") | name = 'Sara' | Enter student name: Sara |
| 25 | 6 | marks = [] | marks = [] | |
| 26 | 7 | for s in range(5): next item taken | s = 0 | |
| 27 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 88.0 | Marks in subject 1: 88 |
| 28 | 9 | marks.append(m) | marks = [88.0] | |
| 29 | 7 | for s in range(5): next item taken | s = 1 | |
| 30 | 8 | m = float(input(f" Marks in subject {s+1}: ")) | m = 91.0 | Marks in subject 2: 91 |
| 31 | 9 | marks.append(m) | marks = [88.0, 91.0] | |
| 32 | 7 | 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
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])
Highest: Sara with value 92
Lowest : Rahul with value 65
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q20.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | d = {"Amit": 78, "Sara": 92, "Rahul": 65, "Priya": 88} | d = {'Amit': 78, 'Sara': 92, 'Rahul': 65, 'Priya': 88} | |
| 2 | 3 | max_key = max(d, key=d.get) | max_key = 'Sara' | |
| 3 | 4 | min_key = min(d, key=d.get) | min_key = 'Rahul' | |
| 4 | 6 | print("Highest:", max_key, "with value", d[max_key]) | Highest: Sara with value 92 | |
| 5 | 7 | print("Lowest :", min_key, "with value", d[min_key]) | Lowest : Rahul with value 65 |
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")
Enter student name to search: Sara
Details found:
roll : 2
class : XI-B
marks : 92
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
name๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ip_q21.py. - Press F5 (Run โ Run Module).
- When the program asks, type Sara (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | "Amit": {"roll": 1, "class": "XI-A", "marks": 88}, | ||
| 2 | 3 | "Sara": {"roll": 2, "class": "XI-B", "marks": 92}, | ||
| 3 | 4 | "Rahul": {"roll": 3, "class": "XI-A", "marks": 76}, | ||
| 4 | 1 | students = { | students = {'Amit': {'roll': 1, 'class': 'XI-A', 'marks': 88}, 'Sara': {'roll'โฆ | |
| 5 | 7 | name = input("Enter student name to search: ") | name = 'Sara' | Enter student name to search: Sara |
| 6 | 8 | if name in students: condition is TRUE โ enters the block | ||
| 7 | 9 | print("Details found:") | Details found: | |
| 8 | 10 | for key, val in students[name].items(): next item taken | key = 'roll', val = 2 | |
| 9 | 11 | print(" ", key, ":", val) | roll : 2 | |
| 10 | 10 | for key, val in students[name].items(): next item taken | key = 'class', val = 'XI-B' | |
| 11 | 11 | print(" ", key, ":", val) | class : XI-B | |
| 12 | 10 | for key, val in students[name].items(): next item taken | key = 'marks', val = 92 | |
| 13 | 11 | print(" ", key, ":", val) | marks : 92 | |
| 14 | 10 | for key, val in students[name].items(): no items left โ loop ends |
SQL: To create a school database and access it.
CREATE DATABASE school;
USE school;
-- Verify:
SHOW DATABASES;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- The code selects the database with
USE school;- MySQL replies Database changed. - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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".
USE school;
Selects the database school - all following commands work inside it.
- MySQL replies "Database changed".
SHOW DATABASES;
Lists all the databases on the MySQL server.
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
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.
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');
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
SQL: To display the entire content of the table.
SELECT * FROM student;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT * FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------+---------+--------+--------------+------------+-------+---------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT student_id, name, marks FROM student WHERE marks > 50;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks > 50 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT student_id, name, marks โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition marks > 50 is checked row by row: 9 row(s) pass โ, 1 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+--------------+-------+ | 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)
SQL: To find the average of marks from the student table.
SELECT AVG(marks) AS Average_Marks
FROM student;
mysql> SELECT AVG(marks) AS Average_Marks
-> FROM student;
+---------------+
| Average_Marks |
+---------------+
| 73.650000 |
+---------------+
1 row in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT AVG(marks) AS Average_Marks FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: AVG() finds the average.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+---------------+ | Average_Marks | +---------------+ | 73.650000 | +---------------+ 1 row in set (0.00 sec)
SQL: To find the number of students who are from section 'A'.
SELECT COUNT(*) AS Total_Section_A
FROM student
WHERE section = 'A';
mysql> SELECT COUNT(*) AS Total_Section_A
-> FROM student
-> WHERE section = 'A';
+-----------------+
| Total_Section_A |
+-----------------+
| 6 |
+-----------------+
1 row in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
Fetches the summary values from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE section = 'A' โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition section = 'A' is checked row by row: 6 row(s) pass โ, 4 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+-----------------+ | Total_Section_A | +-----------------+ | 6 | +-----------------+ 1 row in set (0.00 sec)
SQL: To display information of all students whose name starts with 'AN'.
SELECT * FROM student
WHERE name LIKE 'AN%';
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT * FROM student WHERE name LIKE 'AN%';
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE name LIKE 'AN%' (starts with "AN") โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition name LIKE 'AN%' is checked row by row: 2 row(s) pass โ, 8 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------+---------+--------+-------------+------------+-------+---------------+ | 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)
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';
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT student_id, name, dob โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition dob BETWEEN '2009-01-01' AND '2009-12-31' is checked row by row: 7 row(s) pass โ, 3 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------------+------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE gender = 'M' โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT student_id, name, dob, marks, email โ picks the columns / calculates the values to show.
- ORDER BY name ASC โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition gender = 'M' is checked row by row: 5 row(s) pass โ, 5 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------------+--------------+------------+-------+---------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT student_id, gender, name, dob, marks, email FROM student ORDER BY marks DESC;
Fetches rows from student, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT student_id, gender, name, dob, marks, email โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------------+--------+--------------+------------+-------+---------------+ | 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)
SQL: To display the unique sections available in the table.
SELECT DISTINCT section FROM student;
mysql> SELECT DISTINCT section FROM student;
+---------+
| section |
+---------+
| A |
| B |
+---------+
2 rows in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT DISTINCT section FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT section โ picks the columns / calculates the values to show.
- DISTINCT โ removes repeated rows, so each value appears only once.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; DISTINCT removes repeats โ final result:
+---------+ | section | +---------+ | A | | B | +---------+ 2 rows in set (0.00 sec)
SQL: To display the name and class of students whose marks are less than 33.
SELECT name, class
FROM student
WHERE marks < 33;
mysql> SELECT name, class
-> FROM student
-> WHERE marks < 33;
Empty set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT name, class FROM student WHERE marks < 33;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks < 33 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, class โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition marks < 33 is checked row by row: 0 row(s) pass โ, 10 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
Empty set (0.00 sec)
SQL: To display the structure of the student table.
DESC student;
-- or
DESCRIBE student;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
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.
SQL: To display the Name and DOB of students who were born in 2008.
SELECT name, dob
FROM student
WHERE YEAR(dob) = 2008;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT name, dob FROM student WHERE YEAR(dob) = 2008;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE YEAR(dob) = 2008 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, dob โ picks the columns / calculates the values to show.
- Functions used: YEAR() takes the year from a date.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition YEAR(dob) = 2008 is checked row by row: 3 row(s) pass โ, 7 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------------+------------+ | name | dob | +--------------+------------+ | Rahul Sharma | 2008-12-02 | | Vivek Yadav | 2008-11-30 | | Divya Rao | 2008-10-05 | +--------------+------------+ 3 rows in set (0.00 sec)
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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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.
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")
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]
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
lst, key๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q1.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10 20 30 20 40 20, 20 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def linear_search(lst, key): function is defined (remembered), not run yet | ||
| 2 | 8 | 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 |
| 3 | 9 | key = int(input("Enter element to search: ")) | key = 20 | Enter element to search: 20 |
| 4 | 11 | result = linear_search(lst, key) | result = [1, 3, 5] | |
| โก Python jumps INTO function linear_search(lst=[10, 20, 30, 20, 40, 20], key=20) | ||||
| 5 | 2 | positions = [] | positions = [] | |
| 6 | 3 | for i in range(len(lst)): next item taken | i = 0 | |
| 7 | 4 | if lst[i] == key: condition is FALSE โ skips this block | ||
| 8 | 3 | for i in range(len(lst)): next item taken | i = 1 | |
| 9 | 4 | if lst[i] == key: condition is TRUE โ enters the block | ||
| 10 | 5 | positions.append(i) | positions = [1] | |
| 11 | 3 | for i in range(len(lst)): next item taken | i = 2 | |
| 12 | 4 | if lst[i] == key: condition is FALSE โ skips this block | ||
| 13 | 3 | for i in range(len(lst)): next item taken | i = 3 | |
| 14 | 4 | if lst[i] == key: condition is TRUE โ enters the block | ||
| 15 | 5 | positions.append(i) | positions = [1, 3] | |
| 16 | 3 | for i in range(len(lst)): next item taken | i = 4 | |
| 17 | 4 | if lst[i] == key: condition is FALSE โ skips this block | ||
| 18 | 3 | for i in range(len(lst)): next item taken | i = 5 | |
| 19 | 4 | if lst[i] == key: condition is TRUE โ enters the block | ||
| 20 | 5 | positions.append(i) | positions = [1, 3, 5] | |
| 21 | 3 | for i in range(len(lst)): no items left โ loop ends | ||
| 22 | 6 | return positions | ||
โฌ
function linear_search() ends and returns [1, 3, 5] to the caller | ||||
| 23 | 12 | if result: condition is TRUE โ enters the block | ||
| 24 | 13 | print(key, "found", len(result), "time(s) at position(s):", result) | 20 found 3 time(s) at position(s): [1, 3, 5] | |
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")
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]
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
lst, key๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q2.py. - Press F5 (Run โ Run Module).
- When the program asks, type 5 12 8 20 3, 12 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def binary_search(lst, key): function is defined (remembered), not run yet | ||
| 2 | 22 | lst = sorted(map(int, input("Enter list elements: ").split())) | lst = [3, 5, 8, 12, 20] | Enter list elements: 5 12 8 20 3 |
| 3 | 23 | key = int(input("Enter element to search: ")) | key = 12 | Enter element to search: 12 |
| 4 | 24 | print("Sorted list:", lst) | Sorted list: [3, 5, 8, 12, 20] | |
| 5 | 26 | result = binary_search(lst, key) | result = [3] | |
| โก Python jumps INTO function binary_search(lst=[3, 5, 8, 12, 20], key=12) | ||||
| 6 | 2 | low, high = 0, len(lst) - 1 | low = 0, high = 4 | |
| 7 | 3 | positions = [] | positions = [] | |
| 8 | 4 | while low <= high: condition is TRUE โ enters the block | ||
| 9 | 5 | mid = (low + high) // 2 | mid = 2 | |
| 10 | 6 | if lst[mid] == key: condition is FALSE โ skips this block | ||
| 11 | 16 | elif lst[mid] < key: condition is TRUE โ enters the block | ||
| 12 | 17 | low = mid + 1 | low = 3 | |
| 13 | 4 | while low <= high: condition is TRUE โ enters the block | ||
| 14 | 5 | mid = (low + high) // 2 | mid = 3 | |
| 15 | 6 | if lst[mid] == key: condition is TRUE โ enters the block | ||
| 16 | 7 | positions.append(mid) | positions = [3] | |
| 17 | 9 | i = mid - 1 | i = 2 | |
| 18 | 10 | while i >= 0 and lst[i] == key: condition is FALSE โ loop ends | ||
| 19 | 12 | i = mid + 1 | i = 4 | |
| 20 | 13 | while i < len(lst) and lst[i] == key: condition is FALSE โ loop ends | ||
| 21 | 15 | break | ||
| 22 | 20 | return sorted(positions) | ||
โฌ
function binary_search() ends and returns [3] to the caller | ||||
| 23 | 27 | if result: condition is TRUE โ enters the block | ||
| 24 | 28 | print(key, "found", len(result), "time(s) at position(s):", result) | 12 found 1 time(s) at position(s): [3] | |
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))
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]
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
lst๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q3.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1 2 3 4 5 6 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def modify(lst): function is defined (remembered), not run yet | ||
| 2 | 9 | 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 |
| 3 | 10 | print("Original list :", lst) | Original list : [1, 2, 3, 4, 5, 6] | |
| 4 | 11 | 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]) | ||||
| 5 | 2 | for i in range(len(lst)): next item taken | i = 0 | |
| 6 | 3 | if lst[i] % 2 == 0: condition is FALSE โ skips this block | ||
| 7 | 6 | lst[i] = lst[i] * 2 | lst = [2, 2, 3, 4, 5, 6] | |
| 8 | 2 | for i in range(len(lst)): next item taken | i = 1 | |
| 9 | 3 | if lst[i] % 2 == 0: condition is TRUE โ enters the block | ||
| 10 | 4 | lst[i] = lst[i] / 2 | lst = [2, 1.0, 3, 4, 5, 6] | |
| 11 | 2 | for i in range(len(lst)): next item taken | i = 2 | |
| 12 | 3 | if lst[i] % 2 == 0: condition is FALSE โ skips this block | ||
| 13 | 6 | lst[i] = lst[i] * 2 | lst = [2, 1.0, 6, 4, 5, 6] | |
| 14 | 2 | for i in range(len(lst)): next item taken | i = 3 | |
| 15 | 3 | if lst[i] % 2 == 0: condition is TRUE โ enters the block | ||
| 16 | 4 | lst[i] = lst[i] / 2 | lst = [2, 1.0, 6, 2.0, 5, 6] | |
| 17 | 2 | for i in range(len(lst)): next item taken | i = 4 | |
| 18 | 3 | if lst[i] % 2 == 0: condition is FALSE โ skips this block | ||
| 19 | 6 | lst[i] = lst[i] * 2 | lst = [2, 1.0, 6, 2.0, 10, 6] | |
| 20 | 2 | for i in range(len(lst)): next item taken | i = 5 | |
| 21 | 3 | if lst[i] % 2 == 0: condition is TRUE โ enters the block | ||
| 22 | 4 | lst[i] = lst[i] / 2 | lst = [2, 1.0, 6, 2.0, 10, 3.0] | |
| 23 | 2 | for i in range(len(lst)): no items left โ loop ends | ||
| 24 | 7 | return lst | ||
โฌ
function modify() ends and returns [2, 1.0, 6, 2.0, 10, 3.0] to the caller | ||||
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)
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
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
n, t๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q4.py. - Press F5 (Run โ Run Module).
- When the program asks, type 5, 2, 4, 6, 3, 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def count_even_odd(t): function is defined (remembered), not run yet | ||
| 2 | 10 | n = int(input("How many numbers? ")) | n = 5 | How many numbers? 5 |
| 3 | 11 | 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>) | ||||
| 4 | 11 | 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>) | ||||
| 5 | 11 | 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>) | ||||
| 6 | 11 | 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>) | ||||
| 7 | 11 | 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>) | ||||
| 8 | 11 | 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>) | ||||
| 9 | 11 | t = tuple(int(input("Enter number: ")) for _ in range(n)) | ||
โฌ
function <genexpr>() ends and returns None to the caller | ||||
| 10 | 13 | e, o = count_even_odd(t) | e = 3, o = 2 | |
| โก Python jumps INTO function count_even_odd(t=(2, 4, 6, 3, 5)) | ||||
| 11 | 2 | even = odd = 0 | even = 0, odd = 0 | |
| 12 | 3 | for num in t: next item taken | num = 2 | |
| 13 | 4 | if num % 2 == 0: condition is TRUE โ enters the block | ||
| 14 | 5 | even += 1 | even = 1 | |
| 15 | 3 | for num in t: next item taken | num = 4 | |
| 16 | 4 | if num % 2 == 0: condition is TRUE โ enters the block | ||
| 17 | 5 | even += 1 | even = 2 | |
| 18 | 3 | for num in t: next item taken | num = 6 | |
| 19 | 4 | 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
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))
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'}
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
n, key, value, k, v๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q5.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def update_dict(d, key, value): function is defined (remembered), not run yet | ||
| 2 | 10 | d = {} | d = {} | |
| 3 | 11 | n = int(input("How many key-value pairs to enter? ")) | n = 3 | How many key-value pairs to enter? 3 |
| 4 | 12 | for i in range(n): next item taken | i = 0 | |
| 5 | 13 | k = input("Enter key: ") | k = '1' | Enter key: 1 |
| 6 | 14 | v = input("Enter value: ") | v = 'Amit' | Enter value: Amit |
| 7 | 15 | d[k] = v | d = {'1': 'Amit'} | |
| 8 | 12 | for i in range(n): next item taken | i = 1 | |
| 9 | 13 | k = input("Enter key: ") | k = '2' | Enter key: 2 |
| 10 | 14 | v = input("Enter value: ") | v = 'Sara' | Enter value: Sara |
| 11 | 15 | d[k] = v | d = {'1': 'Amit', '2': 'Sara'} | |
| 12 | 12 | for i in range(n): next item taken | i = 2 | |
| 13 | 13 | k = input("Enter key: ") | k = '3' | Enter key: 3 |
| 14 | 14 | v = input("Enter value: ") | v = 'Rahul' | Enter value: Rahul |
| 15 | 15 | d[k] = v | d = {'1': 'Amit', '2': 'Sara', '3': 'Rahul'} | |
| 16 | 12 | for i in range(n): no items left โ loop ends | ||
| 17 | 17 | print("Dictionary:", d) | Dictionary: {'1': 'Amit', '2': 'Sara', '3': 'Rahul'} | |
| 18 | 18 | key = input("Enter key to update: ") | key = '2' | Enter key to update: 2 |
| 19 | 19 | value = input("Enter new value: ") | value = 'Sara-Updated' | Enter new value: Sara-Updated |
| 20 | 20 | 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') | ||||
| 21 | 2 | if key in d: condition is TRUE โ enters the block | ||
| 22 | 3 | d[key] = value | d = {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'} | |
| 23 | 4 | print("Updated successfully!") | Updated successfully! | |
| 24 | 8 | return d | ||
โฌ
function update_dict() ends and returns {'1': 'Amit', '2': 'Sara-Updated', '3': 'Rahul'} to the caller | ||||
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))
Enter a string: Educational Excellence
Number of vowels = 10
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
s๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q6.py. - Press F5 (Run โ Run Module).
- When the program asks, type Educational Excellence (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def count_vowels(s): function is defined (remembered), not run yet | ||
| 2 | 8 | s = input("Enter a string: ") | s = 'Educational Excellence' | Enter a string: Educational Excellence |
| 3 | 9 | print("Number of vowels =", count_vowels(s)) | Number of vowels = 10 | |
| โก Python jumps INTO function count_vowels(s='Educational Excellence') | ||||
| 4 | 2 | count = 0 | count = 0 | |
| 5 | 3 | for ch in s.lower(): next item taken | ch = 'e' | |
| 6 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 7 | 5 | count += 1 | count = 1 | |
| 8 | 3 | for ch in s.lower(): next item taken | ch = 'd' | |
| 9 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 10 | 3 | for ch in s.lower(): next item taken | ch = 'u' | |
| 11 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 12 | 5 | count += 1 | count = 2 | |
| 13 | 3 | for ch in s.lower(): next item taken | ch = 'c' | |
| 14 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 15 | 3 | for ch in s.lower(): next item taken | ch = 'a' | |
| 16 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 17 | 5 | count += 1 | count = 3 | |
| 18 | 3 | for ch in s.lower(): next item taken | ch = 't' | |
| 19 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 20 | 3 | for ch in s.lower(): next item taken | ch = 'i' | |
| 21 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 22 | 5 | count += 1 | count = 4 | |
| 23 | 3 | for ch in s.lower(): next item taken | ch = 'o' | |
| 24 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 25 | 5 | count += 1 | count = 5 | |
| 26 | 3 | for ch in s.lower(): next item taken | ch = 'n' | |
| 27 | 4 | if ch in 'aeiou': condition is FALSE โ skips this block | ||
| 28 | 3 | for ch in s.lower(): next item taken | ch = 'a' | |
| 29 | 4 | if ch in 'aeiou': condition is TRUE โ enters the block | ||
| 30 | 5 | count += 1 | count = 6 | |
| 31 | 3 | 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'
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())
How many times to roll the dice? 3
Roll 1 : 1
Roll 2 : 3
Roll 3 : 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 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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q7.py. - Press F5 (Run โ Run Module).
- When the program asks, type 3 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import random | ||
| 2 | 3 | def roll_dice(): function is defined (remembered), not run yet | ||
| 3 | 6 | n = int(input("How many times to roll the dice? ")) | n = 3 | How many times to roll the dice? 3 |
| 4 | 7 | for i in range(n): next item taken | i = 0 | |
| 5 | 8 | print("Roll", i + 1, ":", roll_dice()) | Roll 1 : 1 | |
| โก Python jumps INTO function roll_dice() | ||||
| 6 | 4 | return random.randint(1, 6) | ||
โฌ
function roll_dice() ends and returns 1 to the caller | ||||
| 7 | 7 | for i in range(n): next item taken | i = 1 | |
| 8 | 8 | print("Roll", i + 1, ":", roll_dice()) | Roll 2 : 3 | |
| โก Python jumps INTO function roll_dice() | ||||
| 9 | 4 | return random.randint(1, 6) | ||
โฌ
function roll_dice() ends and returns 3 to the caller | ||||
| 10 | 7 | for i in range(n): next item taken | i = 2 | |
| 11 | 8 | print("Roll", i + 1, ":", roll_dice()) | Roll 3 : 5 | |
| โก Python jumps INTO function roll_dice() | ||||
| 12 | 4 | return random.randint(1, 6) | ||
โฌ
function roll_dice() ends and returns 5 to the caller | ||||
| 13 | 7 | for i in range(n): no items left โ loop ends | ||
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")
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
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
ch, b, p๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q8.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import math | ||
| 2 | 3 | def menu(): function is defined (remembered), not run yet | ||
| 3 | 10 | while True: condition is TRUE โ enters the block | ||
| 4 | 11 | menu() | ||
| โก Python jumps INTO function menu() | ||||
| 5 | 4 | 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 | ||||
| 6 | 12 | ch = int(input("Enter choice: ")) | ch = 1 | Enter choice: 1 |
| 7 | 13 | if ch == 0: condition is FALSE โ skips this block | ||
| 8 | 15 | elif ch == 1: condition is TRUE โ enters the block | ||
| 9 | 16 | print(math.sqrt(float(input("Enter number: ")))) | Enter number: 81 9.0 | |
| 10 | 10 | while True: condition is TRUE โ enters the block | ||
| 11 | 11 | menu() | ||
| โก Python jumps INTO function menu() | ||||
| 12 | 4 | 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 | ||||
| 13 | 12 | ch = int(input("Enter choice: ")) | ch = 3 | Enter choice: 3 |
| 14 | 13 | if ch == 0: condition is FALSE โ skips this block | ||
| 15 | 15 | elif ch == 1: condition is FALSE โ skips this block | ||
| 16 | 17 | elif ch == 2: condition is FALSE โ skips this block | ||
| 17 | 20 | elif ch == 3: condition is TRUE โ enters the block | ||
| 18 | 21 | print(math.factorial(int(input("Enter number: ")))) | Enter number: 5 120 | |
| 19 | 10 | while True: condition is TRUE โ enters the block | ||
| 20 | 11 | menu() | ||
| โก Python jumps INTO function menu() | ||||
| 21 | 4 | 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 | ||||
| 22 | 12 | ch = int(input("Enter choice: ")) | ch = 7 | Enter choice: 7 |
| 23 | 13 | if ch == 0: condition is FALSE โ skips this block | ||
| 24 | 15 | elif ch == 1: condition is FALSE โ skips this block | ||
| 25 | 17 | elif ch == 2: condition is FALSE โ skips this block | ||
| 26 | 20 | 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
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])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q9.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | s = "Hello Python Programming" | s = 'Hello Python Programming' | |
| 2 | 3 | print("Original :", s) | Original : Hello Python Programming | |
| 3 | 4 | print("upper() :", s.upper()) | upper() : HELLO PYTHON PROGRAMMING | |
| 4 | 5 | print("lower() :", s.lower()) | lower() : hello python programming | |
| 5 | 6 | print("len() :", len(s)) | len() : 24 | |
| 6 | 7 | print("find('Py') :", s.find("Py")) | find('Py') : 6 | |
| 7 | 8 | print("count('m') :", s.count("m")) | count('m') : 2 | |
| 8 | 9 | print("replace() :", s.replace("Python", "World")) | replace() : Hello World Programming | |
| 9 | 10 | print("split() :", s.split()) | split() : ['Hello', 'Python', 'Programming'] | |
| 10 | 11 | print("strip() :", " spaced ".strip()) | strip() : spaced | |
| 11 | 12 | print("capitalize():", s.capitalize()) | capitalize(): Hello python programming | |
| 12 | 13 | print("title() :", s.title()) | title() : Hello Python Programming | |
| 13 | 14 | print("isalpha() :", "Hello".isalpha()) | isalpha() : True | |
| 14 | 15 | print("isdigit() :", "123".isdigit()) | isdigit() : True | |
| 15 | 16 | print("startswith():", s.startswith("Hello")) | startswith(): True | |
| 16 | 17 | print("endswith() :", s.endswith("ing")) | endswith() : True | |
| 17 | 18 | print("index() :", s.index("Python")) | index() : 6 | |
| 18 | 19 | print("swapcase() :", s.swapcase()) | swapcase() : hELLO pYTHON pROGRAMMING | |
| 19 | 20 | print("join() :", "-".join(["a", "b", "c"])) | join() : a-b-c | |
| 20 | 21 | print("partition() :", s.partition("Python")) | partition() : ('Hello ', 'Python', ' Programming') | |
| 21 | 22 | print("slicing s[0:5]:", s[0:5]) | slicing s[0:5]: Hello |
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")
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
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
ch, name๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q10.py. - Press F5 (Run โ Run Module).
- When the program asks, type 2, Sara, 1, Rahul, 2, Rahul, 3 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | students = {"Amit": "9876543210", "Sara": "9123456780", "Rahul": "9988776655"} | students = {'Amit': '9876543210', 'Sara': '9123456780', 'Rahul': '9988776655'} | |
| 2 | 3 | while True: condition is TRUE โ enters the block | ||
| 3 | 4 | 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 | |
| 4 | 5 | ch = int(input("Enter choice: ")) | ch = 2 | Enter choice: 2 |
| 5 | 6 | if ch == 1: condition is FALSE โ skips this block | ||
| 6 | 13 | elif ch == 2: condition is TRUE โ enters the block | ||
| 7 | 14 | name = input("Enter name to search: ") | name = 'Sara' | Enter name to search: Sara |
| 8 | 15 | if name in students: condition is TRUE โ enters the block | ||
| 9 | 16 | print("Phone number:", students[name]) | Phone number: 9123456780 | |
| 10 | 3 | while True: condition is TRUE โ enters the block | ||
| 11 | 4 | 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 | |
| 12 | 5 | ch = int(input("Enter choice: ")) | ch = 1 | Enter choice: 1 |
| 13 | 6 | if ch == 1: condition is TRUE โ enters the block | ||
| 14 | 7 | name = input("Enter name to delete: ") | name = 'Rahul' | Enter name to delete: Rahul |
| 15 | 8 | if name in students: condition is TRUE โ enters the block | ||
| 16 | 9 | del students[name] | students = {'Amit': '9876543210', 'Sara': '9123456780'} | |
| 17 | 10 | print("Deleted successfully") | Deleted successfully | |
| 18 | 3 | while True: condition is TRUE โ enters the block | ||
| 19 | 4 | 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 | |
| 20 | 5 | ch = int(input("Enter choice: ")) | ch = 2 | Enter choice: 2 |
| 21 | 6 | if ch == 1: condition is FALSE โ skips this block | ||
| 22 | 13 | elif ch == 2: condition is TRUE โ enters the block | ||
| 23 | 14 | name = input("Enter name to search: ") | Enter name to search: Rahul | |
| 24 | 15 | if name in students: condition is FALSE โ skips this block | ||
| 25 | 18 | print("Name not found") | Name not found | |
| 26 | 3 | while True: condition is TRUE โ enters the block | ||
| 27 | 4 | 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 | |
| 28 | 5 | ch = int(input("Enter choice: ")) | ch = 3 | Enter choice: 3 |
| 29 | 6 | if ch == 1: condition is FALSE โ skips this block | ||
| 30 | 13 | elif ch == 2: condition is FALSE โ skips this block | ||
| 31 | 19 | elif ch == 3: condition is TRUE โ enters the block | ||
| 32 | 20 | break |
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))
This#is#line#one
This#is#line#two
Python#file#handling
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q11.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | with open("data.txt", "w") as f: | f = file object "data.txt" (mode w) | |
| 2 | 2 | f.write("This is line one\nThis is line two\nPython file handling") | ||
| 3 | 1 | with open("data.txt", "w") as f:block over โ file closed automatically | ||
| 4 | 4 | with open("data.txt", "r") as f: | f = file object "data.txt" (mode r) | |
| 5 | 5 | for line in f: next item taken | line = 'This is line one\n' | |
| 6 | 6 | words = line.split() | words = ['This', 'is', 'line', 'one'] | |
| 7 | 7 | print("#".join(words)) | This#is#line#one | |
| 8 | 5 | for line in f: next item taken | line = 'This is line two\n' | |
| 9 | 6 | words = line.split() | words = ['This', 'is', 'line', 'two'] | |
| 10 | 7 | print("#".join(words)) | This#is#line#two | |
| 11 | 5 | for line in f: next item taken | line = 'Python file handling' | |
| 12 | 6 | words = line.split() | words = ['Python', 'file', 'handling'] | |
| 13 | 7 | print("#".join(words)) | Python#file#handling | |
| 14 | 5 | for line in f: no items left โ loop ends | ||
| 15 | 4 | with open("data.txt", "r") as f:block over โ file closed automatically |
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)
Vowels : 16
Consonants : 28
Uppercase : 3
Lowercase : 41
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q12.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | with open("data.txt", "r") as f: | f = file object "data.txt" (mode r) | |
| 2 | 2 | content = f.read() | content = 'This is line one\nThis is line two\nPython file handling' | |
| 3 | 1 | with open("data.txt", "r") as f:block over โ file closed automatically | ||
| 4 | 4 | vowels = consonants = upper = lower = 0 | vowels = 0, consonants = 0, upper = 0, lower = 0 | |
| 5 | 5 | for ch in content: next item taken | ch = 'T' | |
| 6 | 6 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 7 | 7 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 8 | 10 | consonants += 1 | consonants = 1 | |
| 9 | 11 | if ch.isupper(): condition is TRUE โ enters the block | ||
| 10 | 12 | upper += 1 | upper = 1 | |
| 11 | 5 | for ch in content: next item taken | ch = 'h' | |
| 12 | 6 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 13 | 7 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 14 | 10 | consonants += 1 | consonants = 2 | |
| 15 | 11 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 16 | 14 | lower += 1 | lower = 1 | |
| 17 | 5 | for ch in content: next item taken | ch = 'i' | |
| 18 | 6 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 19 | 7 | if ch.lower() in 'aeiou': condition is TRUE โ enters the block | ||
| 20 | 8 | vowels += 1 | vowels = 1 | |
| 21 | 11 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 22 | 14 | lower += 1 | lower = 2 | |
| 23 | 5 | for ch in content: next item taken | ch = 's' | |
| 24 | 6 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 25 | 7 | if ch.lower() in 'aeiou': condition is FALSE โ skips this block | ||
| 26 | 10 | consonants += 1 | consonants = 3 | |
| 27 | 11 | if ch.isupper(): condition is FALSE โ skips this block | ||
| 28 | 14 | lower += 1 | lower = 3 | |
| 29 | 5 | for ch in content: next item taken | ch = ' ' | |
| 30 | 6 | if ch.isalpha(): condition is FALSE โ skips this block | ||
| 31 | 5 | for ch in content: next item taken | ch = 'i' | |
| 32 | 6 | 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'
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")
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
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
ch๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q13.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1, 2, 3, 4, 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | with open("TOY.txt", "w") as f: | f = file object "TOY.txt" (mode w) | |
| 2 | 2 | f.write("Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam") | ||
| 3 | 1 | with open("TOY.txt", "w") as f:block over โ file closed automatically | ||
| 4 | 4 | while True: condition is TRUE โ enters the block | ||
| 5 | 5 | 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 | |
| 6 | 6 | ch = int(input("Enter choice: ")) | ch = 1 | Enter choice: 1 |
| 7 | 7 | if ch == 5: condition is FALSE โ skips this block | ||
| 8 | 9 | with open("TOY.txt", "r") as f: | f = file object "TOY.txt" (mode r) | |
| 9 | 10 | content = f.read() | content = 'Hello 123 World\nPython 456 Programming\nCBSE 2027 Exam' | |
| 10 | 9 | with open("TOY.txt", "r") as f:block over โ file closed automatically | ||
| 11 | 11 | if ch == 1: condition is TRUE โ enters the block | ||
| 12 | 12 | print("Spaces:", content.count(" ")) | Spaces: 6 | |
| 13 | 4 | while True: condition is TRUE โ enters the block | ||
| 14 | 5 | 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 | |
| 15 | 6 | ch = int(input("Enter choice: ")) | ch = 2 | Enter choice: 2 |
| 16 | 7 | if ch == 5: condition is FALSE โ skips this block | ||
| 17 | 9 | with open("TOY.txt", "r") as f: | ||
| 18 | 10 | content = f.read() | ||
| 19 | 9 | with open("TOY.txt", "r") as f:block over โ file closed automatically | ||
| 20 | 11 | if ch == 1: condition is FALSE โ skips this block | ||
| 21 | 13 | elif ch == 2: condition is TRUE โ enters the block | ||
| 22 | 14 | 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>) | ||||
| 23 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | c = 'H' | |
| 24 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | c = 'e' | |
| 25 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | c = 'l' | |
| 26 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | ||
| 27 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | c = 'o' | |
| 28 | 14 | print("Digits:", sum(1 for c in content if c.isdigit())) | c = ' ' | |
| 29 | 14 | 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'
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())
Lines without 'a' written to filtered.txt
kvs school
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q14.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | with open("source.txt", "w") as f: | f = file object "source.txt" (mode w) | |
| 2 | 2 | f.write("apple is red\nkvs school\ntoday is monday\nno match here") | ||
| 3 | 1 | with open("source.txt", "w") as f:block over โ file closed automatically | ||
| 4 | 4 | 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) | |
| 5 | 5 | for line in fin: next item taken | line = 'apple is red\n' | |
| 6 | 6 | if 'a' not in line: condition is FALSE โ skips this block | ||
| 7 | 5 | for line in fin: next item taken | line = 'kvs school\n' | |
| 8 | 6 | if 'a' not in line: condition is TRUE โ enters the block | ||
| 9 | 7 | fout.write(line) | ||
| 10 | 5 | for line in fin: next item taken | line = 'today is monday\n' | |
| 11 | 6 | if 'a' not in line: condition is FALSE โ skips this block | ||
| 12 | 5 | for line in fin: next item taken | line = 'no match here' | |
| 13 | 6 | if 'a' not in line: condition is FALSE โ skips this block | ||
| 14 | 5 | for line in fin: no items left โ loop ends | ||
| 15 | 4 | with open("source.txt", "r") as fin, open("filtered.txt", "w") as fout:block over โ file closed automatically | ||
| 16 | 9 | print("Lines without 'a' written to filtered.txt") | Lines without 'a' written to filtered.txt | |
| 17 | 10 | with open("filtered.txt", "r") as f: | f = file object "filtered.txt" (mode r) | |
| 18 | 11 | print(f.read()) | kvs school | |
| 19 | 10 | with open("filtered.txt", "r") as f:block over โ file closed automatically |
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")
Enter roll number to search: 2
Name: Sara
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
roll๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q15.py. - Press F5 (Run โ Run Module).
- When the program asks, type 2 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pickle | ||
| 2 | 3 | with open("student.dat", "wb") as f: | f = file object "student.dat" (mode wb) | |
| 3 | 4 | records = [(1, "Amit"), (2, "Sara"), (3, "Rahul")] | records = [(1, 'Amit'), (2, 'Sara'), (3, 'Rahul')] | |
| 4 | 5 | for rec in records: next item taken | rec = (1, 'Amit') | |
| 5 | 6 | pickle.dump(rec, f) | ||
| 6 | 5 | for rec in records: next item taken | rec = (2, 'Sara') | |
| 7 | 6 | pickle.dump(rec, f) | ||
| 8 | 5 | for rec in records: next item taken | rec = (3, 'Rahul') | |
| 9 | 6 | pickle.dump(rec, f) | ||
| 10 | 5 | for rec in records: no items left โ loop ends | ||
| 11 | 3 | with open("student.dat", "wb") as f:block over โ file closed automatically | ||
| 12 | 8 | roll = int(input("Enter roll number to search: ")) | roll = 2 | Enter roll number to search: 2 |
| 13 | 9 | found = False | found = False | |
| 14 | 10 | with open("student.dat", "rb") as f: | f = file object "student.dat" (mode rb) | |
| 15 | 11 | while True: condition is TRUE โ enters the block | ||
| 16 | 12 | try: | ||
| 17 | 13 | rec = pickle.load(f) | rec = (1, 'Amit') | |
| 18 | 14 | if rec[0] == roll: condition is FALSE โ skips this block | ||
| 19 | 11 | while True: condition is TRUE โ enters the block | ||
| 20 | 12 | try: | ||
| 21 | 13 | rec = pickle.load(f) | rec = (2, 'Sara') | |
| 22 | 14 | if rec[0] == roll: condition is TRUE โ enters the block | ||
| 23 | 15 | print("Name:", rec[1]) | Name: Sara | |
| 24 | 16 | found = True | found = True | |
| 25 | 17 | break | ||
| 26 | 10 | with open("student.dat", "rb") as f:block over โ file closed automatically | ||
| 27 | 21 | if not found: condition is FALSE โ skips this block |
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
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)}
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
roll, name, marks๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q16.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pickle | ||
| 2 | 3 | with open("marks.dat", "wb") as f: | f = file object "marks.dat" (mode wb) | |
| 3 | 4 | for i in range(5): next item taken | i = 0 | |
| 4 | 5 | roll = int(input("Roll number: ")) | roll = 1 | Roll number: 1 |
| 5 | 6 | name = input("Name: ") | name = 'Asmita' | Name: Asmita |
| 6 | 7 | marks = float(input("Marks: ")) | marks = 89.7 | Marks: 89.7 |
| 7 | 8 | student = {roll: (name, marks)} | student = {1: ('Asmita', 89.7)} | |
| 8 | 9 | pickle.dump(student, f) | ||
| 9 | 4 | for i in range(5): next item taken | i = 1 | |
| 10 | 5 | roll = int(input("Roll number: ")) | roll = 2 | Roll number: 2 |
| 11 | 6 | name = input("Name: ") | name = 'Swati' | Name: Swati |
| 12 | 7 | marks = float(input("Marks: ")) | marks = 87.5 | Marks: 87.5 |
| 13 | 8 | student = {roll: (name, marks)} | student = {2: ('Swati', 87.5)} | |
| 14 | 9 | pickle.dump(student, f) | ||
| 15 | 4 | for i in range(5): next item taken | i = 2 | |
| 16 | 5 | roll = int(input("Roll number: ")) | roll = 3 | Roll number: 3 |
| 17 | 6 | name = input("Name: ") | name = 'Rohan' | Name: Rohan |
| 18 | 7 | marks = float(input("Marks: ")) | marks = 76.0 | Marks: 76 |
| 19 | 8 | student = {roll: (name, marks)} | student = {3: ('Rohan', 76.0)} | |
| 20 | 9 | pickle.dump(student, f) | ||
| 21 | 4 | for i in range(5): next item taken | i = 3 | |
| 22 | 5 | roll = int(input("Roll number: ")) | roll = 4 | Roll number: 4 |
| 23 | 6 | name = input("Name: ") | name = 'Kavya' | Name: Kavya |
| 24 | 7 | marks = float(input("Marks: ")) | marks = 92.5 | Marks: 92.5 |
| 25 | 8 | student = {roll: (name, marks)} | student = {4: ('Kavya', 92.5)} | |
| 26 | 9 | pickle.dump(student, f) | ||
| 27 | 4 | for i in range(5): next item taken | i = 4 | |
| 28 | 5 | roll = int(input("Roll number: ")) | roll = 5 | Roll number: 5 |
| 29 | 6 | name = input("Name: ") | name = 'Arjun' | Name: Arjun |
| 30 | 7 | marks = float(input("Marks: ")) | marks = 68.0 | Marks: 68 |
| 31 | 8 | student = {roll: (name, marks)} | student = {5: ('Arjun', 68.0)} | |
| 32 | 9 | 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)}
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")
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
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
search_id, n, uid, pwd๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q17.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import csv | ||
| 2 | 3 | with open("login.csv", "w", newline="") as f: | f = file object "login.csv" (mode w) | |
| 3 | 4 | writer = csv.writer(f) | writer = <_csv.writer object at 0x7f47f978d8a0> | |
| 4 | 5 | n = int(input("How many records? ")) | n = 3 | How many records? 3 |
| 5 | 6 | for i in range(n): next item taken | i = 0 | |
| 6 | 7 | uid = input("Enter user-id: ") | uid = 'admin' | Enter user-id: admin |
| 7 | 8 | pwd = input("Enter password: ") | pwd = 'kvs@123' | Enter password: kvs@123 |
| 8 | 9 | writer.writerow([uid, pwd]) | ||
| 9 | 6 | for i in range(n): next item taken | i = 1 | |
| 10 | 7 | uid = input("Enter user-id: ") | uid = 'student' | Enter user-id: student |
| 11 | 8 | pwd = input("Enter password: ") | pwd = 'pass@26' | Enter password: pass@26 |
| 12 | 9 | writer.writerow([uid, pwd]) | ||
| 13 | 6 | for i in range(n): next item taken | i = 2 | |
| 14 | 7 | uid = input("Enter user-id: ") | uid = 'teacher' | Enter user-id: teacher |
| 15 | 8 | pwd = input("Enter password: ") | pwd = 'tch#2026' | Enter password: tch#2026 |
| 16 | 9 | writer.writerow([uid, pwd]) | ||
| 17 | 6 | for i in range(n): no items left โ loop ends | ||
| 18 | 3 | with open("login.csv", "w", newline="") as f:block over โ file closed automatically | ||
| 19 | 11 | search_id = input("\nEnter user-id to search: ") | search_id = 'admin' | Enter user-id to search: admin |
| 20 | 12 | with open("login.csv", "r", newline="") as f: | f = file object "login.csv" (mode r) | |
| 21 | 13 | reader = csv.reader(f) | reader = <_csv.reader object at 0x7f47f289e3b0> | |
| 22 | 14 | found = False | found = False | |
| 23 | 15 | for row in reader: next item taken | row = ['admin', 'kvs@123'] | |
| 24 | 16 | if row[0] == search_id: condition is TRUE โ enters the block | ||
| 25 | 17 | print("Password:", row[1]) | Password: kvs@123 | |
| 26 | 18 | found = True | found = True | |
| 27 | 19 | break | ||
| 28 | 20 | if not found: condition is FALSE โ skips this block | ||
| 29 | 12 | with open("login.csv", "r", newline="") as f:block over โ file closed automatically |
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")
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
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
did, ch, name, city๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q18.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import csv | ||
| 2 | 3 | def create_csv(): function is defined (remembered), not run yet | ||
| 3 | 12 | def search_csv(): function is defined (remembered), not run yet | ||
| 4 | 24 | while True: condition is TRUE โ enters the block | ||
| 5 | 25 | 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 | |
| 6 | 26 | ch = int(input("Enter choice: ")) | ch = 1 | Enter choice: 1 |
| 7 | 27 | if ch == 1: condition is TRUE โ enters the block | ||
| 8 | 28 | create_csv() | ||
| โก Python jumps INTO function create_csv() | ||||
| 9 | 4 | with open("dept.csv", "a", newline="") as f: | f = file object "dept.csv" (mode a) | |
| 10 | 5 | writer = csv.writer(f) | writer = <_csv.writer object at 0x7f74f51e58a0> | |
| 11 | 6 | did = input("Enter dept-id: ") | did = 'D01' | Enter dept-id: D01 |
| 12 | 7 | name = input("Enter name: ") | name = 'Admin' | Enter name: Admin |
| 13 | 8 | city = input("Enter city: ") | city = 'Delhi' | Enter city: Delhi |
| 14 | 9 | writer.writerow([did, name, city]) | ||
| 15 | 4 | with open("dept.csv", "a", newline="") as f:block over โ file closed automatically | ||
| 16 | 10 | print("Record added") | Record added | |
โฌ
function create_csv() ends and returns None to the caller | ||||
| 17 | 24 | while True: condition is TRUE โ enters the block | ||
| 18 | 25 | 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 | |
| 19 | 26 | ch = int(input("Enter choice: ")) | Enter choice: 1 | |
| 20 | 27 | if ch == 1: condition is TRUE โ enters the block | ||
| 21 | 28 | create_csv() | ||
| โก Python jumps INTO function create_csv() | ||||
| 22 | 4 | with open("dept.csv", "a", newline="") as f: | f = file object "dept.csv" (mode a) | |
| 23 | 5 | writer = csv.writer(f) | writer = <_csv.writer object at 0x7f74f51e58a0> | |
| 24 | 6 | did = input("Enter dept-id: ") | did = 'D02' | Enter dept-id: D02 |
| 25 | 7 | name = input("Enter name: ") | name = 'Accounts' | Enter name: Accounts |
| 26 | 8 | city = input("Enter city: ") | city = 'Mumbai' | Enter city: Mumbai |
| 27 | 9 | writer.writerow([did, name, city]) | ||
| 28 | 4 | with open("dept.csv", "a", newline="") as f:block over โ file closed automatically | ||
| 29 | 10 | 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']
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")
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
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
ch๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q19.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | stack = [] | stack = [] | |
| 2 | 3 | def push(item): function is defined (remembered), not run yet | ||
| 3 | 7 | def pop(): function is defined (remembered), not run yet | ||
| 4 | 13 | while True: condition is TRUE โ enters the block | ||
| 5 | 14 | print("\n1.PUSH 2.POP 3.Display 4.Exit") | 1.PUSH 2.POP 3.Display 4.Exit | |
| 6 | 15 | ch = int(input("Enter choice: ")) | ch = 1 | Enter choice: 1 |
| 7 | 16 | if ch == 1: condition is TRUE โ enters the block | ||
| 8 | 17 | push(input("Enter item to push: ")) | stack = ['10'] | Enter item to push: 10 |
| โก Python jumps INTO function push(item='10') | ||||
| 9 | 4 | stack.append(item) | ||
| 10 | 5 | print(item, "pushed to stack") | 10 pushed to stack | |
โฌ
function push() ends and returns None to the caller | ||||
| 11 | 13 | while True: condition is TRUE โ enters the block | ||
| 12 | 14 | print("\n1.PUSH 2.POP 3.Display 4.Exit") | 1.PUSH 2.POP 3.Display 4.Exit | |
| 13 | 15 | ch = int(input("Enter choice: ")) | Enter choice: 1 | |
| 14 | 16 | if ch == 1: condition is TRUE โ enters the block | ||
| 15 | 17 | push(input("Enter item to push: ")) | stack = ['10', '20'] | Enter item to push: 20 |
| โก Python jumps INTO function push(item='20') | ||||
| 16 | 4 | stack.append(item) | ||
| 17 | 5 | print(item, "pushed to stack") | 20 pushed to stack | |
โฌ
function push() ends and returns None to the caller | ||||
| 18 | 13 | while True: condition is TRUE โ enters the block | ||
| 19 | 14 | print("\n1.PUSH 2.POP 3.Display 4.Exit") | 1.PUSH 2.POP 3.Display 4.Exit | |
| 20 | 15 | ch = int(input("Enter choice: ")) | Enter choice: 1 | |
| 21 | 16 | if ch == 1: condition is TRUE โ enters the block | ||
| 22 | 17 | push(input("Enter item to push: ")) | stack = ['10', '20', '30'] | Enter item to push: 30 |
| โก Python jumps INTO function push(item='30') | ||||
| 23 | 4 | stack.append(item) | ||
| 24 | 5 | print(item, "pushed to stack") | 30 pushed to stack | |
โฌ
function push() ends and returns None to the caller | ||||
| 25 | 13 | while True: condition is TRUE โ enters the block | ||
| 26 | 14 | 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
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")
Enter list of numbers: 5 10 12 15 20 25
Stack (multiples of 5): [5, 10, 15, 20, 25]
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
Arr๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q20.py. - Press F5 (Run โ Run Module).
- When the program asks, type 5 10 12 15 20 25 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def PUSH(Arr): function is defined (remembered), not run yet | ||
| 2 | 8 | 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 |
| 3 | 9 | stack = PUSH(Arr) | stack = [5, 10, 15, 20, 25] | |
| โก Python jumps INTO function PUSH(Arr=[5, 10, 12, 15, 20, 25]) | ||||
| 4 | 2 | stack = [] | stack = [] | |
| 5 | 3 | for num in Arr: next item taken | num = 5 | |
| 6 | 4 | if num % 5 == 0: condition is TRUE โ enters the block | ||
| 7 | 5 | stack.append(num) | stack = [5] | |
| 8 | 3 | for num in Arr: next item taken | num = 10 | |
| 9 | 4 | if num % 5 == 0: condition is TRUE โ enters the block | ||
| 10 | 5 | stack.append(num) | stack = [5, 10] | |
| 11 | 3 | for num in Arr: next item taken | num = 12 | |
| 12 | 4 | if num % 5 == 0: condition is FALSE โ skips this block | ||
| 13 | 3 | for num in Arr: next item taken | num = 15 | |
| 14 | 4 | if num % 5 == 0: condition is TRUE โ enters the block | ||
| 15 | 5 | stack.append(num) | stack = [5, 10, 15] | |
| 16 | 3 | for num in Arr: next item taken | num = 20 | |
| 17 | 4 | if num % 5 == 0: condition is TRUE โ enters the block | ||
| 18 | 5 | stack.append(num) | stack = [5, 10, 15, 20] | |
| 19 | 3 | for num in Arr: next item taken | num = 25 | |
| 20 | 4 | if num % 5 == 0: condition is TRUE โ enters the block | ||
| 21 | 5 | stack.append(num) | stack = [5, 10, 15, 20, 25] | |
| 22 | 3 | for num in Arr: no items left โ loop ends | ||
| 23 | 6 | return stack | ||
โฌ
function PUSH() ends and returns [5, 10, 15, 20, 25] to the caller | ||||
| 24 | 11 | if stack: condition is TRUE โ enters the block | ||
| 25 | 12 | print("Stack (multiples of 5):", stack) | Stack (multiples of 5): [5, 10, 15, 20, 25] | |
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)
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]
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
Arr๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q21.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10 20 30 40 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | def POP(Arr): function is defined (remembered), not run yet | ||
| 2 | 7 | Arr = list(map(int, input("Enter stack elements: ").split())) | Arr = [10, 20, 30, 40] | Enter stack elements: 10 20 30 40 |
| 3 | 8 | print("Stack before POP:", Arr) | Stack before POP: [10, 20, 30, 40] | |
| 4 | 10 | deleted = POP(Arr) | Arr = [10, 20, 30], deleted = 40 | |
| โก Python jumps INTO function POP(Arr=[10, 20, 30, 40]) | ||||
| 5 | 2 | if not Arr: condition is FALSE โ skips this block | ||
| 6 | 5 | return Arr.pop() | Arr = [10, 20, 30] | |
โฌ
function POP() ends and returns 40 to the caller | ||||
| 7 | 11 | if deleted is not None: condition is TRUE โ enters the block | ||
| 8 | 12 | print("Value deleted from stack:", deleted) | Value deleted from stack: 40 | |
| 9 | 13 | print("Stack after POP:", Arr) | Stack after POP: [10, 20, 30] | |
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- The code selects the database with
USE school;- MySQL replies Database changed. - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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".
USE school;
Selects the database school - all following commands work inside it.
- MySQL replies "Database changed".
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.
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.
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.
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.
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.
UPDATE student SET marks = 90.0 WHERE rollno = 3;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE rollno = 3 โ finds only the rows that match.
- SET marks = 90.0 โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE rollno = 3 โ 1 row(s) matched.
| rollno | name | class | marks | |
|---|---|---|---|---|
| 1 | Amit | 12 | 88.50 | |
| 2 | Sara | 12 | 92.00 | |
| 3 | Rahul | 12 | 65.50 | โ |
| 4 | Priya | 12 | 78.00 |
AFTER: The matched rows now have the new values (highlighted).
| rollno | name | class | marks | |
|---|---|---|---|---|
| 1 | Amit | 12 | 88.50 | |
| 2 | Sara | 12 | 92.00 | |
| 3 | Rahul | 12 | 90.00 | โ |
| 4 | Priya | 12 | 78.00 |
SELECT * FROM student ORDER BY marks DESC;
Fetches rows from student, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 4 rows are taken.
| rollno | name | class | marks |
|---|---|---|---|
| 1 | Amit | 12 | 88.50 |
| 2 | Sara | 12 | 92.00 |
| 3 | Rahul | 12 | 90.00 |
| 4 | Priya | 12 | 78.00 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------+-------+-------+-------+ | 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)
SELECT * FROM student ORDER BY name ASC;
Fetches rows from student, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
- ORDER BY name ASC โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 4 rows are taken.
| rollno | name | class | marks |
|---|---|---|---|
| 1 | Amit | 12 | 88.50 |
| 2 | Sara | 12 | 92.00 |
| 3 | Rahul | 12 | 90.00 |
| 4 | Priya | 12 | 78.00 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------+-------+-------+-------+ | 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)
DELETE FROM student WHERE rollno = 4;
Removes rows from table student.
- FROM student โ picks the table.
- WHERE rollno = 4 โ finds the matching rows.
- Those rows are removed permanently โ "Query OK, n rows affected".
FIND: WHERE rollno = 4 โ 1 row(s) matched.
| rollno | name | class | marks | |
|---|---|---|---|---|
| 1 | Amit | 12 | 88.50 | |
| 2 | Sara | 12 | 92.00 | |
| 3 | Rahul | 12 | 90.00 | |
| 4 | Priya | 12 | 78.00 | ๐ |
AFTER: The matched rows are gone โ 3 row(s) left.
| rollno | name | class | marks | |
|---|---|---|---|---|
| 1 | Amit | 12 | 88.50 | |
| 2 | Sara | 12 | 92.00 | |
| 3 | Rahul | 12 | 90.00 |
SELECT class, COUNT(*) FROM student GROUP BY class;
Fetches rows from student, grouped by class.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY class โ makes groups: rows with the same class go into one group (one output row per group).
- SELECT class, COUNT(*) โ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 3 rows are taken.
| rollno | name | class | marks |
|---|---|---|---|
| 1 | Amit | 12 | 88.50 |
| 2 | Sara | 12 | 92.00 |
| 3 | Rahul | 12 | 90.00 |
GROUP BY: Rows with the same class are put in one group โ 1 group(s).
| class | rows_in_group |
|---|---|
| 12 | 3 |
RESULT: SELECT picks / calculates the columns โ final result:
+-------+----------+ | class | COUNT(*) | +-------+----------+ | 12 | 3 | +-------+----------+ 1 row in set (0.00 sec)
SELECT MIN(marks), MAX(marks), SUM(marks), COUNT(*), COUNT(marks), AVG(marks) FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- 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.
FROM: MySQL opens table student - all 3 rows are taken.
| rollno | name | class | marks |
|---|---|---|---|
| 1 | Amit | 12 | 88.50 |
| 2 | Sara | 12 | 92.00 |
| 3 | Rahul | 12 | 90.00 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+------------+------------+------------+----------+--------------+------------+ | 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)
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()
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'))
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
n, empno, name, salary๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q23.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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()
Enter Emp No to search: 101
Record found: (101, 'Ramesh', Decimal('45000.00'))
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
empno๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q24.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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()
1.Update Student 2.Delete Student
Enter choice: 1
Enter rollno to update: 2
Enter new marks: 95
Rows affected: 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
ch, roll, marks๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_cs_q25.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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.
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)
(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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q1.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 5 | arr = np.array([10, 20, 30, 40]) | arr = array([10, 20, 30, 40]) | |
| 4 | 6 | s1 = pd.Series(arr) | s1 = Series (4 values) | |
| 5 | 7 | print("(a) From ndarray:\n", s1) | (a) From ndarray: 0 10 1 20 2 30 3 40 dtype: int64 | |
| 6 | 10 | lst = [5, 15, 25, 35] | lst = [5, 15, 25, 35] | |
| 7 | 11 | s2 = pd.Series(lst, index=['a', 'b', 'c', 'd']) | s2 = Series (4 values) | |
| 8 | 12 | print("\n(b) From List (labeled index):\n", s2) | (b) From List (labeled index): a 5 b 15 c 25 d 35 dtype: int64 | |
| 9 | 13 | print("Positional index access s2[1]:", s2.iloc[1]) | Positional index access s2[1]: 15 | |
| 10 | 16 | d = {'Mon': 100, 'Tue': 200, 'Wed': 150} | d = {'Mon': 100, 'Tue': 200, 'Wed': 150} | |
| 11 | 17 | s3 = pd.Series(d) | s3 = Series (3 values) | |
| 12 | 18 | print("\n(c) From Dictionary:\n", s3) | (c) From Dictionary: Mon 100 Tue 200 Wed 150 dtype: int64 | |
| 13 | 21 | s4 = pd.Series(7, index=[0, 1, 2, 3]) | s4 = Series (4 values) | |
| 14 | 22 | print("\n(d) From Scalar:\n", s4) | (d) From Scalar: 0 7 1 7 2 7 3 7 dtype: int64 |
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])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q2.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | s = pd.Series([10, 20, 30, 40, 50, 60, 70], index=list('abcdefg')) | s = Series (7 values) | |
| 3 | 4 | print("Series:\n", s) | Series: a 10 b 20 c 30 d 40 e 50 f 60 g 70 dtype: int64 | |
| 4 | 7 | print("\ns[1:4] :\n", s[1:4]) | s[1:4] : b 20 c 30 d 40 dtype: int64 | |
| 5 | 8 | print("\ns[:3] :\n", s[:3]) | s[:3] : a 10 b 20 c 30 dtype: int64 | |
| 6 | 9 | print("\ns[-3:] :\n", s[-3:]) | s[-3:] : e 50 f 60 g 70 dtype: int64 | |
| 7 | 10 | print("\ns['b':'e']:\n", s['b':'e']) | s['b':'e']: b 20 c 30 d 40 e 50 dtype: int64 | |
| 8 | 11 | print("\ns[::2] :\n", s[::2]) | s[::2] : a 10 c 30 e 50 g 70 dtype: int64 | |
| 9 | 14 | print("\ns > 30 :\n", s[s > 30]) | s > 30 : d 40 e 50 f 60 g 70 dtype: int64 | |
| 10 | 15 | print("\ns < 30 :\n", s[s < 30]) | s < 30 : a 10 b 20 dtype: int64 | |
| 11 | 16 | print("\ns == 30:\n", s[s == 30]) | s == 30: c 30 dtype: int64 | |
| 12 | 17 | print("\ns != 30:\n", s[s != 30]) | s != 30: a 10 b 20 d 40 e 50 f 60 g 70 dtype: int64 | |
| 13 | 18 | print("\ns >= 40:\n", s[s >= 40]) | s >= 40: d 40 e 50 f 60 g 70 dtype: int64 | |
| 14 | 19 | print("\ns <= 40:\n", s[s <= 40]) | s <= 40: a 10 b 20 c 30 d 40 dtype: int64 |
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])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q3.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 4 | "Amit": 88.5, | ||
| 3 | 5 | "Sara": 92.0, | ||
| 4 | 6 | "Rahul": 65.5, | ||
| 5 | 7 | "Priya": 78.0, | ||
| 6 | 8 | "Karan": 55.0 | ||
| 7 | 3 | results = { | results = {'Amit': 88.5, 'Sara': 92.0, 'Rahul': 65.5, 'Priya': 78.0, 'Karan':โฆ | |
| 8 | 11 | s = pd.Series(results) | s = Series (5 values) | |
| 9 | 12 | print("All Results:\n", s) | All Results: Amit 88.5 Sara 92.0 Rahul 65.5 Priya 78.0 Karan 55.0 dtype: float64 | |
| 10 | 13 | print("\nStudents scoring above 75%:\n", s[s > 75]) | Students scoring above 75%: Amit 88.5 Sara 92.0 Priya 78.0 dtype: float64 |
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)
(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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q4.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 5 | arr = np.array([[1, 2], [3, 4]]) | arr = array([[1, 2], [3, 4]]) | |
| 4 | 6 | df1 = pd.DataFrame(arr, columns=['A', 'B']) | df1 = DataFrame (2 rows ร 2 columns) | |
| 5 | 7 | print("(a) From ndarray:\n", df1) | (a) From ndarray:
A B
0 1 2
1 3 4 | |
| 6 | 10 | lst = [[10, 'Amit'], [20, 'Sara']] | lst = [[10, 'Amit'], [20, 'Sara']] | |
| 7 | 11 | df2 = pd.DataFrame(lst, columns=['Marks', 'Name'], index=['s1', 's2']) | df2 = DataFrame (2 rows ร 2 columns) | |
| 8 | 12 | print("\n(b) From List (labeled index):\n", df2) |
(b) From List (labeled index):
Marks Name
s1 10 Amit
s2 20 Sara | |
| 9 | 13 | print("Positional row df2.iloc[0]:\n", df2.iloc[0]) | Positional row df2.iloc[0]: Marks 10 Name Amit Name: s1, dtype: object | |
| 10 | 16 | d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]} | d = {'Name': ['Amit', 'Sara'], 'Marks': [88, 92]} | |
| 11 | 17 | df3 = pd.DataFrame(d) | df3 = DataFrame (2 rows ร 2 columns) | |
| 12 | 18 | print("\n(c) From Dictionary:\n", df3) |
(c) From Dictionary:
Name Marks
0 Amit 88
1 Sara 92 | |
| 13 | 21 | df4 = pd.DataFrame(df3) | df4 = DataFrame (2 rows ร 2 columns) | |
| 14 | 22 | print("\n(d) From another DataFrame:\n", df4) |
(d) From another DataFrame:
Name Marks
0 Amit 88
1 Sara 92 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q5.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 4 | 'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'Stationery'], | ||
| 3 | 5 | 'Item': ['TV', 'Rice', 'Fan', 'Wheat', 'Pen'], | ||
| 4 | 6 | 'Expenditure': [25000, 3000, 2000, 2500, 500] | ||
| 5 | 3 | data = { | data = {'Category': ['Electronics', 'Grocery', 'Electronics', 'Grocery', 'โฆ | |
| 6 | 8 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 3 columns) | |
| 7 | 9 | 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 | |
| 8 | 11 | grouped = df.groupby('Category')['Expenditure'].sum() | grouped = Series (3 values) | |
| 9 | 12 | print("\nTotal Expenditure per Category:\n", grouped) | Total Expenditure per Category: Category Electronics 27000 Grocery 5500 Stationery 500 Name: Expenditure, dtype: int64 |
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)")
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)
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q6.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 4 | 'Name': ['Amit', 'Sara', 'Rahul'], | ||
| 3 | 5 | 'Marks': [88.5, 92.0, 65.5], | ||
| 4 | 6 | 'Result': ['Pass', 'Pass', 'Pass'] | ||
| 5 | 3 | data = { | data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88.5, 92.0, 65.5], 'Rโฆ | |
| 6 | 8 | df = pd.DataFrame(data, index=['s1', 's2', 's3']) | df = DataFrame (3 rows ร 3 columns) | |
| 7 | 10 | print("DataFrame:\n", df) | DataFrame:
Name Marks Result
s1 Amit 88.5 Pass
s2 Sara 92.0 Pass
s3 Rahul 65.5 Pass | |
| 8 | 11 | print("\nRow labels :", df.index.tolist()) | Row labels : ['s1', 's2', 's3'] | |
| 9 | 12 | print("Column labels:", df.columns.tolist()) | Column labels: ['Name', 'Marks', 'Result'] | |
| 10 | 13 | print("Data types :\n", df.dtypes) | Data types : Name object Marks float64 Result object dtype: object | |
| 11 | 14 | print("Dimensions :", df.shape, " (rows, columns)") | Dimensions : (3, 3) (rows, columns) |
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])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q7.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 4 | 'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'], | ||
| 3 | 5 | 'Marks': [88, 92, 88, 65, 92] | ||
| 4 | 3 | data = { | data = {'Name': ['Amit', 'Sara', 'Amit', 'Rahul', 'Sara'], 'Marks': [88, 9โฆ | |
| 5 | 7 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 2 columns) | |
| 6 | 8 | print("Original DataFrame:\n", df) | Original DataFrame:
Name Marks
0 Amit 88
1 Sara 92
2 Amit 88
3 Rahul 65
4 Sara 92 | |
| 7 | 10 | print("\nDuplicate rows:\n", df[df.duplicated()]) |
Duplicate rows:
Name Marks
2 Amit 88
4 Sara 92 | |
| 8 | 11 | print("\nDataFrame without duplicates:\n", df.drop_duplicates()) |
DataFrame without duplicates:
Name Marks
0 Amit 88
1 Sara 92
3 Rahul 65 | |
| 9 | 12 | 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 |
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)
Data exported to students.csv
Data imported back:
Name Marks
0 Amit 88
1 Sara 92
2 Rahul 65
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q8.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]} | data = {'Name': ['Amit', 'Sara', 'Rahul'], 'Marks': [88, 92, 65]} | |
| 3 | 4 | df = pd.DataFrame(data) | df = DataFrame (3 rows ร 2 columns) | |
| 4 | 7 | df.to_csv("students.csv", index=False) | ||
| 5 | 8 | print("Data exported to students.csv") | Data exported to students.csv | |
| 6 | 11 | df2 = pd.read_csv("students.csv") | df2 = DataFrame (3 rows ร 2 columns) | |
| 7 | 12 | print("\nData imported back:\n", df2) |
Data imported back:
Name Marks
0 Amit 88
1 Sara 92
2 Rahul 65 |
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()])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q9.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 4 | 'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'], | ||
| 3 | 5 | 'Subject': ['CS', 'IP', 'CS', 'IP'], | ||
| 4 | 6 | 'Average': [82, 78, 75, 88] | ||
| 5 | 3 | data = { | data = {'Class': ['XII-A', 'XII-A', 'XII-B', 'XII-B'], 'Subject': ['CS', 'โฆ | |
| 6 | 8 | df = pd.DataFrame(data) | df = DataFrame (4 rows ร 3 columns) | |
| 7 | 9 | 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 | |
| 8 | 11 | 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 | |
| 9 | 12 | print("\nSubject-wise average:\n", df.groupby('Subject')['Average'].mean()) | Subject-wise average: Subject CS 78.5 IP 83.0 Name: Average, dtype: float64 | |
| 10 | 13 | 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 |
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()
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q10.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 4 | data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditure': [27000, 5500, | data = {'Category': ['Electronics', 'Grocery', 'Stationery'], 'Expenditureโฆ | |
| 4 | 5 | df = pd.DataFrame(data) | df = DataFrame (3 rows ร 2 columns) | |
| 5 | 7 | df.plot(kind='bar', x='Category', y='Expenditure', legend=True, | ||
| 6 | 8 | title='Quarterly Expenditure by Category', color='orange') | ||
| 7 | 7 | df.plot(kind='bar', x='Category', y='Expenditure', legend=True, | ||
| 8 | 9 | plt.xlabel("Category") | ||
| 9 | 10 | plt.ylabel("Expenditure (Rs.)") | ||
| 10 | 11 | plt.tight_layout() | ||
| 11 | 12 | plt.savefig("expenditure_chart.png") | ||
| 12 | 13 | plt.show() |
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()
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q11.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 5 | data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'], | ||
| 4 | 6 | 'Literacy_Rate': [86.2, 67.7, 82.3, 96.2]} | ||
| 5 | 5 | data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'], | data = {'State': ['Delhi', 'UP', 'Maharashtra', 'Kerala'], 'Literacy_Rate'โฆ | |
| 6 | 7 | df = pd.DataFrame(data) | df = DataFrame (4 rows ร 2 columns) | |
| 7 | 9 | 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 | |
| 8 | 11 | plt.bar(df['State'], df['Literacy_Rate'], color='navy') | ||
| 9 | 12 | plt.title("State-wise Literacy Rate") | ||
| 10 | 13 | plt.xlabel("State") | ||
| 11 | 14 | plt.ylabel("Literacy Rate (%)") | ||
| 12 | 15 | plt.tight_layout() | ||
| 13 | 16 | plt.show() |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q12.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | df = pd.DataFrame({'Marks': [55, 88, 92, 65, 78, 99]}) | df = DataFrame (6 rows ร 1 columns) | |
| 3 | 4 | print("DataFrame:\n", df) | DataFrame:
Marks
0 55
1 88
2 92
3 65
4 78
5 99 | |
| 4 | 6 | print("\n3 Largest values:\n", df['Marks'].nlargest(3)) | 3 Largest values: 5 99 2 92 1 88 Name: Marks, dtype: int64 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q13.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | df = pd.DataFrame({'Q1': [10, 20, 30], 'Q2': [15, 25, 35], 'Q3': [20, 30, 40]}) | df = DataFrame (3 rows ร 3 columns) | |
| 3 | 4 | print("Original:\n", df) | Original:
Q1 Q2 Q3
0 10 15 20
1 20 25 30
2 30 35 40 | |
| 4 | 6 | result = df.sub(df.mean(axis=1), axis=0) | result = DataFrame (3 rows ร 3 columns) | |
| 5 | 7 | 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 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q14.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | df = pd.DataFrame({'A': [10, -5, 20, -8], 'B': [-3, 15, -1, 9]}) | df = DataFrame (4 rows ร 2 columns) | |
| 3 | 4 | print("Original:\n", df) | Original:
A B
0 10 -3
1 -5 15
2 20 -1
3 -8 9 | |
| 4 | 6 | df[df < 0] = 0 | ||
| 5 | 7 | 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 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q15.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 4 | df = pd.DataFrame({'A': [10, np.nan, 20], 'B': [np.nan, 15, 25]}) | df = DataFrame (3 rows ร 2 columns) | |
| 4 | 5 | print("Original:\n", df) | Original:
A B
0 10.0 NaN
1 NaN 15.0
2 20.0 25.0 | |
| 5 | 7 | df = df.fillna(999) | ||
| 6 | 8 | 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 |
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']])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q16.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | 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], 'โฆ | |
| 3 | 4 | df = pd.DataFrame(d, index=['Jan','Feb','March','April']) | df = DataFrame (4 rows ร 3 columns) | |
| 4 | 5 | print(df) | Mouse Keyboard Scanner Jan 150 180 200 Feb 200 200 280 March 300 190 330 April 400 300 450 | |
| 5 | 8 | print("\nA.\n", df[['Mouse','Scanner']]) |
A.
Mouse Scanner
Jan 150 200
Feb 200 280
March 300 330
April 400 450 | |
| 6 | 11 | print("\nB.\n", df.Keyboard) | B. Jan 180 Feb 200 March 190 April 300 Name: Keyboard, dtype: int64 | |
| 7 | 14 | print("\nC.\n", df.loc[:, 'Scanner']) | C. Jan 200 Feb 280 March 330 April 450 Name: Scanner, dtype: int64 | |
| 8 | 17 | print("\nD.\n", df[df['Mouse'] > 200]) |
D.
Mouse Keyboard Scanner
March 300 190 330
April 400 300 450 | |
| 9 | 20 | print("\nE.\n", df.iloc[:, [0, 2]]) |
E.
Mouse Scanner
Jan 150 200
Feb 200 280
March 300 330
April 400 450 | |
| 10 | 23 | print("\nF.\n", df.loc[['Jan','March'], ['Scanner','Keyboard']]) |
F.
Scanner Keyboard
Jan 200 180
March 330 190 |
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()
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q17.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 5 | 'BookName': ['Informatics Practices', 'Computer Science', 'Physics', 'Chemistry'], | ||
| 4 | 6 | 'Class': [12, 12, 11, 11], | ||
| 5 | 7 | 'Price': [320, 280, 240, 260] | ||
| 6 | 4 | books = { | books = {'BookName': ['Informatics Practices', 'Computer Science', 'Physicsโฆ | |
| 7 | 9 | df = pd.DataFrame(books) | df = DataFrame (4 rows ร 3 columns) | |
| 8 | 10 | print(df) | BookName Class Price 0 Informatics Practices 12 320 1 Computer Science 12 280 2 Physics 11 240 3 Chemistry 11 260 | |
| 9 | 13 | 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 | |
| 10 | 16 | 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 | |
| 11 | 19 | df.plot(kind='line', x='BookName', y='Price', marker='o', title='Book Price Trend') | ||
| 12 | 20 | plt.tight_layout() | ||
| 13 | 21 | plt.show() |
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()
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q18.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 5 | 'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'], | ||
| 4 | 6 | 'Population': [1412, 1408, 215, 231, 331], # in millions | ||
| 5 | 7 | 'BirthRate': [10.6, 16.4, 13.6, 27.5, 12.0] | ||
| 6 | 4 | data = { | data = {'Country': ['China', 'India', 'Brazil', 'Pakistan', 'USA'], 'Populโฆ | |
| 7 | 9 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 3 columns) | |
| 8 | 10 | 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 | |
| 9 | 13 | 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 | |
| 10 | 16 | 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 | |
| 11 | 19 | df.to_csv("country_data.csv", index=False) | ||
| 12 | 22 | plt.bar(df['Country'], df['Population'], color='green') | ||
| 13 | 23 | plt.title("Country vs Population") | ||
| 14 | 24 | plt.xlabel("Country") | ||
| 15 | 25 | plt.ylabel("Population (millions)") | ||
| 16 | 26 | plt.grid(axis='y') | ||
| 17 | 27 | plt.tight_layout() | ||
| 18 | 28 | plt.show() |
SQL: To create a school database and access it.
CREATE DATABASE school;
USE school;
SHOW DATABASES;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- The code selects the database with
USE school;- MySQL replies Database changed. - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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".
USE school;
Selects the database school - all following commands work inside it.
- MySQL replies "Database changed".
SHOW DATABASES;
Lists all the databases on the MySQL server.
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
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.
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');
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
SQL: To display the entire content of the table.
SELECT * FROM student;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT * FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------+---------+--------+--------------+------------+-------+---------------+ | 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)
SQL: To display Rno, Name and Marks of students scoring marks more than 50.
SELECT student_id, name, marks FROM student WHERE marks > 50;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT student_id, name, marks FROM student WHERE marks > 50;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks > 50 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT student_id, name, marks โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition marks > 50 is checked row by row: 9 row(s) pass โ, 1 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+--------------+-------+ | 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)
SQL: To find the average of marks from the student table.
SELECT AVG(marks) AS Average_Marks FROM student;
mysql> SELECT AVG(marks) AS Average_Marks FROM student;
+---------------+
| Average_Marks |
+---------------+
| 73.650000 |
+---------------+
1 row in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT AVG(marks) AS Average_Marks FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: AVG() finds the average.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+---------------+ | Average_Marks | +---------------+ | 73.650000 | +---------------+ 1 row in set (0.00 sec)
SQL: To find the number of students who are from section 'A'.
SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
mysql> SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
+-----------------+
| Total_Section_A |
+-----------------+
| 6 |
+-----------------+
1 row in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT COUNT(*) AS Total_Section_A FROM student WHERE section = 'A';
Fetches the summary values from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE section = 'A' โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition section = 'A' is checked row by row: 6 row(s) pass โ, 4 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+-----------------+ | Total_Section_A | +-----------------+ | 6 | +-----------------+ 1 row in set (0.00 sec)
SQL: To display information of all students whose name starts with 'AN'.
SELECT * FROM student WHERE name LIKE 'AN%';
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT * FROM student WHERE name LIKE 'AN%';
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE name LIKE 'AN%' (starts with "AN") โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition name LIKE 'AN%' is checked row by row: 2 row(s) pass โ, 8 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------+---------+--------+-------------+------------+-------+---------------+ | 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)
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';
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT student_id, name, dob โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition dob BETWEEN '2008-01-01' AND '2008-12-31' is checked row by row: 7 row(s) pass โ, 3 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------------+------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE gender = 'M' โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT student_id, name, dob, marks, email โ picks the columns / calculates the values to show.
- ORDER BY name ASC โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition gender = 'M' is checked row by row: 5 row(s) pass โ, 5 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------------+--------------+------------+-------+---------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT student_id, gender, name, dob, marks, email FROM student ORDER BY marks DESC;
Fetches rows from student, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT student_id, gender, name, dob, marks, email โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------------+--------+--------------+------------+-------+---------------+ | 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)
SQL: To display the unique sections available in the table.
SELECT DISTINCT section FROM student;
mysql> SELECT DISTINCT section FROM student;
+---------+
| section |
+---------+
| A |
| B |
+---------+
2 rows in set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT DISTINCT section FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT section โ picks the columns / calculates the values to show.
- DISTINCT โ removes repeated rows, so each value appears only once.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; DISTINCT removes repeats โ final result:
+---------+ | section | +---------+ | A | | B | +---------+ 2 rows in set (0.00 sec)
SQL: To display the name and class of students whose marks are less than 33.
SELECT name, class FROM student WHERE marks < 33;
mysql> SELECT name, class FROM student WHERE marks < 33;
Empty set (0.00 sec)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT name, class FROM student WHERE marks < 33;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks < 33 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, class โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition marks < 33 is checked row by row: 0 row(s) pass โ, 10 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
Empty set (0.00 sec)
SQL: To display the structure of the student table.
DESC student;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
SQL: To display the Name and DOB of students who were born in 2008.
SELECT name, dob FROM student WHERE YEAR(dob) = 2008;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT name, dob FROM student WHERE YEAR(dob) = 2008;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE YEAR(dob) = 2008 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, dob โ picks the columns / calculates the values to show.
- Functions used: YEAR() takes the year from a date.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition YEAR(dob) = 2008 is checked row by row: 7 row(s) pass โ, 3 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+------------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT COUNT(*), SUM(marks), AVG(marks), MIN(marks), MAX(marks) FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: COUNT(*) counts all rows; SUM() adds the values; AVG() finds the average; MIN() finds the smallest value; MAX() finds the largest value.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+----------+------------+------------+------------+------------+ | 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)
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).
- 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.
- 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.
SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM(' Amit ')
FROM student LIMIT 3;Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT UCASE(name), LCASE(name), LENGTH(name), SUBSTRING(name,1,4), CONCAT(name,'-XII'), TRIM(' Amit ') โ picks the columns / calculates the values to show.
- 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.
- LIMIT 3 โ shows only the first 3 row(s) of the result.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; LIMIT cuts โ final result:
+--------------+--------------+--------------+---------------------+---------------------+------------------+
| 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)SELECT NOW(), CURDATE(), YEAR(dob), MONTH(dob), DAY(dob), DATEDIFF(CURDATE(), dob) AS Age_in_days FROM student LIMIT 3;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- 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.
- LIMIT 3 โ shows only the first 3 row(s) of the result.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; LIMIT cuts โ final result:
+---------------------+------------+-----------+------------+----------+-------------+ | 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)
SELECT section, COUNT(*), AVG(marks) FROM student GROUP BY section;
Fetches rows from student, grouped by section.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY section โ makes groups: rows with the same section go into one group (one output row per group).
- SELECT section, COUNT(*), AVG(marks) โ picks the columns / calculates the values to show; aggregate functions are calculated separately for each group.
- Functions used: COUNT(*) counts all rows; AVG() finds the average.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same section are put in one group โ 2 group(s).
| section | rows_in_group |
|---|---|
| A | 6 |
| B | 4 |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+----------+------------+ | section | COUNT(*) | AVG(marks) | +---------+----------+------------+ | A | 6 | 80.250000 | | B | 4 | 63.750000 | +---------+----------+------------+ 2 rows in set (0.00 sec)
๐ 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.
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")
Delhi : average = 39.43 | highest = 42 on Sat
Shimla: average = 23.86 | highest = 26 on Fri
Chart saved as temp_line.pngNEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q35.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import matplotlib.pyplot as plt | ||
| 2 | 3 | days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] | days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] | |
| 3 | 4 | delhi = [36, 38, 40, 39, 41, 42, 40] | delhi = [36, 38, 40, 39, 41, 42, 40] | |
| 4 | 5 | shimla = [22, 24, 23, 25, 26, 24, 23] | shimla = [22, 24, 23, 25, 26, 24, 23] | |
| 5 | 7 | print("Delhi : average =", round(sum(delhi) / len(delhi), 2), "| highest =", max(delhi), " | Delhi : average = 39.43 | highest = 42 on Sat | |
| 6 | 8 | print("Shimla: average =", round(sum(shimla) / len(shimla), 2), "| highest =", max(shimla) | Shimla: average = 23.86 | highest = 26 on Fri | |
| 7 | 10 | plt.figure(figsize=(8, 4.5)) | ||
| 8 | 11 | plt.plot(days, delhi, color='red', linestyle='-', linewidth=2.5, marker='o', markersize=8, | ||
| 9 | 12 | plt.plot(days, shimla, color='blue', linestyle='--', linewidth=2, marker='s', markersize=7 | ||
| 10 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Mon', y = 36 | |
| 11 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 12 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Tue', y = 38 | |
| 13 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 14 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Wed', y = 40 | |
| 15 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 16 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Thu', y = 39 | |
| 17 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 18 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Fri', y = 41 | |
| 19 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 20 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Sat', y = 42 | |
| 21 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 22 | 13 | for x, y in zip(days, delhi): next item taken | x = 'Sun', y = 40 | |
| 23 | 14 | plt.text(x, y + 0.7, y, ha='center', color='red') | ||
| 24 | 13 | for x, y in zip(days, delhi): no items left โ loop ends | ||
| 25 | 15 | for x, y in zip(days, shimla): next item taken | x = 'Mon', y = 22 | |
| 26 | 16 | plt.text(x, y + 0.7, y, ha='center', color='blue') | ||
| 27 | 15 | for x, y in zip(days, shimla): next item taken | x = 'Tue', y = 24 | |
| 28 | 16 | plt.text(x, y + 0.7, y, ha='center', color='blue') | ||
| 29 | 15 | for x, y in zip(days, shimla): next item taken | x = 'Wed', y = 23 | |
| 30 | 16 | plt.text(x, y + 0.7, y, ha='center', color='blue') | ||
| 31 | 15 | for x, y in zip(days, shimla): next item taken | x = 'Thu', y = 25 | |
| 32 | 16 | 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
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")
Total books read : 46
Top reader : Karan with 12 books
Average per child: 7.67
Chart saved as books_bar.pngNEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q36.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import matplotlib.pyplot as plt | ||
| 2 | 3 | students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek'] # Statement-1 : impor | students = ['Karan', 'Lina', 'Raj', 'Simran', 'Tanya', 'Vivek'] | |
| 3 | 4 | books_read = [12, 9, 5, 3, 10, 7] # Statement-2 : height | books_read = [12, 9, 5, 3, 10, 7] | |
| 4 | 6 | print("Total books read :", sum(books_read)) | Total books read : 46 | |
| 5 | 7 | print("Top reader :", students[books_read.index(max(books_read))], "with", max(books | Top reader : Karan with 12 books | |
| 6 | 8 | print("Average per child:", round(sum(books_read) / len(books_read), 2)) | Average per child: 7.67 | |
| 7 | 10 | colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00'] | colours = ['#e8590c', '#1c7ed6', '#2f9e44', '#c2255c', '#7048e8', '#f59f00'] | |
| 8 | 11 | plt.figure(figsize=(8, 4.5)) | ||
| 9 | 12 | plt.bar(students, books_read, color=colours, edgecolor='black', width=0.6) | ||
| 10 | 13 | for i, v in enumerate(books_read): next item taken | i = 0, v = 12 | |
| 11 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 12 | 13 | for i, v in enumerate(books_read): next item taken | i = 1, v = 9 | |
| 13 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 14 | 13 | for i, v in enumerate(books_read): next item taken | i = 2, v = 5 | |
| 15 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 16 | 13 | for i, v in enumerate(books_read): next item taken | i = 3, v = 3 | |
| 17 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 18 | 13 | for i, v in enumerate(books_read): next item taken | i = 4, v = 10 | |
| 19 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 20 | 13 | for i, v in enumerate(books_read): next item taken | i = 5, v = 7 | |
| 21 | 14 | plt.text(i, v + 0.2, str(v), ha='center', fontweight='bold') | ||
| 22 | 13 | for i, v in enumerate(books_read): no items left โ loop ends | ||
| 23 | 15 | plt.xlabel('Student Name') | ||
| 24 | 16 | plt.ylabel('Books Read') # Statement-3 : ylabel | ||
| 25 | 17 | plt.title('Number of Books Read by Students') # Statement-4 : title | ||
| 26 | 18 | plt.savefig('books_bar.png') | ||
| 27 | 19 | plt.show() | ||
| 28 | 20 | print("Chart saved as books_bar.png") | Chart saved as books_bar.png |
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()
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 )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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q37.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 3 | import matplotlib.pyplot as plt | ||
| 4 | 5 | df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'], | ||
| 5 | 6 | 'Gold': [28, 40, 22, 18, 13], 'Silver': [38, 27, 25, 23, 21], 'Bronze': [41, 23, 30, 31, 1 | ||
| 6 | 5 | df = pd.DataFrame({'Country': ['India', 'China', 'Japan', 'Korea', 'Iran'], | df = DataFrame (5 rows ร 4 columns) | |
| 7 | 7 | df['Total'] = df['Gold'] + df['Silver'] + df['Bronze'] | df = DataFrame (5 rows ร 5 columns) | |
| 8 | 8 | 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 | |
| 9 | 9 | print("\nCountry with maximum medals:", df.loc[df['Total'].idxmax(), 'Country'], "(", df[' | Country with maximum medals: India ( 107 ) | |
| 10 | 11 | x = np.arange(len(df)) | x = array([0, 1, 2, 3, 4]) | |
| 11 | 12 | w = 0.25 | w = 0.25 | |
| 12 | 13 | plt.figure(figsize=(9, 4.8)) | ||
| 13 | 14 | plt.bar(x - w, df['Gold'], width=w, color='gold', edgecolor='black', label='Gold') | ||
| 14 | 15 | plt.bar(x, df['Silver'], width=w, color='silver', edgecolor='black', label='Silver') | ||
| 15 | 16 | plt.bar(x + w, df['Bronze'], width=w, color='#cd7f32', edgecolor='black', label='Bronze') | ||
| 16 | 17 | plt.xticks(x, df['Country']) | ||
| 17 | 18 | plt.xlabel('Country') | ||
| 18 | 19 | plt.ylabel('Number of medals') | ||
| 19 | 20 | plt.title('Medal Tally (sample data) - Multiple Bar Chart') | ||
| 20 | 21 | plt.legend() | ||
| 21 | 22 | plt.grid(axis='y', linestyle='--', alpha=0.6) | ||
| 22 | 23 | plt.savefig('medals_bar.png') | ||
| 23 | 24 | plt.show() |
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()
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 **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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q38.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import numpy as np | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 4 | 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โฆ | |
| 4 | 6 | bins = [30, 35, 40, 45, 50, 55, 60, 65, 70] | bins = [30, 35, 40, 45, 50, 55, 60, 65, 70] | |
| 5 | 7 | freq, edges = np.histogram(weights, bins=bins) | freq = array([0, 4, 6, 11, 9, 5, 3, 2]), edges = array of shape (9,) | |
| 6 | 8 | print("Students:", len(weights), "| Minimum:", min(weights), "| Maximum:", max(weights), " | Students: 40 | Minimum: 36 | Maximum: 69 | Mean: 49.85 | |
| 7 | 9 | print("\nClass interval Frequency") | Class interval Frequency | |
| 8 | 10 | for i in range(len(freq)): next item taken | i = 0 | |
| 9 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 30 - 35 0 | |
| 10 | 10 | for i in range(len(freq)): next item taken | i = 1 | |
| 11 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 35 - 40 4 **** | |
| 12 | 10 | for i in range(len(freq)): next item taken | i = 2 | |
| 13 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 40 - 45 6 ****** | |
| 14 | 10 | for i in range(len(freq)): next item taken | i = 3 | |
| 15 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 45 - 50 11 *********** | |
| 16 | 10 | for i in range(len(freq)): next item taken | i = 4 | |
| 17 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 50 - 55 9 ********* | |
| 18 | 10 | for i in range(len(freq)): next item taken | i = 5 | |
| 19 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 55 - 60 5 ***** | |
| 20 | 10 | for i in range(len(freq)): next item taken | i = 6 | |
| 21 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 60 - 65 3 *** | |
| 22 | 10 | for i in range(len(freq)): next item taken | i = 7 | |
| 23 | 11 | print(f" {edges[i]} - {edges[i + 1]} {freq[i]:>3} " + "*" * freq[i]) | 65 - 70 2 ** | |
| 24 | 10 | for i in range(len(freq)): no items left โ loop ends | ||
| 25 | 13 | plt.figure(figsize=(8, 4.5)) | ||
| 26 | 14 | plt.hist(weights, bins=bins, color='#4dabf7', edgecolor='black') | ||
| 27 | 15 | plt.title('Weights of Students of Class XII') | ||
| 28 | 16 | plt.xlabel('Weight (kg)') | ||
| 29 | 17 | plt.ylabel('Number of students') | ||
| 30 | 18 | plt.xticks(bins) | ||
| 31 | 19 | plt.savefig('weight_hist.png') | ||
| 32 | 20 | 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
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()
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: Q4NEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q39.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 4 | sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55], | ||
| 4 | 5 | 'East': [30, 35, 33, 42], 'West': [50, 48, 57, 63]}, | ||
| 5 | 4 | sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55], | ||
| 6 | 6 | index=['Q1', 'Q2', 'Q3', 'Q4']) | ||
| 7 | 4 | sales = pd.DataFrame({'North': [45, 52, 61, 58], 'South': [38, 41, 47, 55], | sales = DataFrame (4 rows ร 4 columns) | |
| 8 | 7 | 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 | |
| 9 | 8 | total = sales.sum().sort_values() | total = Series (4 values) | |
| 10 | 9 | print("\nTotal sales of each zone:\n", total) | Total sales of each zone: East 140 South 181 North 216 West 218 dtype: int64 | |
| 11 | 10 | print("Best quarter:", sales.sum(axis=1).idxmax()) | Best quarter: Q4 | |
| 12 | 12 | sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5), | ||
| 13 | 13 | color=['#e03131', '#2f9e44', '#1971c2', '#f08c00']) | ||
| 14 | 12 | sales.plot(kind='line', marker='o', linewidth=2, figsize=(8, 4.5), | ||
| 15 | 14 | plt.title('Quarterly Sales of Each Zone') | ||
| 16 | 15 | plt.xlabel('Quarter') | ||
| 17 | 16 | plt.ylabel('Sales (Rs. lakh)') | ||
| 18 | 17 | plt.grid(linestyle=':') | ||
| 19 | 18 | plt.savefig('zone_line.png') | ||
| 20 | 19 | plt.show() | ||
| 21 | 21 | total.plot(kind='barh', color=['#74c0fc', '#63e6be', '#ffa94d', '#ff6b6b'], edgecolor='bla | ||
| 22 | 22 | plt.title('Total Annual Sales by Zone') | ||
| 23 | 23 | plt.xlabel('Sales (Rs. lakh)') | ||
| 24 | 24 | plt.ylabel('Zone') | ||
| 25 | 25 | plt.tight_layout() | ||
| 26 | 26 | plt.savefig('zone_barh.png') | ||
| 27 | 27 | plt.show() |
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()
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.62NEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q40.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 4 | df = pd.read_csv('student_data.csv') | df = DataFrame (15 rows ร 6 columns) | |
| 4 | 5 | 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โฆ | |
| 5 | 6 | avg = df[['Maths', 'Science', 'AI']].mean().round(2) | avg = Series (3 values) | |
| 6 | 7 | print("\nSubject-wise average:\n", avg) | Subject-wise average: Maths 76.40 Science 77.47 AI 84.07 dtype: float64 | |
| 7 | 8 | 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 | |
| 8 | 10 | plt.figure(figsize=(7, 4.2)) | ||
| 9 | 11 | plt.bar(avg.index, avg.values, color=['#f03e3e', '#37b24d', '#1c7ed6'], width=0.5, edgecol | ||
| 10 | 12 | for i, v in enumerate(avg.values): next item taken | i = 0, v = np.float64(76.4) | |
| 11 | 13 | plt.text(i, v + 1, v, ha='center', fontweight='bold') | ||
| 12 | 12 | for i, v in enumerate(avg.values): next item taken | i = 1, v = np.float64(77.47) | |
| 13 | 13 | plt.text(i, v + 1, v, ha='center', fontweight='bold') | ||
| 14 | 12 | for i, v in enumerate(avg.values): next item taken | i = 2, v = np.float64(84.07) | |
| 15 | 13 | plt.text(i, v + 1, v, ha='center', fontweight='bold') | ||
| 16 | 12 | for i, v in enumerate(avg.values): no items left โ loop ends | ||
| 17 | 14 | plt.ylim(0, 100) | ||
| 18 | 15 | plt.title('Subject-wise Average Marks') | ||
| 19 | 16 | plt.xlabel('Subject') | ||
| 20 | 17 | plt.ylabel('Average marks') | ||
| 21 | 18 | plt.savefig('csv_avg_bar.png') | ||
| 22 | 19 | plt.show() | ||
| 23 | 21 | plt.figure(figsize=(9, 4.5)) | ||
| 24 | 22 | plt.plot(df['Name'], df['Maths'], 'g-o', label='Maths') | ||
| 25 | 23 | plt.plot(df['Name'], df['AI'], 'm--^', label='AI') | ||
| 26 | 24 | plt.xticks(rotation=45) | ||
| 27 | 25 | plt.title('Maths vs AI Marks of Students') | ||
| 28 | 26 | plt.xlabel('Student') | ||
| 29 | 27 | plt.ylabel('Marks') | ||
| 30 | 28 | plt.legend() | ||
| 31 | 29 | plt.grid(alpha=0.4) | ||
| 32 | 30 | 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)
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');
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
SELECT student_id, name, marks FROM student WHERE student_id = 7;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE student_id = 7 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT student_id, name, marks โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition student_id = 7 is checked row by row: 1 row(s) pass โ, 9 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------------+-------+ | student_id | name | marks | +------------+-------------+-------+ | 7 | Vivek Yadav | 48.00 | +------------+-------------+-------+ 1 row in set (0.00 sec)
DELETE FROM student WHERE student_id = 7;
Removes rows from table student.
- FROM student โ picks the table.
- WHERE student_id = 7 โ finds the matching rows.
- Those rows are removed permanently โ "Query OK, n rows affected".
FIND: WHERE student_id = 7 โ 1 row(s) matched.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 |
AFTER: The matched rows are gone โ 9 row(s) left.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | |
| 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 |
SELECT COUNT(*) AS Students_Left FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 9 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+---------------+ | Students_Left | +---------------+ | 9 | +---------------+ 1 row in set (0.00 sec)
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.
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- 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 student_id, name, section, marks โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
| 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 |
| 7 | 12 | B | M | Vivek Yadav | 2007-11-30 | 48.00 | vivek@kvsb.in |
WHERE: Condition marks > 80 is checked row by row: 4 row(s) pass โ, 6 fail โ.
| student_id | class | section | gender | name | dob | marks | ||
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
| 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 | โ |
| 7 | 12 | B | M | Vivek Yadav | 2007-11-30 | 48.00 | vivek@kvsb.in | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------------+------------+---------+-------+ | 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)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- 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.
FROM: MySQL opens table student - all 10 rows are taken.
| student_id | class | section | gender | name | dob | marks | |
|---|---|---|---|---|---|---|---|
| 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 |
| 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 |
| 7 | 12 | B | M | Vivek Yadav | 2007-11-30 | 48.00 | vivek@kvsb.in |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+---------+---------+--------+---------+ | Minimum | Maximum | Total | Average | +---------+---------+--------+---------+ | 48.00 | 95.00 | 736.50 | 73.65 | +---------+---------+--------+---------+ 1 row in set (0.00 sec)
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;
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)
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:
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in MySQL on the code box above (or open MySQL 8.0 Command Line Client and type your password).
- First select your database, e.g.
USE school;(the table must already be created). - 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 ;. - Check the result: a table with n rows in set, or Query OK for CREATE / INSERT / UPDATE / DELETE.
- Write the query + output in your practical file.
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.
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.
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.
- FROM customer โ MySQL first opens table customer and looks at all its rows.
- GROUP BY country โ makes groups: rows with the same country go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY Total_Customers DESC, country โ sorts the result rows in descending (big โ small / Z โ A) order - the 2nd column breaks ties.
FROM: MySQL opens table customer - all 8 rows are taken.
| customer_id | customer_name | country |
|---|---|---|
| 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 |
GROUP BY: Rows with the same country are put in one group โ 4 group(s).
| country | rows_in_group |
|---|---|
| India | 3 |
| Singapore | 2 |
| UAE | 1 |
| USA | 2 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-----------+-----------------+ | country | Total_Customers | +-----------+-----------------+ | India | 3 | | Singapore | 2 | | USA | 2 | | UAE | 1 | +-----------+-----------------+ 4 rows in set (0.00 sec)
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])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ip_q45.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50], | ||
| 3 | 4 | index=['Amit', 'Sara', 'Neha', 'Rahul', 'Priya', | ||
| 4 | 3 | marks = pd.Series([45, 78, 92, 66, 88, 59, 95, 71, 83, 50], | marks = Series (10 values) | |
| 5 | 6 | print("Marks Series:") | Marks Series: | |
| 6 | 7 | print(marks) | Amit 45 Sara 78 Neha 92 Rahul 66 Priya 88 Karan 59 Divya 95 Vivek 71 Angad 83 Anand 50 dtype: int64 | |
| 7 | 9 | q75 = marks.quantile(0.75) # 75th percentile | q75 = np.float64(86.75) | |
| 8 | 10 | print("\n75th percentile value =", q75) | 75th percentile value = 86.75 | |
| 9 | 12 | print("\nStudents above the 75th percentile:") | Students above the 75th percentile: | |
| 10 | 13 | 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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)
| Component | Marks |
|---|---|
| Practical File (minimum 15 programs) | 15 |
| Practical Examination - any 3 programs on input/output, variables, operators, expressions, data types, flow of control and lists | 15 |
| Viva Voce | 5 |
| 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.
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("-------------------------------------")
------ MY PERSONAL INFORMATION ------
Name : Aarav Sharma
Father's Name : Mr. Rajesh Sharma
Class : IX - A
School Name : PM SHRI Kendriya Vidyalaya Shalimar Bagh
-------------------------------------
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q1.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | print("------ MY PERSONAL INFORMATION ------") | ------ MY PERSONAL INFORMATION ------ | |
| 2 | 3 | print("Name : Aarav Sharma") | Name : Aarav Sharma | |
| 3 | 4 | print("Father's Name : Mr. Rajesh Sharma") | Father's Name : Mr. Rajesh Sharma | |
| 4 | 5 | print("Class : IX - A") | Class : IX - A | |
| 5 | 6 | print("School Name : PM SHRI Kendriya Vidyalaya Shalimar Bagh") | School Name : PM SHRI Kendriya Vidyalaya Shalimar Bagh | |
| 6 | 7 | print("-------------------------------------") | ------------------------------------- |
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("*")
Pattern 1
*
* *
* * *
* * * *
* * * * *
Pattern 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q2.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | print("Pattern 1") | Pattern 1 | |
| 2 | 3 | print("*") | * | |
| 3 | 4 | print("* *") | * * | |
| 4 | 5 | print("* * *") | * * * | |
| 5 | 6 | print("* * * *") | * * * * | |
| 6 | 7 | print("* * * * *") | * * * * * | |
| 7 | 8 | print() | ||
| 8 | 9 | print("Pattern 2") | Pattern 2 | |
| 9 | 10 | print("* * * * *") | * * * * * | |
| 10 | 11 | print("* * * *") | * * * * | |
| 11 | 12 | print("* * *") | * * * | |
| 12 | 13 | print("* *") | * * | |
| 13 | 14 | print("*") | * |
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)
Number = 7
Square of 7 is 49
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q3.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | num = 7 | num = 7 | |
| 2 | 3 | square = num * num # or num ** 2 | square = 49 | |
| 3 | 4 | print("Number =", num) | Number = 7 | |
| 4 | 5 | print("Square of", num, "is", square) | Square of 7 is 49 |
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)
First number = 15
Second number = 20
Sum = 35
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q4.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | a = 15 | a = 15 | |
| 2 | 3 | b = 20 | b = 20 | |
| 3 | 4 | total = a + b | total = 35 | |
| 4 | 5 | print("First number =", a) | First number = 15 | |
| 5 | 6 | print("Second number =", b) | Second number = 20 | |
| 6 | 7 | print("Sum =", total) | Sum = 35 |
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")
Length in kilometres = 5.5 km
Length in metres = 5500.0 m
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q5.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | km = 5.5 # length in kilometres | km = 5.5 | |
| 2 | 3 | meters = km * 1000 # 1 km = 1000 m | meters = 5500.0 | |
| 3 | 4 | print("Length in kilometres =", km, "km") | Length in kilometres = 5.5 km | |
| 4 | 5 | print("Length in metres =", meters, "m") | Length in metres = 5500.0 m |
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)
Table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q6.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | n = 5 | n = 5 | |
| 2 | 3 | print("Table of", n) | Table of 5 | |
| 3 | 4 | print(n, "x 1 =", n * 1) | 5 x 1 = 5 | |
| 4 | 5 | print(n, "x 2 =", n * 2) | 5 x 2 = 10 | |
| 5 | 6 | print(n, "x 3 =", n * 3) | 5 x 3 = 15 | |
| 6 | 7 | print(n, "x 4 =", n * 4) | 5 x 4 = 20 | |
| 7 | 8 | print(n, "x 5 =", n * 5) | 5 x 5 = 25 |
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)
Principle amount = 2000
Rate of interest = 4.5 %
Time = 10 years
Simple Interest = 900.0
Total amount = 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q7.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | principle_amount = 2000 | principle_amount = 2000 | |
| 2 | 3 | rate_of_interest = 4.5 | rate_of_interest = 4.5 | |
| 3 | 4 | time = 10 | time = 10 | |
| 4 | 5 | simple_interest = (principle_amount * rate_of_interest * time) / 100 | simple_interest = 900.0 | |
| 5 | 6 | amount = principle_amount + simple_interest | amount = 2900.0 | |
| 6 | 7 | print("Principle amount =", principle_amount) | Principle amount = 2000 | |
| 7 | 8 | print("Rate of interest =", rate_of_interest, "%") | Rate of interest = 4.5 % | |
| 8 | 9 | print("Time =", time, "years") | Time = 10 years | |
| 9 | 10 | print("Simple Interest =", simple_interest) | Simple Interest = 900.0 | |
| 10 | 11 | print("Total amount =", amount) | Total amount = 2900.0 |
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)
Enter length of the rectangle : 12
Enter breadth of the rectangle: 8
Area of rectangle = 96.0
Perimeter of rectangle = 40.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
length, breadth๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q8.py. - Press F5 (Run โ Run Module).
- When the program asks, type 12, 8 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | length = float(input("Enter length of the rectangle : ")) | length = 12.0 | Enter length of the rectangle : 12 |
| 2 | 3 | breadth = float(input("Enter breadth of the rectangle: ")) | breadth = 8.0 | Enter breadth of the rectangle: 8 |
| 3 | 4 | area = length * breadth | area = 96.0 | |
| 4 | 5 | perimeter = 2 * (length + breadth) | perimeter = 40.0 | |
| 5 | 6 | print("Area of rectangle =", area) | Area of rectangle = 96.0 | |
| 6 | 7 | print("Perimeter of rectangle =", perimeter) | Perimeter of rectangle = 40.0 |
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)
Enter base of the triangle : 10
Enter height of the triangle: 6
Area of triangle = 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
base, height๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q9.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10, 6 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | base = float(input("Enter base of the triangle : ")) | base = 10.0 | Enter base of the triangle : 10 |
| 2 | 3 | height = float(input("Enter height of the triangle: ")) | height = 6.0 | Enter height of the triangle: 6 |
| 3 | 4 | area = 0.5 * base * height | area = 30.0 | |
| 4 | 5 | print("Area of triangle =", area) | Area of triangle = 30.0 |
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))
Enter marks in English : 78
Enter marks in Maths : 92
Enter marks in Science : 85
Total marks = 255.0
Average marks = 85.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
eng, maths, sci๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q10.py. - Press F5 (Run โ Run Module).
- When the program asks, type 78, 92, 85 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | eng = float(input("Enter marks in English : ")) | eng = 78.0 | Enter marks in English : 78 |
| 2 | 3 | maths = float(input("Enter marks in Maths : ")) | maths = 92.0 | Enter marks in Maths : 92 |
| 3 | 4 | sci = float(input("Enter marks in Science : ")) | sci = 85.0 | Enter marks in Science : 85 |
| 4 | 5 | total = eng + maths + sci | total = 255.0 | |
| 5 | 6 | average = total / 3 | average = 85.0 | |
| 6 | 7 | print("Total marks =", total) | Total marks = 255.0 | |
| 7 | 8 | print("Average marks =", round(average, 2)) | Average marks = 85.0 |
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)
Enter the marked price (Rs.): 1500
Enter discount % : 20
Discount given = Rs. 300.0
Amount to be paid = Rs. 1200.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
price, disc_percent๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q11.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1500, 20 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | price = float(input("Enter the marked price (Rs.): ")) | price = 1500.0 | Enter the marked price (Rs.): 1500 |
| 2 | 3 | disc_percent = float(input("Enter discount % : ")) | disc_percent = 20.0 | Enter discount % : 20 |
| 3 | 4 | discount = price * disc_percent / 100 | discount = 300.0 | |
| 4 | 5 | final_amount = price - discount | final_amount = 1200.0 | |
| 5 | 6 | print("Discount given = Rs.", discount) | Discount given = Rs. 300.0 | |
| 6 | 7 | print("Amount to be paid = Rs.", final_amount) | Amount to be paid = Rs. 1200.0 |
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)
Enter length : 5
Enter breadth : 4
Enter height : 3
Total surface area of cuboid = 94.0
Volume of cuboid = 60.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
l, b, h๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q12.py. - Press F5 (Run โ Run Module).
- When the program asks, type 5, 4, 3 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | l = float(input("Enter length : ")) | l = 5.0 | Enter length : 5 |
| 2 | 3 | b = float(input("Enter breadth : ")) | b = 4.0 | Enter breadth : 4 |
| 3 | 4 | h = float(input("Enter height : ")) | h = 3.0 | Enter height : 3 |
| 4 | 5 | surface_area = 2 * (l*b + b*h + h*l) | surface_area = 94.0 | |
| 5 | 6 | volume = l * b * h | volume = 60.0 | |
| 6 | 7 | print("Total surface area of cuboid =", surface_area) | Total surface area of cuboid = 94.0 | |
| 7 | 8 | print("Volume of cuboid =", volume) | Volume of cuboid = 60.0 |
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)
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']
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q13.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | quiz = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"] | quiz = ['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik'] | |
| 2 | 3 | print("Whole list :", quiz) | Whole list : ['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik'] | |
| 3 | 5 | quiz.remove("Vikram") # delete by value | quiz = ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik'] | |
| 4 | 6 | print("After deleting Vikram:", quiz) | After deleting Vikram: ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik'] | |
| 5 | 8 | quiz.append("Jay") # add at the end | quiz = ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay'] | |
| 6 | 9 | print("After adding Jay :", quiz) | After adding Jay : ['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay'] | |
| 7 | 11 | del quiz[1] # second position = index 1 | quiz = ['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay'] | |
| 8 | 12 | print("After removing item at 2nd position:", quiz) | After removing item at 2nd position: ['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay'] |
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])
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]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q14.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | num = [23, 12, 5, 9, 65, 44] | num = [23, 12, 5, 9, 65, 44] | |
| 2 | 3 | print("List :", num) | List : [23, 12, 5, 9, 65, 44] | |
| 3 | 4 | print("Length of the list =", len(num)) | Length of the list = 6 | |
| 4 | 6 | print("2nd to 4th (positive indexing):", num[1:4]) | 2nd to 4th (positive indexing): [12, 5, 9] | |
| 5 | 8 | print("3rd to 5th (negative indexing):", num[-4:-1]) | 3rd to 5th (negative indexing): [5, 9, 65] |
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)
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]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q15.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] | even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] | |
| 2 | 3 | print("First 10 even numbers:", even) | First 10 even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] | |
| 3 | 4 | for i in range(len(even)): next item taken | i = 0 | |
| 4 | 5 | even[i] = even[i] + 1 | even = [3, 4, 6, 8, 10, 12, 14, 16, 18, 20] | |
| 5 | 4 | for i in range(len(even)): next item taken | i = 1 | |
| 6 | 5 | even[i] = even[i] + 1 | even = [3, 5, 6, 8, 10, 12, 14, 16, 18, 20] | |
| 7 | 4 | for i in range(len(even)): next item taken | i = 2 | |
| 8 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 8, 10, 12, 14, 16, 18, 20] | |
| 9 | 4 | for i in range(len(even)): next item taken | i = 3 | |
| 10 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 10, 12, 14, 16, 18, 20] | |
| 11 | 4 | for i in range(len(even)): next item taken | i = 4 | |
| 12 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 12, 14, 16, 18, 20] | |
| 13 | 4 | for i in range(len(even)): next item taken | i = 5 | |
| 14 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 13, 14, 16, 18, 20] | |
| 15 | 4 | for i in range(len(even)): next item taken | i = 6 | |
| 16 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 13, 15, 16, 18, 20] | |
| 17 | 4 | for i in range(len(even)): next item taken | i = 7 | |
| 18 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 13, 15, 17, 18, 20] | |
| 19 | 4 | for i in range(len(even)): next item taken | i = 8 | |
| 20 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20] | |
| 21 | 4 | for i in range(len(even)): next item taken | i = 9 | |
| 22 | 5 | even[i] = even[i] + 1 | even = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21] | |
| 23 | 4 | for i in range(len(even)): no items left โ loop ends | ||
| 24 | 6 | print("After adding 1 :", even) | After adding 1 : [3, 5, 7, 9, 11, 13, 15, 17, 19, 21] |
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)
After extend : [10, 20, 30, 40, 14, 15, 12]
Sorted list : [10, 12, 14, 15, 20, 30, 40]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q16.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | List_1 = [10, 20, 30, 40] | List_1 = [10, 20, 30, 40] | |
| 2 | 3 | List_1.extend([14, 15, 12]) | List_1 = [10, 20, 30, 40, 14, 15, 12] | |
| 3 | 4 | print("After extend :", List_1) | After extend : [10, 20, 30, 40, 14, 15, 12] | |
| 4 | 5 | List_1.sort() | List_1 = [10, 12, 14, 15, 20, 30, 40] | |
| 5 | 6 | print("Sorted list :", List_1) | Sorted list : [10, 12, 14, 15, 20, 30, 40] |
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).")
Enter your name: Riya
Enter your age : 15
Riya is not eligible to vote. Wait for 3 more year(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
name, age๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q17.py. - Press F5 (Run โ Run Module).
- When the program asks, type Riya, 15 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | name = input("Enter your name: ") | name = 'Riya' | Enter your name: Riya |
| 2 | 3 | age = int(input("Enter your age : ")) | age = 15 | Enter your age : 15 |
| 3 | 4 | if age >= 18: condition is FALSE โ skips this block | ||
| 4 | 7 | 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). |
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)
Enter percentage marks: 84.5
Grade = A2
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
marks๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q18.py. - Press F5 (Run โ Run Module).
- When the program asks, type 84.5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | marks = float(input("Enter percentage marks: ")) | marks = 84.5 | Enter percentage marks: 84.5 |
| 2 | 3 | if marks >= 90: condition is FALSE โ skips this block | ||
| 3 | 5 | elif marks >= 80: condition is TRUE โ enters the block | ||
| 4 | 6 | grade = "A2" | grade = 'A2' | |
| 5 | 17 | print("Grade =", grade) | Grade = A2 |
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")
Enter a number: -7
-7.0 is a NEGATIVE number
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q19.py. - Press F5 (Run โ Run Module).
- When the program asks, type -7 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | n = float(input("Enter a number: ")) | n = -7.0 | Enter a number: -7 |
| 2 | 3 | if n > 0: condition is FALSE โ skips this block | ||
| 3 | 5 | elif n < 0: condition is TRUE โ enters the block | ||
| 4 | 6 | print(n, "is a NEGATIVE number") | -7.0 is a NEGATIVE number |
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()
First 10 natural numbers:
1 2 3 4 5 6 7 8 9 10
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q20.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | print("First 10 natural numbers:") | First 10 natural numbers: | |
| 2 | 3 | for i in range(1, 11): next item taken | i = 1 | |
| 3 | 4 | print(i, end=" ") | 1 | |
| 4 | 3 | for i in range(1, 11): next item taken | i = 2 | |
| 5 | 4 | print(i, end=" ") | 2 | |
| 6 | 3 | for i in range(1, 11): next item taken | i = 3 | |
| 7 | 4 | print(i, end=" ") | 3 | |
| 8 | 3 | for i in range(1, 11): next item taken | i = 4 | |
| 9 | 4 | print(i, end=" ") | 4 | |
| 10 | 3 | for i in range(1, 11): next item taken | i = 5 | |
| 11 | 4 | print(i, end=" ") | 5 | |
| 12 | 3 | for i in range(1, 11): next item taken | i = 6 | |
| 13 | 4 | print(i, end=" ") | 6 | |
| 14 | 3 | for i in range(1, 11): next item taken | i = 7 | |
| 15 | 4 | print(i, end=" ") | 7 | |
| 16 | 3 | for i in range(1, 11): next item taken | i = 8 | |
| 17 | 4 | print(i, end=" ") | 8 | |
| 18 | 3 | for i in range(1, 11): next item taken | i = 9 | |
| 19 | 4 | print(i, end=" ") | 9 | |
| 20 | 3 | for i in range(1, 11): next item taken | i = 10 | |
| 21 | 4 | print(i, end=" ") | 10 | |
| 22 | 3 | for i in range(1, 11): no items left โ loop ends | ||
| 23 | 5 | print() |
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()
First 10 even numbers:
2 4 6 8 10 12 14 16 18 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q21.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | print("First 10 even numbers:") | First 10 even numbers: | |
| 2 | 3 | for i in range(2, 21, 2): next item taken | i = 2 | |
| 3 | 4 | print(i, end=" ") | 2 | |
| 4 | 3 | for i in range(2, 21, 2): next item taken | i = 4 | |
| 5 | 4 | print(i, end=" ") | 4 | |
| 6 | 3 | for i in range(2, 21, 2): next item taken | i = 6 | |
| 7 | 4 | print(i, end=" ") | 6 | |
| 8 | 3 | for i in range(2, 21, 2): next item taken | i = 8 | |
| 9 | 4 | print(i, end=" ") | 8 | |
| 10 | 3 | for i in range(2, 21, 2): next item taken | i = 10 | |
| 11 | 4 | print(i, end=" ") | 10 | |
| 12 | 3 | for i in range(2, 21, 2): next item taken | i = 12 | |
| 13 | 4 | print(i, end=" ") | 12 | |
| 14 | 3 | for i in range(2, 21, 2): next item taken | i = 14 | |
| 15 | 4 | print(i, end=" ") | 14 | |
| 16 | 3 | for i in range(2, 21, 2): next item taken | i = 16 | |
| 17 | 4 | print(i, end=" ") | 16 | |
| 18 | 3 | for i in range(2, 21, 2): next item taken | i = 18 | |
| 19 | 4 | print(i, end=" ") | 18 | |
| 20 | 3 | for i in range(2, 21, 2): next item taken | i = 20 | |
| 21 | 4 | print(i, end=" ") | 20 | |
| 22 | 3 | for i in range(2, 21, 2): no items left โ loop ends | ||
| 23 | 5 | print() |
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()
Enter the value of n: 15
Odd numbers from 1 to 15 :
1 3 5 7 9 11 13 15
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q22.py. - Press F5 (Run โ Run Module).
- When the program asks, type 15 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | n = int(input("Enter the value of n: ")) | n = 15 | Enter the value of n: 15 |
| 2 | 3 | i = 1 | i = 1 | |
| 3 | 4 | print("Odd numbers from 1 to", n, ":") | Odd numbers from 1 to 15 : | |
| 4 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 5 | 6 | print(i, end=" ") | 1 | |
| 6 | 7 | i = i + 2 | i = 3 | |
| 7 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 8 | 6 | print(i, end=" ") | 3 | |
| 9 | 7 | i = i + 2 | i = 5 | |
| 10 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 11 | 6 | print(i, end=" ") | 5 | |
| 12 | 7 | i = i + 2 | i = 7 | |
| 13 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 14 | 6 | print(i, end=" ") | 7 | |
| 15 | 7 | i = i + 2 | i = 9 | |
| 16 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 17 | 6 | print(i, end=" ") | 9 | |
| 18 | 7 | i = i + 2 | i = 11 | |
| 19 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 20 | 6 | print(i, end=" ") | 11 | |
| 21 | 7 | i = i + 2 | i = 13 | |
| 22 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 23 | 6 | print(i, end=" ") | 13 | |
| 24 | 7 | i = i + 2 | i = 15 | |
| 25 | 5 | while i <= n: condition is TRUE โ enters the block | ||
| 26 | 6 | print(i, end=" ") | 15 | |
| 27 | 7 | i = i + 2 | i = 17 | |
| 28 | 5 | while i <= n: condition is FALSE โ loop ends | ||
| 29 | 8 | print() |
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)
Sum of first 10 natural numbers = 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q23.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | total = 0 | total = 0 | |
| 2 | 3 | for i in range(1, 11): next item taken | i = 1 | |
| 3 | 4 | total = total + i | total = 1 | |
| 4 | 3 | for i in range(1, 11): next item taken | i = 2 | |
| 5 | 4 | total = total + i | total = 3 | |
| 6 | 3 | for i in range(1, 11): next item taken | i = 3 | |
| 7 | 4 | total = total + i | total = 6 | |
| 8 | 3 | for i in range(1, 11): next item taken | i = 4 | |
| 9 | 4 | total = total + i | total = 10 | |
| 10 | 3 | for i in range(1, 11): next item taken | i = 5 | |
| 11 | 4 | total = total + i | total = 15 | |
| 12 | 3 | for i in range(1, 11): next item taken | i = 6 | |
| 13 | 4 | total = total + i | total = 21 | |
| 14 | 3 | for i in range(1, 11): next item taken | i = 7 | |
| 15 | 4 | total = total + i | total = 28 | |
| 16 | 3 | for i in range(1, 11): next item taken | i = 8 | |
| 17 | 4 | total = total + i | total = 36 | |
| 18 | 3 | for i in range(1, 11): next item taken | i = 9 | |
| 19 | 4 | total = total + i | total = 45 | |
| 20 | 3 | for i in range(1, 11): next item taken | i = 10 | |
| 21 | 4 | total = total + i | total = 55 | |
| 22 | 3 | for i in range(1, 11): no items left โ loop ends | ||
| 23 | 5 | print("Sum of first 10 natural numbers =", total) | Sum of first 10 natural numbers = 55 |
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))
List : [12, 45, 7, 23, 56, 89, 34]
Sum using loop = 266
Sum using sum() = 266
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
ix_ai_q24.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | numbers = [12, 45, 7, 23, 56, 89, 34] | numbers = [12, 45, 7, 23, 56, 89, 34] | |
| 2 | 3 | total = 0 | total = 0 | |
| 3 | 4 | for x in numbers: next item taken | x = 12 | |
| 4 | 5 | total = total + x | total = 12 | |
| 5 | 4 | for x in numbers: next item taken | x = 45 | |
| 6 | 5 | total = total + x | total = 57 | |
| 7 | 4 | for x in numbers: next item taken | x = 7 | |
| 8 | 5 | total = total + x | total = 64 | |
| 9 | 4 | for x in numbers: next item taken | x = 23 | |
| 10 | 5 | total = total + x | total = 87 | |
| 11 | 4 | for x in numbers: next item taken | x = 56 | |
| 12 | 5 | total = total + x | total = 143 | |
| 13 | 4 | for x in numbers: next item taken | x = 89 | |
| 14 | 5 | total = total + x | total = 232 | |
| 15 | 4 | for x in numbers: next item taken | x = 34 | |
| 16 | 5 | total = total + x | total = 266 | |
| 17 | 4 | for x in numbers: no items left โ loop ends | ||
| 18 | 6 | print("List :", numbers) | List : [12, 45, 7, 23, 56, 89, 34] | |
| 19 | 7 | print("Sum using loop =", total) | Sum using loop = 266 | |
| 20 | 8 | print("Sum using sum() =", sum(numbers)) | Sum using sum() = 266 |
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: 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).
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: 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.
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
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.
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).
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.
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.
Mode colour: White | P(White) = 0.37 | P(not Red) = 0.87
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 %
Accuracy of the model = 85 %
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
Score in Real vs AI: 5 / 6 identified correctly.
Learning: AI images look real, so always verify the source before sharing.
๐ 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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)
| Component | Marks |
|---|---|
| Practical File with minimum 15 programs | 15 |
| Practical Examination - Statistical Data, Computer Vision, NLP, Advance Python | 15 |
| Viva Voce | 5 |
| 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.
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)
=============================================
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
=============================================
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q1.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | name = "Ananya Verma" | name = 'Ananya Verma' | |
| 2 | 3 | father_name = "Mr. Sanjay Verma" | father_name = 'Mr. Sanjay Verma' | |
| 3 | 4 | mother_name = "Mrs. Kavita Verma" | mother_name = 'Mrs. Kavita Verma' | |
| 4 | 5 | class_name = "X - B" | class_name = 'X - B' | |
| 5 | 6 | school_name = "PM SHRI Kendriya Vidyalaya Shalimar Bagh" | school_name = 'PM SHRI Kendriya Vidyalaya Shalimar Bagh' | |
| 6 | 7 | hobbies = "Coding, Chess, Reading" | hobbies = 'Coding, Chess, Reading' | |
| 7 | 9 | print("=" * 45) | ============================================= | |
| 8 | 10 | print(" BIO-DATA") | BIO-DATA | |
| 9 | 11 | print("=" * 45) | ============================================= | |
| 10 | 12 | print("Name :", name) | Name : Ananya Verma | |
| 11 | 13 | print("Father's Name :", father_name) | Father's Name : Mr. Sanjay Verma | |
| 12 | 14 | print("Mother's Name :", mother_name) | Mother's Name : Mrs. Kavita Verma | |
| 13 | 15 | print("Class :", class_name) | Class : X - B | |
| 14 | 16 | print("School :", school_name) | School : PM SHRI Kendriya Vidyalaya Shalimar Bagh | |
| 15 | 17 | print("Hobbies :", hobbies) | Hobbies : Coding, Chess, Reading | |
| 16 | 18 | print("=" * 45) | ============================================= |
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")
Enter temperature in Celsius: 45
45.0 degree Celsius = 113.0 degree Fahrenheit
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
celsius๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q2.py. - Press F5 (Run โ Run Module).
- When the program asks, type 45 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | celsius = float(input("Enter temperature in Celsius: ")) | celsius = 45.0 | Enter temperature in Celsius: 45 |
| 2 | 3 | fahrenheit = (celsius * 9 / 5) + 32 | fahrenheit = 113.0 | |
| 3 | 4 | print(celsius, "degree Celsius =", fahrenheit, "degree Fahrenheit") | 45.0 degree Celsius = 113.0 degree Fahrenheit |
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.")
Enter a number: 48
48 is an EVEN number.
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
number๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q3.py. - Press F5 (Run โ Run Module).
- When the program asks, type 48 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | number = int(input("Enter a number: ")) | number = 48 | Enter a number: 48 |
| 2 | 3 | if number % 2 == 0: condition is TRUE โ enters the block | ||
| 3 | 4 | print(number, "is an EVEN number.") | 48 is an EVEN number. |
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.")
----- 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!
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
choice, num1, num2๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q4.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | while True: condition is TRUE โ enters the block | ||
| 2 | 3 | print("\n----- MENU -----") | ----- MENU ----- | |
| 3 | 4 | print("1. Addition") | 1. Addition | |
| 4 | 5 | print("2. Subtraction") | 2. Subtraction | |
| 5 | 6 | print("3. Multiplication") | 3. Multiplication | |
| 6 | 7 | print("4. Division") | 4. Division | |
| 7 | 8 | print("5. Exit") | 5. Exit | |
| 8 | 9 | choice = input("Enter your choice (1-5): ") | choice = '1' | Enter your choice (1-5): 1 |
| 9 | 10 | if choice == '5': condition is FALSE โ skips this block | ||
| 10 | 13 | if choice not in ('1', '2', '3', '4'):condition is FALSE โ skips this block | ||
| 11 | 16 | num1 = float(input("Enter first number : ")) | num1 = 34.0 | Enter first number : 34 |
| 12 | 17 | num2 = float(input("Enter second number: ")) | num2 = 65.0 | Enter second number: 65 |
| 13 | 18 | if choice == '1': condition is TRUE โ enters the block | ||
| 14 | 19 | print("Result:", num1 + num2) | Result: 99.0 | |
| 15 | 2 | while True: condition is TRUE โ enters the block | ||
| 16 | 3 | print("\n----- MENU -----") | ----- MENU ----- | |
| 17 | 4 | print("1. Addition") | 1. Addition | |
| 18 | 5 | print("2. Subtraction") | 2. Subtraction | |
| 19 | 6 | print("3. Multiplication") | 3. Multiplication | |
| 20 | 7 | print("4. Division") | 4. Division | |
| 21 | 8 | print("5. Exit") | 5. Exit | |
| 22 | 9 | choice = input("Enter your choice (1-5): ") | choice = '4' | Enter your choice (1-5): 4 |
| 23 | 10 | if choice == '5': condition is FALSE โ skips this block | ||
| 24 | 13 | if choice not in ('1', '2', '3', '4'):condition is FALSE โ skips this block | ||
| 25 | 16 | num1 = float(input("Enter first number : ")) | num1 = 45.0 | Enter first number : 45 |
| 26 | 17 | num2 = float(input("Enter second number: ")) | num2 = 0.0 | Enter second number: 0 |
| 27 | 18 | if choice == '1': condition is FALSE โ skips this block | ||
| 28 | 20 | elif choice == '2': condition is FALSE โ skips this block | ||
| 29 | 22 | elif choice == '3': condition is FALSE โ skips this block | ||
| 30 | 24 | elif choice == '4': condition is TRUE โ enters the block | ||
| 31 | 25 | if num2 != 0: condition is FALSE โ skips this block | ||
| 32 | 28 | 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
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)
Enter your name: Kendriya Vidyalaya
1 Kendriya Vidyalaya
2 Kendriya Vidyalaya
3 Kendriya Vidyalaya
4 Kendriya Vidyalaya
5 Kendriya Vidyalaya
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
name๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q5.py. - Press F5 (Run โ Run Module).
- When the program asks, type Kendriya Vidyalaya (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | name = input("Enter your name: ") | name = 'Kendriya Vidyalaya' | Enter your name: Kendriya Vidyalaya |
| 2 | 3 | for i in range(5): next item taken | i = 0 | |
| 3 | 4 | print(i + 1, name) | 1 Kendriya Vidyalaya | |
| 4 | 3 | for i in range(5): next item taken | i = 1 | |
| 5 | 4 | print(i + 1, name) | 2 Kendriya Vidyalaya | |
| 6 | 3 | for i in range(5): next item taken | i = 2 | |
| 7 | 4 | print(i + 1, name) | 3 Kendriya Vidyalaya | |
| 8 | 3 | for i in range(5): next item taken | i = 3 | |
| 9 | 4 | print(i + 1, name) | 4 Kendriya Vidyalaya | |
| 10 | 3 | for i in range(5): next item taken | i = 4 | |
| 11 | 4 | print(i + 1, name) | 5 Kendriya Vidyalaya | |
| 12 | 3 | for i in range(5): no items left โ loop ends |
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)
Enter first number : 45
Enter second number: 95
HCF = 5
LCM = 855
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
num1, num2๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q6.py. - Press F5 (Run โ Run Module).
- When the program asks, type 45, 95 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | num1 = int(input("Enter first number : ")) | num1 = 45 | Enter first number : 45 |
| 2 | 3 | num2 = int(input("Enter second number: ")) | num2 = 95 | Enter second number: 95 |
| 3 | 4 | small = min(num1, num2) | small = 45 | |
| 4 | 5 | hcf = 1 | hcf = 1 | |
| 5 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 1 | |
| 6 | 7 | if num1 % i == 0 and num2 % i == 0: condition is TRUE โ enters the block | ||
| 7 | 8 | hcf = i | ||
| 8 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 2 | |
| 9 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 10 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 3 | |
| 11 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 12 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 4 | |
| 13 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 14 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 5 | |
| 15 | 7 | if num1 % i == 0 and num2 % i == 0: condition is TRUE โ enters the block | ||
| 16 | 8 | hcf = i | hcf = 5 | |
| 17 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 6 | |
| 18 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 19 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 7 | |
| 20 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 21 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 8 | |
| 22 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 23 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 9 | |
| 24 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 25 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 10 | |
| 26 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 27 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 11 | |
| 28 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 29 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 12 | |
| 30 | 7 | if num1 % i == 0 and num2 % i == 0: condition is FALSE โ skips this block | ||
| 31 | 6 | for i in range(1, small + 1): # include 'small' itself next item taken | i = 13 | |
| 32 | 7 | 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
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)
Enter the number of rows: 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
rows๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q7.py. - Press F5 (Run โ Run Module).
- When the program asks, type 5 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | rows = int(input("Enter the number of rows: ")) | rows = 5 | Enter the number of rows: 5 |
| 2 | 3 | for i in range(1, rows + 1): next item taken | i = 1 | |
| 3 | 4 | print('* ' * i) | * | |
| 4 | 3 | for i in range(1, rows + 1): next item taken | i = 2 | |
| 5 | 4 | print('* ' * i) | * * | |
| 6 | 3 | for i in range(1, rows + 1): next item taken | i = 3 | |
| 7 | 4 | print('* ' * i) | * * * | |
| 8 | 3 | for i in range(1, rows + 1): next item taken | i = 4 | |
| 9 | 4 | print('* ' * i) | * * * * | |
| 10 | 3 | for i in range(1, rows + 1): next item taken | i = 5 | |
| 11 | 4 | print('* ' * i) | * * * * * | |
| 12 | 3 | for i in range(1, rows + 1): no items left โ loop ends |
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)
Enter a string: pm shri kendriya vidyalaya shalimar bagh
Total number of vowels : 12
Total number of consonants : 23
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
text๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q8.py. - Press F5 (Run โ Run Module).
- When the program asks, type pm shri kendriya vidyalaya shalimar bagh (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | text = input("Enter a string: ") | text = 'pm shri kendriya vidyalaya shalimar bagh' | Enter a string: pm shri kendriya vidyalaya shalimar bagh |
| 2 | 3 | v = c = 0 | v = 0, c = 0 | |
| 3 | 4 | for ch in text: next item taken | ch = 'p' | |
| 4 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 5 | 6 | if ch in "aeiouAEIOU": condition is FALSE โ skips this block | ||
| 6 | 9 | c += 1 | c = 1 | |
| 7 | 4 | for ch in text: next item taken | ch = 'm' | |
| 8 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 9 | 6 | if ch in "aeiouAEIOU": condition is FALSE โ skips this block | ||
| 10 | 9 | c += 1 | c = 2 | |
| 11 | 4 | for ch in text: next item taken | ch = ' ' | |
| 12 | 5 | if ch.isalpha(): condition is FALSE โ skips this block | ||
| 13 | 4 | for ch in text: next item taken | ch = 's' | |
| 14 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 15 | 6 | if ch in "aeiouAEIOU": condition is FALSE โ skips this block | ||
| 16 | 9 | c += 1 | c = 3 | |
| 17 | 4 | for ch in text: next item taken | ch = 'h' | |
| 18 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 19 | 6 | if ch in "aeiouAEIOU": condition is FALSE โ skips this block | ||
| 20 | 9 | c += 1 | c = 4 | |
| 21 | 4 | for ch in text: next item taken | ch = 'r' | |
| 22 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 23 | 6 | if ch in "aeiouAEIOU": condition is FALSE โ skips this block | ||
| 24 | 9 | c += 1 | c = 5 | |
| 25 | 4 | for ch in text: next item taken | ch = 'i' | |
| 26 | 5 | if ch.isalpha(): condition is TRUE โ enters the block | ||
| 27 | 6 | if ch in "aeiouAEIOU": condition is TRUE โ enters the block | ||
| 28 | 7 | v += 1 | v = 1 | |
| 29 | 4 | for ch in text: next item taken | ch = ' ' | |
| 30 | 5 | if ch.isalpha(): condition is FALSE โ skips this block | ||
| 31 | 4 | for ch in text: next item taken | ch = 'k' | |
| 32 | 5 | 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'
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")
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
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
choice, element๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q9.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | my_list = [] | my_list = [] | |
| 2 | 3 | while True: condition is TRUE โ enters the block | ||
| 3 | 4 | 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 | |
| 4 | 5 | choice = input("Enter your choice: ") | choice = '1' | Enter your choice: 1 |
| 5 | 6 | if choice == '1': condition is TRUE โ enters the block | ||
| 6 | 7 | element = input("Enter element to insert: ") | element = 'AI' | Enter element to insert: AI |
| 7 | 8 | my_list.append(element) | my_list = ['AI'] | |
| 8 | 9 | print(element, "inserted.") | AI inserted. | |
| 9 | 3 | while True: condition is TRUE โ enters the block | ||
| 10 | 4 | 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 | |
| 11 | 5 | choice = input("Enter your choice: ") | Enter your choice: 1 | |
| 12 | 6 | if choice == '1': condition is TRUE โ enters the block | ||
| 13 | 7 | element = input("Enter element to insert: ") | element = 'ML' | Enter element to insert: ML |
| 14 | 8 | my_list.append(element) | my_list = ['AI', 'ML'] | |
| 15 | 9 | print(element, "inserted.") | ML inserted. | |
| 16 | 3 | while True: condition is TRUE โ enters the block | ||
| 17 | 4 | 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 | |
| 18 | 5 | choice = input("Enter your choice: ") | Enter your choice: 1 | |
| 19 | 6 | if choice == '1': condition is TRUE โ enters the block | ||
| 20 | 7 | element = input("Enter element to insert: ") | element = 'DL' | Enter element to insert: DL |
| 21 | 8 | my_list.append(element) | my_list = ['AI', 'ML', 'DL'] | |
| 22 | 9 | print(element, "inserted.") | DL inserted. | |
| 23 | 3 | while True: condition is TRUE โ enters the block | ||
| 24 | 4 | 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 | |
| 25 | 5 | choice = input("Enter your choice: ") | choice = '3' | Enter your choice: 3 |
| 26 | 6 | if choice == '1': condition is FALSE โ skips this block | ||
| 27 | 10 | elif choice == '2': condition is FALSE โ skips this block | ||
| 28 | 17 | elif choice == '3': condition is TRUE โ enters the block | ||
| 29 | 18 | print("List:", my_list) | List: ['AI', 'ML', 'DL'] | |
| 30 | 3 | while True: condition is TRUE โ enters the block | ||
| 31 | 4 | 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 | |
| 32 | 5 | 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'
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))
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]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q10.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | list1 = [10, 20, 30, 40, 50] | list1 = [10, 20, 30, 40, 50] | |
| 2 | 3 | list2 = [5, 15, 25, 35, 45] | list2 = [5, 15, 25, 35, 45] | |
| 3 | 4 | result = [] | result = [] | |
| 4 | 5 | for i in range(len(list1)): next item taken | i = 0 | |
| 5 | 6 | result.append(list1[i] + list2[i]) | result = [15] | |
| 6 | 5 | for i in range(len(list1)): next item taken | i = 1 | |
| 7 | 6 | result.append(list1[i] + list2[i]) | result = [15, 35] | |
| 8 | 5 | for i in range(len(list1)): next item taken | i = 2 | |
| 9 | 6 | result.append(list1[i] + list2[i]) | result = [15, 35, 55] | |
| 10 | 5 | for i in range(len(list1)): next item taken | i = 3 | |
| 11 | 6 | result.append(list1[i] + list2[i]) | result = [15, 35, 55, 75] | |
| 12 | 5 | for i in range(len(list1)): next item taken | i = 4 | |
| 13 | 6 | result.append(list1[i] + list2[i]) | result = [15, 35, 55, 75, 95] | |
| 14 | 5 | for i in range(len(list1)): no items left โ loop ends | ||
| 15 | 7 | print("List 1 :", list1) | List 1 : [10, 20, 30, 40, 50] | |
| 16 | 8 | print("List 2 :", list2) | List 2 : [5, 15, 25, 35, 45] | |
| 17 | 9 | print("Sum :", result) | Sum : [15, 35, 55, 75, 95] | |
| 18 | 12 | import numpy as np | ||
| 19 | 13 | print("Using NumPy:", np.array(list1) + np.array(list2)) | Using NumPy: [15 35 55 75 95] |
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)
Given List: [10, 20, 30, 40, 50]
Mean: 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q11.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | numbers = [10, 20, 30, 40, 50] | numbers = [10, 20, 30, 40, 50] | |
| 2 | 3 | mean = sum(numbers) / len(numbers) | mean = 30.0 | |
| 3 | 4 | print("Given List:", numbers) | Given List: [10, 20, 30, 40, 50] | |
| 4 | 5 | print("Mean:", mean) | Mean: 30.0 |
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)
[[1 2 3]
[4 5 6]]
Dimensions (ndim): 2
Shape : (2, 3)
Total elements : 6
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q12.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | array_2d = np.array([[1, 2, 3], [4, 5, 6]]) | array_2d = array([[1, 2, 3], [4, 5, 6]]) | |
| 3 | 4 | print(array_2d) | [[1 2 3] [4 5 6]] | |
| 4 | 5 | print("Dimensions (ndim):", array_2d.ndim) | Dimensions (ndim): 2 | |
| 5 | 6 | print("Shape :", array_2d.shape) | Shape : (2, 3) | |
| 6 | 7 | print("Total elements :", array_2d.size) | Total elements : 6 |
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)
Python list : [10, 20, 30, 40] <class 'list'>
NumPy array : [10 20 30 40] <class 'numpy.ndarray'>
Array * 2 : [20 40 60 80]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q13.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | my_list = [10, 20, 30, 40] | my_list = [10, 20, 30, 40] | |
| 3 | 4 | numpy_array = np.array(my_list) | numpy_array = array([10, 20, 30, 40]) | |
| 4 | 5 | print("Python list :", my_list, type(my_list)) | Python list : [10, 20, 30, 40] <class 'list'> | |
| 5 | 6 | print("NumPy array :", numpy_array, type(numpy_array)) | NumPy array : [10 20 30 40] <class 'numpy.ndarray'> | |
| 6 | 7 | print("Array * 2 :", numpy_array * 2) | Array * 2 : [20 40 60 80] |
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)
[[11 12 13]
[14 15 16]
[17 18 19]]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q14.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | matrix_3x3 = np.arange(11, 20).reshape(3, 3) | matrix_3x3 = array of shape (3, 3) | |
| 3 | 4 | print(matrix_3x3) | [[11 12 13] [14 15 16] [17 18 19]] |
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)")
Marks : [45 67 89 67 90 56 67 78 89 72]
Mean : 72.0
Median : 69.5
Mode : 67 (occurs 3 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q15.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | marks = np.array([45, 67, 89, 67, 90, 56, 67, 78, 89, 72]) | marks = array of shape (10,) | |
| 3 | 4 | mean = np.mean(marks) | mean = np.float64(72.0) | |
| 4 | 5 | median = np.median(marks) | median = np.float64(69.5) | |
| 5 | 6 | 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]) | |
| 6 | 7 | mode = values[np.argmax(counts)] | mode = np.int64(67) | |
| 7 | 8 | print("Marks :", marks) | Marks : [45 67 89 67 90 56 67 78 89 72] | |
| 8 | 9 | print("Mean :", mean) | Mean : 72.0 | |
| 9 | 10 | print("Median :", median) | Median : 69.5 | |
| 10 | 11 | print("Mode :", mode, "(occurs", counts.max(), "times)") | Mode : 67 (occurs 3 times) |
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")
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!
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
ch๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q16.py. - Press F5 (Run โ Run Module).
- When the program asks, type 1, 2, 3, 4 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import statistics | ||
| 2 | 3 | data = [1, 2, 2, 3, 4, 5] | data = [1, 2, 2, 3, 4, 5] | |
| 3 | 4 | print("Data:", data) | Data: [1, 2, 2, 3, 4, 5] | |
| 4 | 5 | while True: condition is TRUE โ enters the block | ||
| 5 | 6 | print("\n1. Mean 2. Median 3. Mode 4. Exit") | 1. Mean 2. Median 3. Mode 4. Exit | |
| 6 | 7 | ch = input("Enter choice: ") | ch = '1' | Enter choice: 1 |
| 7 | 8 | if ch == '1': condition is TRUE โ enters the block | ||
| 8 | 9 | print("Mean =", round(statistics.mean(data), 2)) | Mean = 2.83 | |
| 9 | 5 | while True: condition is TRUE โ enters the block | ||
| 10 | 6 | print("\n1. Mean 2. Median 3. Mode 4. Exit") | 1. Mean 2. Median 3. Mode 4. Exit | |
| 11 | 7 | ch = input("Enter choice: ") | ch = '2' | Enter choice: 2 |
| 12 | 8 | if ch == '1': condition is FALSE โ skips this block | ||
| 13 | 10 | elif ch == '2': condition is TRUE โ enters the block | ||
| 14 | 11 | print("Median =", statistics.median(data)) | Median = 2.5 | |
| 15 | 5 | while True: condition is TRUE โ enters the block | ||
| 16 | 6 | print("\n1. Mean 2. Median 3. Mode 4. Exit") | 1. Mean 2. Median 3. Mode 4. Exit | |
| 17 | 7 | ch = input("Enter choice: ") | ch = '3' | Enter choice: 3 |
| 18 | 8 | if ch == '1': condition is FALSE โ skips this block | ||
| 19 | 10 | elif ch == '2': condition is FALSE โ skips this block | ||
| 20 | 12 | elif ch == '3': condition is TRUE โ enters the block | ||
| 21 | 13 | print("Mode =", statistics.mode(data)) | Mode = 2 | |
| 22 | 5 | while True: condition is TRUE โ enters the block | ||
| 23 | 6 | print("\n1. Mean 2. Median 3. Mode 4. Exit") | 1. Mean 2. Median 3. Mode 4. Exit | |
| 24 | 7 | ch = input("Enter choice: ") | ch = '4' | Enter choice: 4 |
| 25 | 8 | if ch == '1': condition is FALSE โ skips this block | ||
| 26 | 10 | elif ch == '2': condition is FALSE โ skips this block | ||
| 27 | 12 | elif ch == '3': condition is FALSE โ skips this block | ||
| 28 | 14 | elif ch == '4': condition is TRUE โ enters the block | ||
| 29 | 15 | print("Bye!") | Bye! | |
| 30 | 16 | break |
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))
Data : [10, 20, 30, 40, 50]
Variance : 250
Standard deviation : 15.8114
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q17.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import statistics | ||
| 2 | 3 | data = [10, 20, 30, 40, 50] | data = [10, 20, 30, 40, 50] | |
| 3 | 4 | variance = statistics.variance(data) # sample variance | variance = 250 | |
| 4 | 5 | std_dev = statistics.stdev(data) # sample standard deviation | std_dev = 15.811388300841896 | |
| 5 | 6 | print("Data :", data) | Data : [10, 20, 30, 40, 50] | |
| 6 | 7 | print("Variance :", variance) | Variance : 250 | |
| 7 | 8 | print("Standard deviation :", round(std_dev, 4)) | Standard deviation : 15.8114 |
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())
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q18.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'], | ||
| 3 | 4 | 'Age': [25, 30, 22, 27, 24], | ||
| 4 | 5 | 'Interview_Score': [85, 90, 88, 76, 93]} | ||
| 5 | 3 | data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'], | data = {'Name': ['Aman', 'Babita', 'Karan', 'Divya', 'Esha'], 'Age': [25, โฆ | |
| 6 | 6 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 3 columns) | |
| 7 | 7 | 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 | |
| 8 | 8 | print("\nHighest score:", df['Interview_Score'].max()) | Highest score: 93 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q19.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'], | ||
| 3 | 4 | 'Runs': [1450, 1820, 990, 560, 1105]} | ||
| 4 | 3 | data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'], | data = {'Player': ['Rohit', 'Virat', 'Shubman', 'Rinku', 'Hardik'], 'Runs'โฆ | |
| 5 | 5 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 2 columns) | |
| 6 | 6 | print("All players:\n", df) | All players:
Player Runs
0 Rohit 1450
1 Virat 1820
2 Shubman 990
3 Rinku 560
4 Hardik 1105 | |
| 7 | 7 | filtered_df = df[df['Runs'] > 1000] | filtered_df = DataFrame (3 rows ร 2 columns) | |
| 8 | 8 | print("\nPlayers with Runs > 1000:\n", filtered_df) |
Players with Runs > 1000:
Player Runs
0 Rohit 1450
1 Virat 1820
4 Hardik 1105 |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q20.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | x = [2, 9] | x = [2, 9] | |
| 3 | 4 | y = [5, 10] | y = [5, 10] | |
| 4 | 5 | plt.plot(x, y, color='blue', marker='o') | ||
| 5 | 6 | plt.title("Line chart from (2,5) to (9,10)") | ||
| 6 | 7 | plt.xlabel("X-axis") | ||
| 7 | 8 | plt.ylabel("Y-axis") | ||
| 8 | 9 | plt.grid(True) | ||
| 9 | 10 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q21.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | x = [2, 9, 8, 5, 6] | x = [2, 9, 8, 5, 6] | |
| 3 | 4 | y = [5, 10, 3, 7, 18] | y = [5, 10, 3, 7, 18] | |
| 4 | 5 | plt.scatter(x, y, color='red', s=60) | ||
| 5 | 6 | plt.title("Scatter Chart") | ||
| 6 | 7 | plt.xlabel("X-axis") | ||
| 7 | 8 | plt.ylabel("Y-axis") | ||
| 8 | 9 | plt.grid(True) | ||
| 9 | 10 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q22.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing'] | games = ['Chess', 'Ludo', 'Cricket', 'Puzzle', 'Racing'] | |
| 3 | 4 | ratings = [4.5, 4.0, 3.8, 4.2, 3.5] | ratings = [4.5, 4.0, 3.8, 4.2, 3.5] | |
| 4 | 5 | plt.bar(games, ratings, color=['teal', 'orange', 'green', 'purple', 'red']) | ||
| 5 | 6 | plt.xlabel('Games') | ||
| 6 | 7 | plt.ylabel('Ratings (out of 5)') | ||
| 7 | 8 | plt.title('Mobile Game Ratings') | ||
| 8 | 9 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q23.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] | months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] | |
| 3 | 4 | sales = [5000, 6000, 5500, 7000, 8000, 7600] | sales = [5000, 6000, 5500, 7000, 8000, 7600] | |
| 4 | 5 | plt.plot(months, sales, marker='o', color='green', linewidth=2) | ||
| 5 | 6 | plt.xlabel('Months') | ||
| 6 | 7 | plt.ylabel('Sales (Rs.)') | ||
| 7 | 8 | plt.title('Monthly Sales Data for Garments') | ||
| 8 | 9 | plt.grid(True) | ||
| 9 | 10 | plt.show() |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q24.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 3 | import pandas as pd | ||
| 2 | 4 | df = pd.read_csv("student_data.csv") | df = DataFrame (15 rows ร 6 columns) | |
| 3 | 5 | 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 โฆ |
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())
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q25.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | df = pd.read_csv("student_data.csv") | df = DataFrame (15 rows ร 6 columns) | |
| 3 | 4 | print("Shape (rows, columns):", df.shape) | Shape (rows, columns): (15, 6) | |
| 4 | 5 | print() | ||
| 5 | 6 | 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โฆ | |
| 6 | 7 | print() | ||
| 7 | 8 | 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โฆ |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q26.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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)
Shape of the image: (300, 400, 3)
Height : 300 pixels
Width : 400 pixels
Channels : 3 (B, G, R)
Total pixels: 120000
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q27.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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()
Image Shape: (300, 400)
Minimum Pixel Value: 79
Maximum Pixel Value: 221
Grayscale image saved as flower_gray.jpgNEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q28.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q29.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | 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] | |
| 2 | 3 | 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] | |
| 3 | 4 | TP = FP = TN = FN = 0 | TP = 0, FP = 0, TN = 0, FN = 0 | |
| 4 | 5 | for a, p in zip(actual, predicted): next item taken | a = 1, p = 1 | |
| 5 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | TP = 1 | |
| 6 | 5 | for a, p in zip(actual, predicted): next item taken | a = 0, p = 0 | |
| 7 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | ||
| 8 | 7 | elif a == 0 and p == 1: FP += 1 condition is FALSE โ skips this block | ||
| 9 | 8 | elif a == 0 and p == 0: TN += 1 condition is FALSE โ skips this block | TN = 1 | |
| 10 | 5 | for a, p in zip(actual, predicted): next item taken | a = 1, p = 1 | |
| 11 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | TP = 2 | |
| 12 | 5 | for a, p in zip(actual, predicted): next item taken | p = 0 | |
| 13 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | ||
| 14 | 7 | elif a == 0 and p == 1: FP += 1 condition is FALSE โ skips this block | ||
| 15 | 8 | elif a == 0 and p == 0: TN += 1 condition is FALSE โ skips this block | ||
| 16 | 9 | else: FN += 1 | FN = 1 | |
| 17 | 5 | for a, p in zip(actual, predicted): next item taken | a = 0 | |
| 18 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | ||
| 19 | 7 | elif a == 0 and p == 1: FP += 1 condition is FALSE โ skips this block | ||
| 20 | 8 | elif a == 0 and p == 0: TN += 1 condition is FALSE โ skips this block | TN = 2 | |
| 21 | 5 | for a, p in zip(actual, predicted): next item taken | a = 1, p = 1 | |
| 22 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | TP = 3 | |
| 23 | 5 | for a, p in zip(actual, predicted): next item taken | a = 0 | |
| 24 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | ||
| 25 | 7 | elif a == 0 and p == 1: FP += 1 condition is FALSE โ skips this block | FP = 1 | |
| 26 | 5 | for a, p in zip(actual, predicted): next item taken | p = 0 | |
| 27 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | ||
| 28 | 7 | elif a == 0 and p == 1: FP += 1 condition is FALSE โ skips this block | ||
| 29 | 8 | elif a == 0 and p == 0: TN += 1 condition is FALSE โ skips this block | TN = 3 | |
| 30 | 5 | for a, p in zip(actual, predicted): next item taken | a = 1, p = 1 | |
| 31 | 6 | if a == 1 and p == 1: TP += 1 condition is FALSE โ skips this block | TP = 4 | |
| 32 | 5 | 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
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)
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]]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q30.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | image = np.array([[10, 10, 10, 80, 80], | ||
| 3 | 4 | [10, 10, 10, 80, 80], | ||
| 4 | 5 | [10, 10, 10, 80, 80], | ||
| 5 | 6 | [10, 10, 10, 80, 80], | ||
| 6 | 7 | [10, 10, 10, 80, 80]]) | ||
| 7 | 3 | image = np.array([[10, 10, 10, 80, 80], | image = array of shape (5, 5) | |
| 8 | 8 | kernel = np.array([[-1, 0, 1], # vertical edge detector | ||
| 9 | 9 | [-1, 0, 1], | ||
| 10 | 10 | [-1, 0, 1]]) | ||
| 11 | 8 | kernel = np.array([[-1, 0, 1], # vertical edge detector | kernel = array of shape (3, 3) | |
| 12 | 11 | out = np.zeros((3, 3), dtype=int) # (5-3+1) x (5-3+1) | out = array of shape (3, 3) | |
| 13 | 12 | for i in range(3): next item taken | i = 0 | |
| 14 | 13 | for j in range(3): next item taken | j = 0 | |
| 15 | 14 | region = image[i:i+3, j:j+3] | region = array of shape (3, 3) | |
| 16 | 15 | out[i, j] = np.sum(region * kernel) | ||
| 17 | 13 | for j in range(3): next item taken | j = 1 | |
| 18 | 14 | region = image[i:i+3, j:j+3] | ||
| 19 | 15 | out[i, j] = np.sum(region * kernel) | ||
| 20 | 13 | for j in range(3): next item taken | j = 2 | |
| 21 | 14 | region = image[i:i+3, j:j+3] | ||
| 22 | 15 | out[i, j] = np.sum(region * kernel) | ||
| 23 | 13 | for j in range(3): no items left โ loop ends | ||
| 24 | 12 | for i in range(3): next item taken | i = 1 | |
| 25 | 13 | for j in range(3): next item taken | j = 0 | |
| 26 | 14 | region = image[i:i+3, j:j+3] | ||
| 27 | 15 | out[i, j] = np.sum(region * kernel) | ||
| 28 | 13 | for j in range(3): next item taken | j = 1 | |
| 29 | 14 | region = image[i:i+3, j:j+3] | ||
| 30 | 15 | out[i, j] = np.sum(region * kernel) | ||
| 31 | 13 | for j in range(3): next item taken | j = 2 | |
| 32 | 14 | 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)
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}")
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
x_ai_q31.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import math | ||
| 2 | 3 | docs = ["Aman and Anil are stressed", | docs = ['Aman and Anil are stressed', 'Aman went to a therapist', 'Anil weโฆ | |
| 3 | 6 | stop_words = {"and", "are", "to", "a"} | stop_words = {'and', 'a', 'to', 'are'} | |
| 4 | 9 | tokens = [] | tokens = [] | |
| 5 | 10 | for d in docs: next item taken | d = 'Aman and Anil are stressed' | |
| 6 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 7 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 8 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 9 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 10 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 11 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | words = ['aman', 'anil', 'stressed'] | |
| 12 | 12 | tokens.append(words) | tokens = [['aman', 'anil', 'stressed']] | |
| 13 | 13 | print("Tokens:", words) | Tokens: ['aman', 'anil', 'stressed'] | |
| 14 | 10 | for d in docs: next item taken | d = 'Aman went to a therapist' | |
| 15 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 16 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 17 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 18 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 19 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 20 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | words = ['aman', 'went', 'therapist'] | |
| 21 | 12 | tokens.append(words) | tokens = [['aman', 'anil', 'stressed'], ['aman', 'went', 'therapist']] | |
| 22 | 13 | print("Tokens:", words) | Tokens: ['aman', 'went', 'therapist'] | |
| 23 | 10 | for d in docs: next item taken | d = 'Anil went to download a health chatbot' | |
| 24 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 25 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 26 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 27 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 28 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 29 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 30 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | ||
| 31 | 11 | words = [w.lower() for w in d.split() if w.lower() not in stop_words] | words = ['anil', 'went', 'download', 'health', 'chatbot'] | |
| 32 | 12 | 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
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
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.
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.
Output: an animated GIF (32 x 32 pixels, 6 frames) of a waving stick-man.
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.
Model accuracy on 10 new test items: 9 correct (90 %).
Mistake: a crushed plastic cup was classified as Non-Recyclable - add more such images.
๐ 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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)
| Component | Marks |
|---|---|
| IBM SkillsBuild Certification / any other industry certification | 5 |
| Capstone Project | 12 |
| Bootcamps / Internship / other startups | 7 |
| Practical File | 10 |
| 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.
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).
Domain-wise count: Computer Vision = 4, NLP = 4, Data Statistics = 4
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: Most openings ask for Python, statistics and ML basics; Bengaluru and
Hyderabad have the maximum AI openings.
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
My skill-gap plan: learn Pandas & Scikit-learn this year, complete an IBM SkillsBuild
course, and practise presenting projects to improve communication.
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)
Enter an integer: -14
Number : -14
Sign : Negative
Even / Odd : Even
Square : 196
n // 3, n % 3 : -5 , 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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q4.py. - Press F5 (Run โ Run Module).
- When the program asks, type -14 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | n = int(input("Enter an integer: ")) | n = -14 | Enter an integer: -14 |
| 2 | 3 | if n > 0: condition is FALSE โ skips this block | ||
| 3 | 5 | elif n < 0: condition is TRUE โ enters the block | ||
| 4 | 6 | sign = "Negative" | sign = 'Negative' | |
| 5 | 9 | parity = "Even" if n % 2 == 0 else "Odd" | parity = 'Even' | |
| 6 | 10 | print("Number :", n) | Number : -14 | |
| 7 | 11 | print("Sign :", sign) | Sign : Negative | |
| 8 | 12 | print("Even / Odd :", parity) | Even / Odd : Even | |
| 9 | 13 | print("Square :", n ** 2) | Square : 196 | |
| 10 | 14 | print("n // 3, n % 3 :", n // 3, ",", n % 3) | n // 3, n % 3 : -5 , 1 |
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)
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
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
name, m๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q5.py. - Press F5 (Run โ Run Module).
- When the program asks, type Ishaan, 88, 92, 79, 95, 84 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | name = input("Enter student name: ") | name = 'Ishaan' | Enter student name: Ishaan |
| 2 | 3 | total = 0 | total = 0 | |
| 3 | 4 | for i in range(1, 6): next item taken | i = 1 | |
| 4 | 5 | m = float(input("Enter marks of subject " + str(i) + " (out of 100): ")) | m = 88.0 | Enter marks of subject 1 (out of 100): 88 |
| 5 | 6 | total += m | total = 88.0 | |
| 6 | 4 | for i in range(1, 6): next item taken | i = 2 | |
| 7 | 5 | m = float(input("Enter marks of subject " + str(i) + " (out of 100): ")) | m = 92.0 | Enter marks of subject 2 (out of 100): 92 |
| 8 | 6 | total += m | total = 180.0 | |
| 9 | 4 | for i in range(1, 6): next item taken | i = 3 | |
| 10 | 5 | m = float(input("Enter marks of subject " + str(i) + " (out of 100): ")) | m = 79.0 | Enter marks of subject 3 (out of 100): 79 |
| 11 | 6 | total += m | total = 259.0 | |
| 12 | 4 | for i in range(1, 6): next item taken | i = 4 | |
| 13 | 5 | m = float(input("Enter marks of subject " + str(i) + " (out of 100): ")) | m = 95.0 | Enter marks of subject 4 (out of 100): 95 |
| 14 | 6 | total += m | total = 354.0 | |
| 15 | 4 | for i in range(1, 6): next item taken | i = 5 | |
| 16 | 5 | m = float(input("Enter marks of subject " + str(i) + " (out of 100): ")) | m = 84.0 | Enter marks of subject 5 (out of 100): 84 |
| 17 | 6 | total += m | total = 438.0 | |
| 18 | 4 | for i in range(1, 6): no items left โ loop ends | ||
| 19 | 7 | percent = total / 5 | percent = 87.6 | |
| 20 | 8 | if percent >= 90: grade = 'A' condition is FALSE โ skips this block | ||
| 21 | 9 | elif percent >= 75: grade = 'B' condition is FALSE โ skips this block | grade = 'B' | |
| 22 | 13 | print("\nName :", name) | Name : Ishaan | |
| 23 | 14 | print("Total :", total, "/ 500") | Total : 438.0 / 500 | |
| 24 | 15 | print("Percentage :", round(percent, 2), "%") | Percentage : 87.6 % | |
| 25 | 16 | print("Grade :", grade) | Grade : B |
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")
Enter a number: 12321
Sum of digits : 9
Reverse : 12321
12321 is a Palindrome
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
num๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q6.py. - Press F5 (Run โ Run Module).
- When the program asks, type 12321 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | num = int(input("Enter a number: ")) | num = 12321 | Enter a number: 12321 |
| 2 | 3 | temp = num | temp = 12321 | |
| 3 | 4 | total = 0 | total = 0 | |
| 4 | 5 | rev = 0 | rev = 0 | |
| 5 | 6 | while temp > 0: condition is TRUE โ enters the block | ||
| 6 | 7 | digit = temp % 10 | digit = 1 | |
| 7 | 8 | total += digit | total = 1 | |
| 8 | 9 | rev = rev * 10 + digit | rev = 1 | |
| 9 | 10 | temp //= 10 | temp = 1232 | |
| 10 | 6 | while temp > 0: condition is TRUE โ enters the block | ||
| 11 | 7 | digit = temp % 10 | digit = 2 | |
| 12 | 8 | total += digit | total = 3 | |
| 13 | 9 | rev = rev * 10 + digit | rev = 12 | |
| 14 | 10 | temp //= 10 | temp = 123 | |
| 15 | 6 | while temp > 0: condition is TRUE โ enters the block | ||
| 16 | 7 | digit = temp % 10 | digit = 3 | |
| 17 | 8 | total += digit | total = 6 | |
| 18 | 9 | rev = rev * 10 + digit | rev = 123 | |
| 19 | 10 | temp //= 10 | temp = 12 | |
| 20 | 6 | while temp > 0: condition is TRUE โ enters the block | ||
| 21 | 7 | digit = temp % 10 | digit = 2 | |
| 22 | 8 | total += digit | total = 8 | |
| 23 | 9 | rev = rev * 10 + digit | rev = 1232 | |
| 24 | 10 | temp //= 10 | temp = 1 | |
| 25 | 6 | while temp > 0: condition is TRUE โ enters the block | ||
| 26 | 7 | digit = temp % 10 | digit = 1 | |
| 27 | 8 | total += digit | total = 9 | |
| 28 | 9 | rev = rev * 10 + digit | rev = 12321 | |
| 29 | 10 | temp //= 10 | temp = 0 | |
| 30 | 6 | while temp > 0: condition is FALSE โ loop ends | ||
| 31 | 11 | print("Sum of digits :", total) | Sum of digits : 9 | |
| 32 | 12 | 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
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)
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
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
n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q7.py. - Press F5 (Run โ Run Module).
- When the program asks, type 6 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | n = int(input("Enter a number: ")) | n = 6 | Enter a number: 6 |
| 2 | 3 | print("Multiplication table of", n) | Multiplication table of 6 | |
| 3 | 4 | for i in range(1, 11): next item taken | i = 1 | |
| 4 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 1 = 6 | |
| 5 | 4 | for i in range(1, 11): next item taken | i = 2 | |
| 6 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 2 = 12 | |
| 7 | 4 | for i in range(1, 11): next item taken | i = 3 | |
| 8 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 3 = 18 | |
| 9 | 4 | for i in range(1, 11): next item taken | i = 4 | |
| 10 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 4 = 24 | |
| 11 | 4 | for i in range(1, 11): next item taken | i = 5 | |
| 12 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 5 = 30 | |
| 13 | 4 | for i in range(1, 11): next item taken | i = 6 | |
| 14 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 6 = 36 | |
| 15 | 4 | for i in range(1, 11): next item taken | i = 7 | |
| 16 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 7 = 42 | |
| 17 | 4 | for i in range(1, 11): next item taken | i = 8 | |
| 18 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 8 = 48 | |
| 19 | 4 | for i in range(1, 11): next item taken | i = 9 | |
| 20 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 9 = 54 | |
| 21 | 4 | for i in range(1, 11): next item taken | i = 10 | |
| 22 | 5 | print(f"{n} x {i:2} = {n * i}") | 6 x 10 = 60 | |
| 23 | 4 | for i in range(1, 11): no items left โ loop ends | ||
| 24 | 6 | fact = 1 | fact = 1 | |
| 25 | 7 | for i in range(1, n + 1): next item taken | i = 1 | |
| 26 | 8 | fact *= i | ||
| 27 | 7 | for i in range(1, n + 1): next item taken | i = 2 | |
| 28 | 8 | fact *= i | fact = 2 | |
| 29 | 7 | for i in range(1, n + 1): next item taken | i = 3 | |
| 30 | 8 | fact *= i | fact = 6 | |
| 31 | 7 | for i in range(1, n + 1): next item taken | i = 4 | |
| 32 | 8 | 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
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()
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
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
low, high, n๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q8.py. - Press F5 (Run โ Run Module).
- When the program asks, type 10, 50, 10 (the same values as the Sample Output) and press Enter after each.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | low = int(input("Enter lower limit: ")) | low = 10 | Enter lower limit: 10 |
| 2 | 3 | high = int(input("Enter upper limit: ")) | high = 50 | Enter upper limit: 50 |
| 3 | 4 | print("Prime numbers:", end=" ") | Prime numbers: | |
| 4 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 10 | |
| 5 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | d = 2 | |
| 6 | 7 | if num % d == 0: condition is TRUE โ enters the block | ||
| 7 | 8 | break | ||
| 8 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 11 | |
| 9 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | ||
| 10 | 7 | if num % d == 0: condition is FALSE โ skips this block | ||
| 11 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | d = 3 | |
| 12 | 7 | if num % d == 0: condition is FALSE โ skips this block | ||
| 13 | 6 | for d in range(2, int(num ** 0.5) + 1): no items left โ loop ends | ||
| 14 | 10 | print(num, end=" ") | 11 | |
| 15 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 12 | |
| 16 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | d = 2 | |
| 17 | 7 | if num % d == 0: condition is TRUE โ enters the block | ||
| 18 | 8 | break | ||
| 19 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 13 | |
| 20 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | ||
| 21 | 7 | if num % d == 0: condition is FALSE โ skips this block | ||
| 22 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | d = 3 | |
| 23 | 7 | if num % d == 0: condition is FALSE โ skips this block | ||
| 24 | 6 | for d in range(2, int(num ** 0.5) + 1): no items left โ loop ends | ||
| 25 | 10 | print(num, end=" ") | 13 | |
| 26 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 14 | |
| 27 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | d = 2 | |
| 28 | 7 | if num % d == 0: condition is TRUE โ enters the block | ||
| 29 | 8 | break | ||
| 30 | 5 | for num in range(max(2, low), high + 1): next item taken | num = 15 | |
| 31 | 6 | for d in range(2, int(num ** 0.5) + 1): next item taken | ||
| 32 | 7 | 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
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))
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. ]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q9.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | marks = np.array([78, 85, 62, 90, 71, 88]) | marks = array([78, 85, 62, 90, 71, 88]) | |
| 3 | 4 | print("Array :", marks) | Array : [78 85 62 90 71 88] | |
| 4 | 5 | print("Type / dtype :", type(marks), marks.dtype) | Type / dtype : <class 'numpy.ndarray'> int64 | |
| 5 | 6 | print("Add 5 grace :", marks + 5) | Add 5 grace : [83 90 67 95 76 93] | |
| 6 | 7 | print("Sum / Mean :", marks.sum(), "/", round(marks.mean(), 2)) | Sum / Mean : 474 / 79.0 | |
| 7 | 8 | print("Max / Min :", marks.max(), "/", marks.min()) | Max / Min : 90 / 62 | |
| 8 | 9 | print("Std deviation:", round(marks.std(), 3)) | Std deviation: 9.933 | |
| 9 | 10 | print("Marks > 80 :", marks[marks > 80]) | Marks > 80 : [85 90 88] | |
| 10 | 11 | print("zeros(3) :", np.zeros(3)) | zeros(3) : [0. 0. 0.] | |
| 11 | 12 | print("arange(0,10,3):", np.arange(0, 10, 3)) | arange(0,10,3): [0 3 6 9] | |
| 12 | 13 | print("linspace(0,1,5):", np.linspace(0, 1, 5)) | linspace(0,1,5): [0. 0.25 0.5 0.75 1. ] |
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)
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]]
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q10.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | A = np.array([[2, 1, 3], [0, 4, 5], [1, 2, 1]]) | A = array of shape (3, 3) | |
| 3 | 4 | B = np.arange(1, 10).reshape(3, 3) | B = array of shape (3, 3) | |
| 4 | 5 | print("Matrix A:\n", A) | Matrix A: [[2 1 3] [0 4 5] [1 2 1]] | |
| 5 | 6 | print("Matrix B:\n", B) | Matrix B: [[1 2 3] [4 5 6] [7 8 9]] | |
| 6 | 7 | print("A + B:\n", A + B) | A + B: [[ 3 3 6] [ 4 9 11] [ 8 10 10]] | |
| 7 | 8 | print("A x B (matrix product):\n", A @ B) | A x B (matrix product): [[27 33 39] [51 60 69] [16 20 24]] | |
| 8 | 9 | print("Transpose of A:\n", A.T) | Transpose of A: [[2 0 1] [1 4 2] [3 5 1]] | |
| 9 | 10 | print("Determinant of A:", round(np.linalg.det(A), 2)) | Determinant of A: -19.0 | |
| 10 | 11 | print("Element-wise A * B:\n", A * B) | Element-wise A * B: [[ 2 2 9] [ 0 20 30] [ 7 16 9]] |
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'])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q11.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'], | ||
| 3 | 4 | 'Maths': [88, 92, 67, 75, 95], | ||
| 4 | 5 | 'Science': [79, 85, 72, 91, 89]} | ||
| 5 | 3 | data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'], | data = {'Name': ['Ravi', 'Sana', 'Tom', 'Uma', 'Vikas'], 'Maths': [88, 92,โฆ | |
| 6 | 6 | df = pd.DataFrame(data) | df = DataFrame (5 rows ร 3 columns) | |
| 7 | 7 | df['Total'] = df['Maths'] + df['Science'] | df = DataFrame (5 rows ร 4 columns) | |
| 8 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | ||
| 9 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | ||
| 10 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | ||
| 11 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | ||
| 12 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | ||
| 13 | 8 | df['Result'] = ['Pass' if t >= 150 else 'Needs Help' for t in df['Total']] | df = DataFrame (5 rows ร 5 columns) | |
| 14 | 9 | 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 | |
| 15 | 10 | 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 | |
| 16 | 11 | print("\nTopper:", df.loc[df['Total'].idxmax(), 'Name']) | Topper: Vikas |
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")
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q12.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | df = pd.read_csv("rainfall.csv") | df = DataFrame (12 rows ร 3 columns) | |
| 3 | 4 | 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 | |
| 4 | 5 | print("Shape:", df.shape) | Shape: (12, 3) | |
| 5 | 6 | print("Average annual rainfall (mm):", round(df['Rainfall_mm'].mean(), 2)) | Average annual rainfall (mm): 63.0 | |
| 6 | 7 | wet = df.loc[df['Rainfall_mm'].idxmax()] | wet = Series (3 values) | |
| 7 | 8 | dry = df.loc[df['Rainfall_mm'].idxmin()] | dry = Series (3 values) | |
| 8 | 9 | print("Wettest month:", wet['Month'], "-", wet['Rainfall_mm'], "mm") | Wettest month: Aug - 233 mm | |
| 9 | 10 | print("Driest month :", dry['Month'], "-", dry['Rainfall_mm'], "mm") | Driest month : Nov - 6 mm | |
| 10 | 11 | print("Monsoon (Jun-Sep) total:", df.loc[5:8, 'Rainfall_mm'].sum(), "mm") | Monsoon (Jun-Sep) total: 637 mm |
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]])
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q13.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | from sklearn.datasets import load_iris | ||
| 2 | 3 | from sklearn.model_selection import train_test_split | ||
| 3 | 4 | from sklearn.tree import DecisionTreeClassifier | ||
| 4 | 5 | from sklearn.metrics import accuracy_score | ||
| 5 | 6 | iris = load_iris() | iris = Bunch model | |
| 6 | 7 | X, y = iris.data, iris.target | X = array of shape (150, 4), y = array of shape (150,) | |
| 7 | 8 | print("Features:", iris.feature_names) | Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] | |
| 8 | 9 | print("Classes :", iris.target_names.tolist()) | Classes : ['setosa', 'versicolor', 'virginica'] | |
| 9 | 10 | print("Dataset shape:", X.shape) | Dataset shape: (150, 4) | |
| 10 | 11 | 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,) | |
| 11 | 12 | model = DecisionTreeClassifier(random_state=42) | model = DecisionTreeClassifier model | |
| 12 | 13 | model.fit(X_train, y_train) | ||
| 13 | 14 | pred = model.predict(X_test) | pred = array of shape (30,) | |
| 14 | 15 | print("Training samples:", len(X_train), " Testing samples:", len(X_test)) | Training samples: 120 Testing samples: 30 | |
| 15 | 16 | print("Accuracy:", round(accuracy_score(y_test, pred) * 100, 2), "%") | Accuracy: 100.0 % | |
| 16 | 17 | sample = [[5.1, 3.5, 1.4, 0.2]] | sample = [[5.1, 3.5, 1.4, 0.2]] | |
| 17 | 18 | print("Prediction for", sample, "->", iris.target_names[model.predict(sample)[0]]) | Prediction for [[5.1, 3.5, 1.4, 0.2]] -> setosa |
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 |
+----+--------------------------------------+-----------+
Nominal = 2, Ordinal = 3, Interval = 2, Ratio = 3
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q15.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import statistics as st | ||
| 2 | 3 | import numpy as np | ||
| 3 | 4 | heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170] | heights = [150, 152, 155, 155, 158, 160, 155, 162, 165, 170] | |
| 4 | 5 | print("Data (heights in cm):", heights) | Data (heights in cm): [150, 152, 155, 155, 158, 160, 155, 162, 165, 170] | |
| 5 | 6 | print("Mean :", st.mean(heights)) | Mean : 158.2 | |
| 6 | 7 | print("Median :", st.median(heights)) | Median : 156.5 | |
| 7 | 8 | print("Mode :", st.mode(heights)) | Mode : 155 | |
| 8 | 9 | print("Range :", max(heights) - min(heights)) | Range : 20 | |
| 9 | 10 | print("Population variance (pvariance):", round(st.pvariance(heights), 2)) | Population variance (pvariance): 33.96 | |
| 10 | 11 | print("Population std deviation (pstdev):", round(st.pstdev(heights), 2)) | Population std deviation (pstdev): 5.83 | |
| 11 | 12 | print("Sample variance (variance):", round(st.variance(heights), 2)) | Sample variance (variance): 37.73 | |
| 12 | 13 | print("Sample std deviation (stdev):", round(st.stdev(heights), 2)) | Sample std deviation (stdev): 6.14 | |
| 13 | 14 | print("NumPy check -> var:", round(np.var(heights), 2), " std:", round(np.std(heights), 2) | NumPy check -> var: 33.96 std: 5.83 |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q16.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import pandas as pd | ||
| 2 | 3 | import matplotlib.pyplot as plt | ||
| 3 | 4 | df = pd.read_csv("rainfall.csv") | df = DataFrame (12 rows ร 3 columns) | |
| 4 | 5 | plt.plot(df['Month'], df['Rainfall_mm'], marker='o', color='navy', label='Rainfall (mm)') | ||
| 5 | 6 | plt.title("Monthly Rainfall - Delhi") | ||
| 6 | 7 | plt.xlabel("Month") | ||
| 7 | 8 | plt.ylabel("Rainfall (mm)") | ||
| 8 | 9 | plt.legend() | ||
| 9 | 10 | plt.grid(True, linestyle='--', alpha=0.5) | ||
| 10 | 11 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q17.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI'] | domains = ['Data Science', 'Computer Vision', 'NLP', 'Robotics', 'Gen AI'] | |
| 3 | 4 | students = [34, 22, 18, 12, 40] | students = [34, 22, 18, 12, 40] | |
| 4 | 5 | plt.bar(domains, students, color=['#0A2472', '#FF6B00', '#2B8A3E', '#9C36B5', '#1971C2']) | ||
| 5 | 6 | plt.title("Favourite AI Domain of Class XI Students") | ||
| 6 | 7 | plt.xlabel("AI Domain") | ||
| 7 | 8 | plt.ylabel("Number of students") | ||
| 8 | 9 | for i, v in enumerate(students): next item taken | i = 0, v = 34 | |
| 9 | 10 | plt.text(i, v + 0.5, str(v), ha='center') | ||
| 10 | 9 | for i, v in enumerate(students): next item taken | i = 1, v = 22 | |
| 11 | 10 | plt.text(i, v + 0.5, str(v), ha='center') | ||
| 12 | 9 | for i, v in enumerate(students): next item taken | i = 2, v = 18 | |
| 13 | 10 | plt.text(i, v + 0.5, str(v), ha='center') | ||
| 14 | 9 | for i, v in enumerate(students): next item taken | i = 3, v = 12 | |
| 15 | 10 | plt.text(i, v + 0.5, str(v), ha='center') | ||
| 16 | 9 | for i, v in enumerate(students): next item taken | i = 4, v = 40 | |
| 17 | 10 | plt.text(i, v + 0.5, str(v), ha='center') | ||
| 18 | 9 | for i, v in enumerate(students): no items left โ loop ends | ||
| 19 | 11 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q18.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | 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โฆ | |
| 3 | 5 | plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], color='orange', edgecolor='black') | ||
| 4 | 6 | plt.title("Distribution of AI Marks") | ||
| 5 | 7 | plt.xlabel("Marks range") | ||
| 6 | 8 | plt.ylabel("Number of students") | ||
| 7 | 9 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q19.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | 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] | |
| 3 | 4 | marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88] | marks = [35, 42, 48, 50, 58, 62, 66, 72, 75, 80, 88] | |
| 4 | 5 | plt.scatter(study_hours, marks, color='green', s=60) | ||
| 5 | 6 | plt.title("Study Hours vs Marks") | ||
| 6 | 7 | plt.xlabel("Study hours per day") | ||
| 7 | 8 | plt.ylabel("Marks") | ||
| 8 | 9 | plt.grid(True, alpha=0.4) | ||
| 9 | 10 | plt.show() |
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()
(The program opens a chart / image window - see the output figure below.)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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q20.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import matplotlib.pyplot as plt | ||
| 2 | 3 | sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others'] | sources = ['Coal', 'Solar', 'Wind', 'Hydro', 'Nuclear', 'Others'] | |
| 3 | 4 | share = [48, 18, 11, 10, 2, 11] | share = [48, 18, 11, 10, 2, 11] | |
| 4 | 5 | plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90, | ||
| 5 | 6 | explode=[0, 0.1, 0, 0, 0, 0]) | ||
| 6 | 5 | plt.pie(share, labels=sources, autopct='%1.1f%%', startangle=90, | ||
| 7 | 7 | plt.title("Energy Mix (sample data)") | ||
| 8 | 8 | plt.axis('equal') | ||
| 9 | 9 | plt.show() |
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?
Problem identified: senior citizens need a simple, voice-guided and fraud-safe payment
interface in Indian languages (SDG 10 - Reduced Inequalities).
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.
Abstract prepared (approx. 100 words) with problem, users, AI approach, SDG and test result.
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) )
r = 0.9993 -> very strong positive correlation between study hours and marks.
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)
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
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()
Slope (m) : 7.56
Intercept (c) : 27.357
R-squared : 0.9993
Predicted marks for 9 hours: 95.39NEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q25.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | import matplotlib.pyplot as plt | ||
| 3 | 4 | from sklearn.linear_model import LinearRegression | ||
| 4 | 5 | hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1) | hours = array([[1], [2], [3], [4], [5], [6], [7], [8]]) | |
| 5 | 6 | marks = np.array([35, 42, 50, 58, 66, 72, 80, 88]) | marks = array([35, 42, 50, 58, 66, 72, 80, 88]) | |
| 6 | 7 | model = LinearRegression() | model = LinearRegression model | |
| 7 | 8 | model.fit(hours, marks) | ||
| 8 | 9 | print("Slope (m) :", round(model.coef_[0], 3)) | Slope (m) : 7.56 | |
| 9 | 10 | print("Intercept (c) :", round(model.intercept_, 3)) | Intercept (c) : 27.357 | |
| 10 | 11 | print("R-squared :", round(model.score(hours, marks), 4)) | R-squared : 0.9993 | |
| 11 | 12 | print("Predicted marks for 9 hours:", round(model.predict([[9]])[0], 2)) | Predicted marks for 9 hours: 95.39 | |
| 12 | 13 | plt.scatter(hours, marks, color='blue', label='Actual data') | ||
| 13 | 14 | plt.plot(hours, model.predict(hours), color='red', label='Best-fit line') | ||
| 14 | 15 | plt.title("Linear Regression: Study Hours vs Marks") | ||
| 15 | 16 | plt.xlabel("Hours"); plt.ylabel("Marks"); plt.legend() | ||
| 16 | 17 | plt.show() |
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]])
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']
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q26.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | from sklearn.neighbors import KNeighborsClassifier | ||
| 2 | 4 | 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, โฆ | |
| 3 | 5 | y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', 'Orange'] | y = ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Apple', โฆ | |
| 4 | 6 | knn = KNeighborsClassifier(n_neighbors=3) | knn = KNeighborsClassifier model | |
| 5 | 7 | knn.fit(X, y) | ||
| 6 | 8 | tests = [[145, 0], [165, 1], [158, 0]] | tests = [[145, 0], [165, 1], [158, 0]] | |
| 7 | 9 | for t in tests: next item taken | t = [145, 0] | |
| 8 | 10 | dist, idx = knn.kneighbors([t]) | dist = array([[5.0, 5.0, 10.0]]), idx = array([[0, 2, 6]]) | |
| 9 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | ||
| 10 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 11 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 12 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 13 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 14 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | Fruit [145, 0] -> predicted: Apple | 3 nearest: ['Apple', 'Apple', 'Apple'] | |
| 15 | 9 | for t in tests: next item taken | t = [165, 1] | |
| 16 | 10 | dist, idx = knn.kneighbors([t]) | idx = array([[3, 4, 7]]) | |
| 17 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | ||
| 18 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 19 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 20 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 21 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 22 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | Fruit [165, 1] -> predicted: Orange | 3 nearest: ['Orange', 'Orange', 'Orange'] | |
| 23 | 9 | for t in tests: next item taken | t = [158, 0] | |
| 24 | 10 | dist, idx = knn.kneighbors([t]) | dist = array([[2.23606797749979, 8.0, 12.041594578792296]]), idx = array([[4, 2, 3]]) | |
| 25 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | ||
| 26 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 27 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 28 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 29 | 12 | "| 3 nearest:", [y[i] for i in idx[0]]) | ||
| 30 | 11 | print("Fruit", t, "-> predicted:", knn.predict([t])[0], | Fruit [158, 0] -> predicted: Orange | 3 nearest: ['Orange', 'Apple', 'Orange'] | |
| 31 | 9 | for t in tests: no items left โ loop ends |
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()
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 ]]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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q27.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | import numpy as np | ||
| 2 | 3 | import matplotlib.pyplot as plt | ||
| 3 | 4 | from sklearn.cluster import KMeans | ||
| 4 | 6 | X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10], | ||
| 5 | 7 | [35, 5], [38, 6], [33, 5], [62, 9], [17, 3], [36, 6]]) | ||
| 6 | 6 | X = np.array([[15, 2], [18, 3], [16, 2], [55, 8], [60, 9], [58, 10], | X = array of shape (12, 2) | |
| 7 | 8 | km = KMeans(n_clusters=3, n_init=10, random_state=0) | km = KMeans model | |
| 8 | 9 | labels = km.fit_predict(X) | labels = array of shape (12,) | |
| 9 | 10 | print("Cluster labels :", labels) | Cluster labels : [2 2 2 1 1 1 0 0 0 1 2 0] | |
| 10 | 11 | print("Cluster centres:\n", km.cluster_centers_.round(2)) | Cluster centres: [[35.5 5.5 ] [58.75 9. ] [16.5 2.5 ]] | |
| 11 | 12 | plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=70) | ||
| 12 | 13 | plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='red', marker='X', s=2 | ||
| 13 | 14 | plt.title("K-Means Customer Segments"); plt.xlabel("Annual spend (thousand Rs)") | ||
| 14 | 15 | plt.ylabel("Visits / month"); plt.legend(); plt.show() |
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).
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!
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'.")
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.
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
msg๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q29.py. - Press F5 (Run โ Run Module).
- 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.
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 2 | menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65} | menu = {'chocolate': 60, 'vanilla': 50, 'mango': 55, 'butterscotch': 65} | |
| 2 | 3 | order = [] | order = [] | |
| 3 | 4 | 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'. | |
| 4 | 5 | while True: condition is TRUE โ enters the block | ||
| 5 | 6 | msg = input("You: ").lower().strip() | msg = 'hello' | You: hello |
| 6 | 7 | if msg in ('hi', 'hello', 'hey'):condition is TRUE โ enters the block | ||
| 7 | 8 | print("Bot: Hello! What would you like today?") | Bot: Hello! What would you like today? | |
| 8 | 5 | while True: condition is TRUE โ enters the block | ||
| 9 | 6 | msg = input("You: ").lower().strip() | msg = 'menu' | You: menu |
| 10 | 7 | if msg in ('hi', 'hello', 'hey'):condition is FALSE โ skips this block | ||
| 11 | 9 | elif 'menu' in msg: condition is TRUE โ enters the block | ||
| 12 | 10 | for f, p in menu.items(): next item taken | f = 'chocolate', p = 60 | |
| 13 | 11 | print(f"Bot: {f.title():<13} Rs.{p}") | Bot: Chocolate Rs.60 | |
| 14 | 10 | for f, p in menu.items(): next item taken | f = 'vanilla', p = 50 | |
| 15 | 11 | print(f"Bot: {f.title():<13} Rs.{p}") | Bot: Vanilla Rs.50 | |
| 16 | 10 | for f, p in menu.items(): next item taken | f = 'mango', p = 55 | |
| 17 | 11 | print(f"Bot: {f.title():<13} Rs.{p}") | Bot: Mango Rs.55 | |
| 18 | 10 | for f, p in menu.items(): next item taken | f = 'butterscotch', p = 65 | |
| 19 | 11 | print(f"Bot: {f.title():<13} Rs.{p}") | Bot: Butterscotch Rs.65 | |
| 20 | 10 | for f, p in menu.items(): no items left โ loop ends | ||
| 21 | 5 | while True: condition is TRUE โ enters the block | ||
| 22 | 6 | msg = input("You: ").lower().strip() | msg = 'i want mango' | You: I want mango |
| 23 | 7 | if msg in ('hi', 'hello', 'hey'):condition is FALSE โ skips this block | ||
| 24 | 9 | elif 'menu' in msg: condition is FALSE โ skips this block | ||
| 25 | 12 | 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>) | ||||
| 26 | 12 | 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>) | ||||
| 27 | 12 | 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
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}")
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
. .
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xi_ai_q30.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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.
Article of about 250 words written with title, facts, applications and personal view.
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.
Insight: AI will change most jobs; the safest strategy is to keep learning skills that
complement AI (creativity, empathy, problem solving).
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: all frameworks place humans at the centre of AI; India's approach is
'AI for All' with responsible-AI principles.
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.
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.
๐ 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
- Execution starts at line 1 and goes top to bottom.
input()stops and waits for you; what you type comes back as text - so we useint()/float()to make it a number.- if / elif / else: only ONE block runs - the first whose condition is True.
- for repeats once per item; while repeats while the condition is True; break leaves the loop.
- 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.
- 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
A SELECT is written as SELECT โฆ FROM โฆ WHERE โฆ but MySQL executes it in this order:
- 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
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)
| Component | Marks |
|---|---|
| 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.
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())
(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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q1.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 5 | [101, 'Aditi', 17, 88, 'Delhi'], [102, 'Bharat', 18, 76, 'Noida'], | ||
| 4 | 6 | [103, 'Chirag', 17, np.nan, 'Delhi'], [104, 'Divya', 17, 91, None], | ||
| 5 | 7 | [105, 'Eshan', 18, 67, 'Gurugram'], [106, 'Fatima', 17, 82, 'Delhi'], | ||
| 6 | 8 | [107, 'Gaurav', np.nan, 74, 'Noida'], [108, 'Harsh', 18, 59, 'Delhi'], | ||
| 7 | 9 | [109, 'Ira', 17, 95, 'Faridabad'], [110, 'Jatin', 17, np.nan, 'Delhi'], | ||
| 8 | 10 | [111, 'Kavya', 18, 86, 'Noida'], [112, 'Lakshay', 17, 71, 'Delhi']] | ||
| 9 | 4 | records = [ | records = [[101, 'Aditi', 17, 88, 'Delhi'], [102, 'Bharat', 18, 76, 'Noida'],โฆ | |
| 10 | 11 | df = pd.DataFrame(records, columns=['RollNo', 'Name', 'Age', 'AI_Marks', 'City']) | df = DataFrame (12 rows ร 5 columns) | |
| 11 | 13 | 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โฆ | |
| 12 | 14 | 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 | |
| 13 | 15 | 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 โฆ | |
| 14 | 16 | 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 | |
| 15 | 17 | print("Total missing values:", df.isnull().sum().sum()) | Total missing values: 4 |
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)
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q2.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 3 | df = pd.read_csv("health_survey.csv") | df = DataFrame (12 rows ร 6 columns) | |
| 3 | 4 | print("Shape:", df.shape) | Shape: (12, 6) | |
| 4 | 5 | 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 โฆ | |
| 5 | 6 | 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 | |
| 6 | 7 | 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% โฆ | |
| 7 | 8 | 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 | |
| 8 | 11 | df['Height_cm'] = df['Height_cm'].fillna(df['Height_cm'].mean().round(1)) | ||
| 9 | 12 | df['Weight_kg'] = df['Weight_kg'].fillna(df['Weight_kg'].median()) | ||
| 10 | 13 | df['Sleep_hrs'] = df['Sleep_hrs'].fillna(df['Sleep_hrs'].mean().round(1)) | ||
| 11 | 14 | df['Diet'] = df['Diet'].fillna(df['Diet'].mode()[0]) | ||
| 12 | 15 | print("\nMissing values after cleaning:", df.isnull().sum().sum()) | Missing values after cleaning: 0 | |
| 13 | 16 | 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 โฆ |
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))
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']
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q3.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | df = pd.read_csv("health_survey.csv") # IMPORT | df = DataFrame (12 rows ร 6 columns) | |
| 3 | 3 | df = df.dropna() # keep complete rows only | df = DataFrame (6 rows ร 6 columns) | |
| 4 | 4 | df['BMI'] = (df['Weight_kg'] / (df['Height_cm'] / 100) ** 2).round(1) | df = DataFrame (6 rows ร 7 columns) | |
| 5 | 5 | df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100], | ||
| 6 | 6 | labels=['Underweight', 'Normal', 'Overweight', 'Obese']) | ||
| 7 | 5 | df['Status'] = pd.cut(df['BMI'], bins=[0, 18.5, 25, 30, 100], | df = DataFrame (6 rows ร 8 columns) | |
| 8 | 7 | 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.โฆ | |
| 9 | 8 | df.to_csv("bmi_report.csv", index=False) # EXPORT | ||
| 10 | 9 | print("\nExported", len(df), "rows to bmi_report.csv") | Exported 6 rows to bmi_report.csv | |
| 11 | 10 | check = pd.read_csv("bmi_report.csv") # verify | check = DataFrame (6 rows ร 8 columns) | |
| 12 | 11 | print("Columns in exported file:", list(check.columns)) | Columns in exported file: ['Name', 'Age', 'Height_cm', 'Weight_kg', 'Sleep_hrs', 'Diet', 'BMI', 'Status'] |
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())
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q4.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import pandas as pd | ||
| 2 | 2 | import numpy as np | ||
| 3 | 3 | aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], | ||
| 4 | 4 | 'AQI': [210, np.nan, 245, 260, np.nan, 300, 280], | ||
| 5 | 5 | 'Temp': [31, 30, np.nan, 29, 28, np.nan, 27]}) | ||
| 6 | 3 | aqi = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], | aqi = DataFrame (7 rows ร 3 columns) | |
| 7 | 6 | 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 | |
| 8 | 7 | 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 | |
| 9 | 8 | 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 | |
| 10 | 9 | 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 | |
| 11 | 10 | 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 | |
| 12 | 11 | 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 |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q5.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | from sklearn.datasets import load_breast_cancer | ||
| 2 | 2 | from sklearn.model_selection import train_test_split | ||
| 3 | 3 | from sklearn.linear_model import LogisticRegression | ||
| 4 | 4 | from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score, | ||
| 5 | 6 | data = load_breast_cancer() | data = Bunch model | |
| 6 | 7 | X_train, X_test, y_train, y_test = train_test_split( | ||
| 7 | 8 | data.data, data.target, test_size=0.25, random_state=7) | ||
| 8 | 7 | 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,) | |
| 9 | 9 | model = LogisticRegression(max_iter=5000) | model = LogisticRegression model | |
| 10 | 10 | model.fit(X_train, y_train) | ||
| 11 | 11 | y_pred = model.predict(X_test) | y_pred = array of shape (143,) | |
| 12 | 12 | print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred)) | Confusion Matrix: [[39 6] [ 1 97]] | |
| 13 | 13 | print("Accuracy :", round(accuracy_score(y_test, y_pred), 4)) | Accuracy : 0.951 | |
| 14 | 14 | print("Precision:", round(precision_score(y_test, y_pred), 4)) | Precision: 0.9417 | |
| 15 | 15 | print("Recall :", round(recall_score(y_test, y_pred), 4)) | Recall : 0.9898 | |
| 16 | 16 | print("F1 Score :", round(f1_score(y_test, y_pred), 4)) | F1 Score : 0.9652 | |
| 17 | 17 | 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โฆ |
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))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q6.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import numpy as np | ||
| 2 | 2 | from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score | ||
| 3 | 3 | actual = np.array([250, 300, 320, 410, 380, 450, 500, 520]) # house price (lakh) | actual = array([250, 300, 320, 410, 380, 450, 500, 520]) | |
| 4 | 4 | predicted = np.array([260, 290, 330, 400, 395, 430, 510, 540]) | predicted = array([260, 290, 330, 400, 395, 430, 510, 540]) | |
| 5 | 5 | mae = mean_absolute_error(actual, predicted) | mae = 13.125 | |
| 6 | 6 | mse = mean_squared_error(actual, predicted) | mse = 190.625 | |
| 7 | 7 | rmse = np.sqrt(mse) | rmse = np.float64(13.806701271484076) | |
| 8 | 8 | r2 = r2_score(actual, predicted) | r2 = 0.9767840152235966 | |
| 9 | 9 | print("Errors (actual - predicted):", actual - predicted) | Errors (actual - predicted): [-10 10 -10 10 -15 20 -10 -20] | |
| 10 | 10 | print("MAE =", round(mae, 2)) | MAE = 13.12 | |
| 11 | 11 | print("MSE =", round(mse, 2)) | MSE = 190.62 | |
| 12 | 12 | print("RMSE =", round(rmse, 2)) | RMSE = 13.81 | |
| 13 | 13 | print("R2 =", round(r2, 4)) | R2 = 0.9768 | |
| 14 | 15 | print("Manual MSE =", np.mean((actual - predicted) ** 2)) | Manual MSE = 190.625 |
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()
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.9801NEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q7.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 1 | import numpy as np | ||
| 2 | 2 | import matplotlib.pyplot as plt | ||
| 3 | 3 | from sklearn.model_selection import train_test_split | ||
| 4 | 4 | from sklearn.linear_model import LinearRegression | ||
| 5 | 5 | from sklearn.metrics import mean_squared_error, r2_score | ||
| 6 | 6 | area = np.array([600, 750, 800, 900, 1000, 1100, 1200, 1350, 1500, 1600, 1750, 1900]).resh | area = array of shape (12, 1) | |
| 7 | 7 | price = np.array([32, 39, 41, 47, 52, 56, 61, 68, 76, 80, 88, 95]) # lakh Rs | price = array of shape (12,) | |
| 8 | 8 | 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]) | |
| 9 | 9 | model = LinearRegression().fit(X_train, y_train) | model = LinearRegression model | |
| 10 | 10 | pred = model.predict(X_test) | pred = array([41.52945428261654, 46.391760028912174, 51.2540657752078]) | |
| 11 | 11 | print("Train size:", len(X_train), " Test size:", len(X_test)) | Train size: 9 Test size: 3 | |
| 12 | 12 | print("Equation : Price = %.4f x Area + %.3f" % (model.coef_[0], model.intercept_)) | Equation : Price = 0.0486 x Area + 2.631 | |
| 13 | 13 | 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) | |
| 14 | 14 | print(f"Area {a:5} sq ft actual {y:3} predicted {p:6.2f}") | Area 800 sq ft actual 41 predicted 41.53 | |
| 15 | 13 | 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) | |
| 16 | 14 | print(f"Area {a:5} sq ft actual {y:3} predicted {p:6.2f}") | Area 900 sq ft actual 47 predicted 46.39 | |
| 17 | 13 | 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) | |
| 18 | 14 | print(f"Area {a:5} sq ft actual {y:3} predicted {p:6.2f}") | Area 1000 sq ft actual 52 predicted 51.25 | |
| 19 | 13 | for a, y, p in zip(X_test.ravel(), y_test, pred): no items left โ loop ends | ||
| 20 | 15 | print("RMSE on test data:", round(np.sqrt(mean_squared_error(y_test, pred)), 3)) | RMSE on test data: 0.634 | |
| 21 | 16 | print("R2 on test data :", round(r2_score(y_test, pred), 4)) | R2 on test data : 0.9801 | |
| 22 | 17 | plt.scatter(X_train, y_train, label='Train'); plt.scatter(X_test, y_test, color='red', lab | ||
| 23 | 18 | plt.plot(area, model.predict(area), color='green', label='Regression line') | ||
| 24 | 19 | plt.xlabel('Area (sq ft)'); plt.ylabel('Price (lakh Rs)'); plt.title('Train-Test Split in | ||
| 25 | 20 | plt.legend(); plt.show() |
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)")
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)
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q8.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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()
Original size (h, w, channels): (300, 400, 3)
Resized to 200x150 : (150, 200, 3)
Half size : (150, 200, 3)
Enlarged 600x450 : (450, 600, 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q9.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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()))
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
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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q10.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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)
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.
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
question๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q11.py. - Press F5 (Run โ Run Module).
- Match your screen with the Sample Output. Then write the code + output in your practical file.
โ What each line does (colour = type of statement)
| Line | Code | What 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 |
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)
Errors: -10, 10, -10, 10, -15, 20, -10, -20
MSE = 193.75
RMSE = 13.92
MAE = 13.13
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
Accuracy = 87.5 % Precision = 85.7 % Recall = 80.0 % F1 = 82.8 %
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: Setosa forms a separate cluster (small petals); Versicolor and Virginica
overlap slightly. Petal features are the most informative.
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]
Predictions widget: 45 test flowers classified; Tree rule learnt -
'petal length <= 1.9 -> Setosa'.
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.
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.
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]
Hierarchical clustering grouped the images into 3 clusters matching cat, dog and bird;
2 images were placed in the wrong cluster.
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]
For 200 canteen reviews the largest words were: food, tasty, price, samosa, clean, slow.
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 insight: average AQI in winter months (Nov-Jan) was nearly double the monsoon
months; k-Means grouped cities into 3 pollution levels.
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))".
Test: parrot -> bird (92 %), elephant -> animal (88 %), bat -> bird (61 %, wrong - add more bat images).
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).
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.
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.
Plane: test loss 0.002 with no hidden layer.
Multi Gaussian: 0.21 (no hidden layer) -> 0.03 (2 hidden layers).
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
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.
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.
Website published; live webcam predictions displayed with class name and probability bars.
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()
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.996NEW ๐ 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
๐งโ๐ป Do it yourself - easy steps
- Click โถ Run in Python on the code box above (or open IDLE / Thonny / Jupyter โ File โ New File).
- Type the code exactly - indentation (4 spaces) matters in Python. Save it as
xii_ai_q25.py. - Press F5 (Run โ Run Module).
- 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)
| Line | Code | What 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)
| Step | Line | Line being run | Variables changed | On screen |
|---|---|---|---|---|
| 1 | 3 | import pandas as pd | ||
| 2 | 4 | import matplotlib.pyplot as plt | ||
| 3 | 5 | df = pd.DataFrame({ | ||
| 4 | 6 | 'Year': [1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012], | ||
| 5 | 7 | 'Enrolment_L': [42.0, 44.5, 46.8, 48.2, 50.1, 53.6, 55.0, 56.2, 57.1, 57.8], | ||
| 6 | 8 | 'Attendance': [61, 64, 67, 69, 71, 76, 79, 81, 83, 84], | ||
| 7 | 9 | 'Dropout': [38.0, 36.1, 33.9, 32.0, 30.4, 26.2, 23.5, 21.0, 18.6, 17.1]}) | ||
| 8 | 5 | df = pd.DataFrame({ | df = DataFrame (10 rows ร 4 columns) | |
| 9 | 10 | 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.โฆ | |
| 10 | 11 | print("\nDropout fell by", round(df.Dropout.iloc[0] - df.Dropout.iloc[-1], 1), "percentage | Dropout fell by 20.9 percentage points | |
| 11 | 12 | print("Correlation (Attendance vs Dropout):", round(df.Attendance.corr(df.Dropout), 3)) | Correlation (Attendance vs Dropout): -0.996 | |
| 12 | 14 | fig, ax1 = plt.subplots(figsize=(8, 4.5)) | fig = chart object, ax1 = chart object | |
| 13 | 15 | ax1.plot(df.Year, df.Dropout, 'r-o', label='Dropout rate (%)') | ||
| 14 | 16 | ax1.plot(df.Year, df.Attendance, 'g-s', label='Attendance (%)') | ||
| 15 | 17 | ax1.axvline(1995, color='grey', linestyle='--'); ax1.text(1995.3, 45, 'MDMS launched (1995 | ||
| 16 | 18 | ax1.axvline(2004, color='grey', linestyle=':'); ax1.text(2004.3, 52, 'Cooked-meal\nscheme | ||
| 17 | 19 | ax1.set_xticks(df.Year); ax1.set_xlabel('Year'); ax1.set_ylabel('Percent'); ax1.legend(loc | ||
| 18 | 20 | ax1.set_title('Mid-Day Meals and Dropout Rate (illustrative data)') | ||
| 19 | 21 | 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
Personal Expense Tracker (Console)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
expenses | list of dict | Each dict holds date, category, amount and note of one expense |
budget | float | Monthly budget set by the user |
CATEGORIES | tuple | Allowed categories: Food, Travel, Study, Health, Fun, Other |
FILE | str | Name of the data file - expenses.txt |
summary | dict | Category -> total amount (built from the list) |
# =====================================================================
# 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.")
============================================================
PERSONAL EXPENSE TRACKER - KV Student Edition
============================================================
Enter your monthly budget (Rs.): 5000
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 01-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Food
Amount (Rs.) : 450
Note : Lunch with friends
Expense added. Total records: 1
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 02-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Travel
Amount (Rs.) : 120
Note : Bus pass top-up
Expense added. Total records: 2
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 03-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Study
Amount (Rs.) : 650
Note : Reference books
Expense added. Total records: 3
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 04-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): games
Unknown category - saved under 'Other'.
Amount (Rs.) : 300
Note : Mobile game coins
Expense added. Total records: 4
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 05-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Food
Amount (Rs.) : abc
Invalid amount! Please enter digits only.
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 06-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Health
Amount (Rs.) : 800
Note : Doctor fees
Expense added. Total records: 5
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 1
Date (dd-mm-yyyy) : 07-07-2026
Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Other'): Food
Amount (Rs.) : 1200
Note : Birthday party
Expense added. Total records: 6
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 2
No Date Category Amount Note
------------------------------------------------------------
1 01-07-2026 Food 450.00 Lunch with friends
2 02-07-2026 Travel 120.00 Bus pass top-up
3 03-07-2026 Study 650.00 Reference books
4 04-07-2026 Other 300.00 Mobile game coins
5 06-07-2026 Health 800.00 Doctor fees
6 07-07-2026 Food 1200.00 Birthday party
------------------------------------------------------------
TOTAL 3520.00
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 3
----- CATEGORY SUMMARY -----
Food Rs. 1650.00 46.9% ###########
Health Rs. 800.00 22.7% #####
Study Rs. 650.00 18.5% ####
Other Rs. 300.00 8.5% ##
Travel Rs. 120.00 3.4%
Highest spending category: Food ( Rs. 1650.0 )
Lowest spending category: Travel ( Rs. 120.0 )
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 4
Enter category or word to search: bus
1 matching record(s)
No Date Category Amount Note
------------------------------------------------------------
1 02-07-2026 Travel 120.00 Bus pass top-up
------------------------------------------------------------
TOTAL 120.00
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 5
No Date Category Amount Note
------------------------------------------------------------
1 01-07-2026 Food 450.00 Lunch with friends
2 02-07-2026 Travel 120.00 Bus pass top-up
3 03-07-2026 Study 650.00 Reference books
4 04-07-2026 Other 300.00 Mobile game coins
5 06-07-2026 Health 800.00 Doctor fees
6 07-07-2026 Food 1200.00 Birthday party
------------------------------------------------------------
TOTAL 3520.00
E = Edit amount, D = Delete : E
Record number: 2
New amount: 300
Record 2 updated.
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 5
No Date Category Amount Note
------------------------------------------------------------
1 01-07-2026 Food 450.00 Lunch with friends
2 02-07-2026 Travel 300.00 Bus pass top-up
3 03-07-2026 Study 650.00 Reference books
4 04-07-2026 Other 300.00 Mobile game coins
5 06-07-2026 Health 800.00 Doctor fees
6 07-07-2026 Food 1200.00 Birthday party
------------------------------------------------------------
TOTAL 3700.00
E = Edit amount, D = Delete : D
Record number: 4
Record 4 deleted. Records left: 5
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 6
Sort by A = Amount, D = Date : A
No Date Category Amount Note
------------------------------------------------------------
1 07-07-2026 Food 1200.00 Birthday party
2 06-07-2026 Health 800.00 Doctor fees
3 03-07-2026 Study 650.00 Reference books
4 01-07-2026 Food 450.00 Lunch with friends
5 02-07-2026 Travel 300.00 Bus pass top-up
------------------------------------------------------------
TOTAL 3400.00
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 6
Sort by A = Amount, D = Date : D
No Date Category Amount Note
------------------------------------------------------------
1 01-07-2026 Food 450.00 Lunch with friends
2 02-07-2026 Travel 300.00 Bus pass top-up
3 03-07-2026 Study 650.00 Reference books
4 06-07-2026 Health 800.00 Doctor fees
5 07-07-2026 Food 1200.00 Birthday party
------------------------------------------------------------
TOTAL 3400.00
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 7
Budget Rs.5000.00 | Spent Rs.3400.00 | Used 68.0%
[============= ]
Good! Remaining budget: Rs. 1600.0
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 8
Most money goes to: Food
Tip: Carry lunch from home and limit eating out to weekends.
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 9
5 record(s) saved to expenses.txt
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 10
5 record(s) loaded from expenses.txt
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 15
Invalid choice, try again.
1.Add 2.View 3.Summary 4.Search 5.Edit/Delete 6.Sort
7.Budget 8.Tips 9.Save 10.Load 0.Exit
Enter choice: 0
5 record(s) saved to expenses.txt
Thank you for using Expense Tracker!
- Start
- Read monthly budget
- Display main menu and read choice
- Choice is 1 (Add)? → No: go to the matching menu option
- Read date, category, amount, note and append record
- Summary - total per category, share % and bar chart
- Search / edit / delete / sort records as selected
- Total > budget? → No: show remaining budget
- Show budget warning and saving tips
- Save records to expenses.txt
- Choice is 0 (Exit)? → No: show menu again
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Budget 5000; add Food 450 | Record stored, confirmation printed | PASS |
| 2 | Amount entered as 'abc' | 'Invalid amount' message, record not added | PASS |
| 3 | Category 'games' | Stored under 'Other' category | PASS |
| 4 | Category summary | Totals and % share add up to 100 % | PASS |
| 5 | Search 'bus' | Matching travel record shown | PASS |
| 6 | Edit record 2 to 300 | Amount updated and shown in list | PASS |
| 7 | Delete record 4 | Record removed; count reduces by 1 | PASS |
| 8 | Spending above 80 % of budget | Warning message printed | PASS |
| 9 | Save then Load | Same number of records read back from expenses.txt | PASS |
| 10 | Choice 15 | 'Invalid choice' and menu repeats | PASS |
โ 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
- Global variables / constants are created:
CATEGORIES,FILE,expenses,budget. - 13 functions are defined (lines 13โ183) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
line(ch, n) | 13โ15 | Prints a separator line. | banner(), show_all() |
banner() | 18โ22 | Shows the title of the application. | main program |
read_amount(prompt) | 25โ35 | Reads a positive amount; returns None for invalid input. | add_expense(), edit_delete(), main program |
add_expense() | 38โ50 | Adds one expense record to the list. | main program (menu) |
show_all(data) | 53โ64 | Displays the records in a table. | search_expense(), edit_delete(), sort_expenses(), main program (menu) |
category_summary() | 67โ83 | Shows total, share and a text bar chart for every category. | main program (menu) |
search_expense() | 86โ91 | Searches by category or by a word present in the note. | main program (menu) |
edit_delete() | 94โ115 | Edits the amount of a record or deletes it. | main program (menu) |
sort_expenses() | 118โ124 | Sorts by amount (high to low) or by date. | main program (menu) |
budget_status() | 127โ138 | Compares spending with the budget. | main program (menu) |
saving_tips() | 141โ157 | Gives tips for the category where most money is spent. | main program (menu) |
save_file() | 160โ166 | Saves all records to the text file. | main program (menu), main program |
load_file() | 169โ183 | Loads records from the text file. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
banner()โline()ร2 โread_amount()shows: PERSONAL EXPENSE TRACKER - KV Student Edition - 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)
- You type 1 at Enter choice:runs:
add_expense() - You type 01-07-2026 at Date (dd-mm-yyyy) :
- You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type 450 at Amount (Rs.) :
- You type Lunch with friends at Note :shows: Expense added. Total records: 1 (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 02-07-2026 at Date (dd-mm-yyyy) :
- You type Travel at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type 120 at Amount (Rs.) :
- You type Bus pass top-up at Note :shows: Expense added. Total records: 2 (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 03-07-2026 at Date (dd-mm-yyyy) :
- You type Study at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type 650 at Amount (Rs.) :
- You type Reference books at Note :shows: Expense added. Total records: 3 (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 04-07-2026 at Date (dd-mm-yyyy) :
- You type games at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount()shows: Unknown category - saved under 'Other'. - You type 300 at Amount (Rs.) :
- You type Mobile game coins at Note :shows: Expense added. Total records: 4 (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 05-07-2026 at Date (dd-mm-yyyy) :
- You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type abc at Amount (Rs.) :shows: Invalid amount! Please enter digits only. (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 06-07-2026 at Date (dd-mm-yyyy) :
- You type Health at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type 800 at Amount (Rs.) :
- You type Doctor fees at Note :shows: Expense added. Total records: 5 (+2 more lines)
- You type 1 at Enter choice:runs:
add_expense() - You type 07-07-2026 at Date (dd-mm-yyyy) :
- You type Food at Category ('Food', 'Travel', 'Study', 'Health', 'Fun', 'Otherruns:
read_amount() - You type 1200 at Amount (Rs.) :
- You type Birthday party at Note :shows: Expense added. Total records: 6 (+2 more lines)
- You type 2 at Enter choice:runs:
show_all()โline()ร2shows: No Date Category Amount Note (+9 more lines) - You type 3 at Enter choice:runs:
category_summary()shows: ----- CATEGORY SUMMARY ----- (+9 more lines) - You type 4 at Enter choice:runs:
search_expense() - You type bus at Enter category or word to search:runs:
show_all()โline()ร2shows: 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
School Grade Calculator
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
results | dict of dict | Student name -> {'marks': list of 5, 'total', 'pct', 'grade'} |
SUBJECTS | tuple | Names of the five subjects |
marks | list of float | Marks of one student in the five subjects |
GRADES | list of tuple | (minimum %, grade) pairs used by get_grade() |
# =====================================================================
# 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"))()
==============================================================
SCHOOL GRADE CALCULATOR & RESULT ANALYSER
==============================================================
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 1
Student name: Sara
Marks in English : 95
Marks in Maths : 92
Marks in Physics : 88
Marks in Chemistry : 97
Marks in CS : 90
Saved Sara: 92.40% Grade A1
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 1
Student name: Rahul
Marks in English : 78
Marks in Maths : 120
Marks must be 0-100. Try again.
Marks in Maths : 82
Marks in Physics : 69
Marks in Chemistry : 74
Marks in CS : 80
Saved Rahul: 76.60% Grade B1
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 1
Student name: Vikas
Marks in English : 45
Marks in Maths : 28
Marks in Physics : 51
Marks in Chemistry : 40
Marks in CS : 38
Saved Vikas: 40.40% Grade D
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 1
Student name: Meena
Marks in English : 88
Marks in Maths : 91
Marks in Physics : 79
Marks in Chemistry : 85
Marks in CS : 93
Saved Meena: 87.20% Grade A2
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 2
Name Engli Maths Physi Chemi CS Total % Gr Status
------------------------------------------------------------------------------------------
Sara 95 92 88 97 90 462 92.40 A1 PASS
Rahul 78 82 69 74 80 383 76.60 B1 PASS
Vikas 45 28 51 40 38 202 40.40 D COMPARTMENT
Meena 88 91 79 85 93 436 87.20 A2 PASS
------------------------------------------------------------------------------------------
Students: 4 | Passed: 3
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 3
Enter name: Rahul
--------------------------------------------------------------
REPORT CARD : Rahul
--------------------------------------------------------------
English 78 Grade B1
Maths 82 Grade A2
Physics 69 Grade B2
Chemistry 74 Grade B1
CS 80 Grade B1
--------------------------------------------------------------
Total 383/500 Percentage 76.60% Grade B1 PASS
Best subject: Maths | Needs attention: Physics
Remarks: Very good, keep it up.
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 4
1. Sara 92.40% A1
2. Meena 87.20% A2
3. Rahul 76.60% B1
4. Vikas 40.40% D
Class topper: Sara
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 5
Subject Average High Low Topper
English 76.50 95 45 Sara
Maths 73.25 92 28 Sara
Physics 71.75 88 51 Sara
Chemistry 74.00 97 40 Sara
CS 75.25 93 38 Meena
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 6
A1 #### 1
A2 #### 1
B1 #### 1
D #### 1
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 7
Enter name: Sara
1. English 2. Maths 3. Physics 4. Chemistry 5. CS
Subject number: 2
Marks in Maths : 85
Updated: Sara 91.00% A1
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 2
Name Engli Maths Physi Chemi CS Total % Gr Status
------------------------------------------------------------------------------------------
Sara 95 85 88 97 90 455 91.00 A1 PASS
Rahul 78 82 69 74 80 383 76.60 B1 PASS
Vikas 45 28 51 40 38 202 40.40 D COMPARTMENT
Meena 88 91 79 85 93 436 87.20 A2 PASS
------------------------------------------------------------------------------------------
Students: 4 | Passed: 3
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 8
Enter name to delete: Vikas
Vikas deleted. Students left: 3
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 3
Enter name: Arjun
Student not found.
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 4
1. Sara 91.00% A1
2. Meena 87.20% A2
3. Rahul 76.60% B1
Class topper: Sara
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 9
Invalid choice
1.Add 2.Result 3.Report Card 4.Rank 5.Subjects 6.Grades
7.Update 8.Delete 0.Exit
Enter choice: 0
Good luck for the exams!
- Start
- Display menu and read choice
- Choice is 1 (Add)? → No: go to the selected option
- Read name and 5 marks (0-100)
- total, percentage = total / 5, grade and status
- Store in the results dictionary
- Reports - result sheet, rank list, subject analysis, grade chart
- Update / delete records when chosen
- Choice is 0? → No: show menu again
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Marks 95, 92, 88, 97, 90 | Total 462, 92.4 %, grade A1, PASS | PASS |
| 2 | Mark 120 entered | 'Marks must be 0-100' and asked again | PASS |
| 3 | One subject below 33 | Status 'COMPARTMENT' | PASS |
| 4 | Rank list | Students in descending order of % | PASS |
| 5 | Subject analysis | Average/highest/lowest per subject printed | PASS |
| 6 | Report card of 'Rahul' | Full card with remarks shown | PASS |
| 7 | Update Maths of Sara to 85 | New total and grade recalculated | PASS |
| 8 | Delete 'Vikas' | Student removed; count reduced | PASS |
| 9 | Report 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
- Global variables / constants are created:
SUBJECTS,GRADES,results. - 13 functions are defined (lines 13โ149) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
line(n) | 13โ15 | Prints a separator line. | result_sheet(), report_card() |
get_grade(pct) | 18โ23 | Returns the CBSE-style grade for a percentage. | calculate(), report_card() |
status_of(marks) | 26โ29 | PASS, COMPARTMENT (one subject < 33) or FAIL (more than one). | calculate() |
read_marks(subject) | 32โ41 | Reads marks between 0 and 100 (asks again if invalid). | add_student(), update_marks() |
calculate(name) | 44โ50 | Recalculates total, percentage and grade of a student. | add_student(), update_marks() |
add_student() | 53โ62 | Adds a new student with marks of five subjects. | main program (menu) |
result_sheet() | 65โ76 | Displays the result of all students. | main program (menu) |
report_card() | 79โ96 | Prints the report card of one student. | main program (menu) |
rank_list() | 99โ105 | Shows students sorted by percentage. | main program (menu) |
subject_analysis() | 108โ117 | Average, highest, lowest and topper of each subject. | main program (menu) |
grade_distribution() | 120โ125 | Counts students in each grade and draws a text bar chart. | main program (menu) |
update_marks() | 128โ140 | Updates marks of one subject. | main program (menu) |
delete_student() | 143โ149 | Deletes a student record. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: SCHOOL GRADE CALCULATOR & RESULT ANALYSER (+2 more lines)
- You type 1 at Enter choice:runs:
add_student() - You type Sara at Student name:runs:
read_marks() - You type 95 at Marks in English :runs:
read_marks() - You type 92 at Marks in Maths :runs:
read_marks() - You type 88 at Marks in Physics :runs:
read_marks() - You type 97 at Marks in Chemistry :runs:
read_marks() - You type 90 at Marks in CS :runs:
calculate()โget_grade()โstatus_of()shows: Saved Sara: 92.40% Grade A1 (+2 more lines) - You type 1 at Enter choice:runs:
add_student() - You type Rahul at Student name:runs:
read_marks() - You type 78 at Marks in English :runs:
read_marks() - You type 120 at Marks in Maths :shows: Marks must be 0-100. Try again.
- You type 82 at Marks in Maths :runs:
read_marks() - You type 69 at Marks in Physics :runs:
read_marks() - You type 74 at Marks in Chemistry :runs:
read_marks() - You type 80 at Marks in CS :runs:
calculate()โget_grade()โstatus_of()shows: Saved Rahul: 76.60% Grade B1 (+2 more lines) - You type 1 at Enter choice:runs:
add_student() - You type Vikas at Student name:runs:
read_marks() - You type 45 at Marks in English :runs:
read_marks() - You type 28 at Marks in Maths :runs:
read_marks() - You type 51 at Marks in Physics :runs:
read_marks() - You type 40 at Marks in Chemistry :runs:
read_marks() - You type 38 at Marks in CS :runs:
calculate()โget_grade()โstatus_of()shows: Saved Vikas: 40.40% Grade D (+2 more lines) - You type 1 at Enter choice:runs:
add_student() - You type Meena at Student name:runs:
read_marks() - You type 88 at Marks in English :runs:
read_marks() - You type 91 at Marks in Maths :runs:
read_marks() - You type 79 at Marks in Physics :runs:
read_marks() - You type 85 at Marks in Chemistry :runs:
read_marks() - You type 93 at Marks in CS :runs:
calculate()โget_grade()โstatus_of()shows: Saved Meena: 87.20% Grade A2 (+2 more lines) - You type 2 at Enter choice:runs:
result_sheet()โline()ร2shows: Name Engli Maths Physi Chemi CS Total % Gr Status (+7 more lines) - You type 3 at Enter choice:runs:
report_card() - You type Rahul at Enter name:runs:
line()ร2 โget_grade()ร5 โline()shows: REPORT CARD : Rahul (+10 more lines) - You type 4 at Enter choice:runs:
rank_list()shows: 1. Sara 92.40% A1 (+6 more lines) - You type 5 at Enter choice:runs:
subject_analysis()shows: Subject Average High Low Topper (+7 more lines) - You type 6 at Enter choice:runs:
grade_distribution()shows: A1 #### 1 (+5 more lines) - You type 7 at Enter choice:runs:
update_marks() - You type Sara at Enter name:shows: 1. English 2. Maths 3. Physics 4. Chemistry 5. CS
- You type 2 at Subject number:runs:
read_marks() - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Number Pattern & Math Puzzle Generator
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
๐ฏ Objectives
- Print patterns using loops
- Test Armstrong, prime and palindrome numbers
- Generate random questions with the random module and keep a score
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
n | int | Number entered by the user |
score | int | Correct answers in the quiz |
history | list | Names of tools used in the session |
ops | tuple | Operators used in the quiz: + - * |
# =====================================================================
# 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")
========================================================
NUMBER PATTERN & MATH PUZZLE GENERATOR
========================================================
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 1
Enter rows: 4
Right triangle:
*
**
***
****
Inverted triangle:
****
***
**
*
Pyramid:
*
* *
* * *
* * * *
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 2
Enter rows: 5
Number triangle:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 3
Enter number: 153
153 is an Armstrong number
153 is NOT a Prime number
153 is NOT a Perfect number
153 is NOT a Palindrome
153 is ODD
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 3
Enter number: 28
28 is NOT an Armstrong number
28 is NOT a Prime number
28 is a Perfect number
28 is NOT a Palindrome
28 is EVEN
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 3
Enter number: 97
97 is NOT an Armstrong number
97 is a Prime number
97 is NOT a Perfect number
97 is NOT a Palindrome
97 is ODD
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 4
How many terms / factorial of: 10
Fibonacci: 0 1 1 2 3 5 8 13 21 34
10! = 3628800
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 5
Lower limit: 10
Upper limit: 50
Primes: 11 13 17 19 23 29 31 37 41 43 47
Count : 11 | Sum: 311
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 6
First number : 12
Second number: 18
(12, 18) -> (18, 12)
(18, 12) -> (12, 6)
(12, 6) -> (6, 0)
HCF = 6 | LCM = 36
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 7
Enter number: 4096
Sum of digits : 19
Product of digits: 0
Reverse : 6904
Number of digits : 4
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 8
Number of questions: 3
Q1: 5 * 12 = 60
Correct!
Q2: 18 + 5 = 23
Correct!
Q3: 19 * 15 = 200
Wrong! Answer: 285
Score 2/3 Accuracy 66.7%
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 9
Invalid choice
1.Star patterns 2.Number patterns 3.Number checker 4.Fibonacci & factorial
5.Primes in range 6.HCF & LCM 7.Digit operations 8.Maths quiz
0.Exit Enter choice: 0
Tools used this session: Star patterns, Number patterns, Number checker, Number checker, Number checker, Fibonacci & factorial, Primes in range, HCF & LCM, Digit operations, Maths quiz
- Start
- Display menu and read choice
- Valid choice? → No: print 'Invalid choice'
- Read number / rows / range
- Run the selected tool (pattern, check, series, quiz)
- Display result
- Add tool name to history
- Choice is 0? → No: show menu
- Print session summary
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Star pattern with 4 rows | Three patterns of 4 rows | PASS |
| 2 | Number 153 | Armstrong, not prime, not perfect, not palindrome, odd | PASS |
| 3 | Number 28 | Perfect number | PASS |
| 4 | Number 97 | Prime | PASS |
| 5 | Fibonacci 10 terms | 0 1 1 2 3 5 8 13 21 34 | PASS |
| 6 | Primes 10-50 | 11 primes listed | PASS |
| 7 | HCF/LCM of 12, 18 | HCF 6, LCM 36 | PASS |
| 8 | Digit ops on 4096 | Sum 19, product 0, reverse 6904, 4 digits | PASS |
| 9 | Quiz 3 rounds | Score and accuracy printed | PASS |
โ 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
- Imports (line 6):
random- random number functions are loaded. - Global variables / constants are created:
history. - 10 functions are defined (lines 11โ135) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_int(msg) | 11โ17 | Reads an integer safely. | star_patterns(), number_patterns(), number_checker(), fibo_fact() |
star_patterns() | 20โ31 | Prints three star patterns. | main program (menu) |
number_patterns() | 34โ47 | Number triangle and Floyd's triangle. | main program (menu) |
is_prime(n) | 50โ57 | Returns True if n is prime. | number_checker(), primes_in_range() |
number_checker() | 60โ70 | Runs five checks on a number. | main program (menu) |
fibo_fact() | 73โ84 | Fibonacci series and factorial. | main program (menu) |
primes_in_range() | 87โ93 | Lists primes between two numbers. | main program (menu) |
hcf_lcm() | 96โ104 | HCF using Euclid's algorithm and LCM. | main program (menu) |
digit_ops() | 107โ118 | Sum, product, reverse and count of digits. | main program (menu) |
math_quiz() | 121โ135 | Random arithmetic quiz with score. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: NUMBER PATTERN & MATH PUZZLE GENERATOR (+2 more lines)
- You type 1 at 0.Exit Enter choice:runs:
star_patterns()โread_int() - You type 4 at Enter rows:shows: Right triangle: (+4 more lines)
- You type 2 at 0.Exit Enter choice:runs:
number_patterns()โread_int() - You type 5 at Enter rows:shows: Number triangle: (+13 more lines)
- You type 3 at 0.Exit Enter choice:runs:
number_checker()โread_int() - You type 153 at Enter number:runs:
is_prime()shows: 153 is an Armstrong number (+6 more lines) - You type 3 at 0.Exit Enter choice:runs:
number_checker()โread_int() - You type 28 at Enter number:runs:
is_prime()shows: 28 is NOT an Armstrong number (+6 more lines) - You type 3 at 0.Exit Enter choice:runs:
number_checker()โread_int() - You type 97 at Enter number:runs:
is_prime()shows: 97 is NOT an Armstrong number (+6 more lines) - You type 4 at 0.Exit Enter choice:runs:
fibo_fact()โread_int() - You type 10 at How many terms / factorial of:shows: Fibonacci: 0 1 1 2 3 5 8 13 21 34 (+3 more lines)
- You type 5 at 0.Exit Enter choice:runs:
primes_in_range()โread_int() - You type 10 at Lower limit:runs:
read_int() - You type 50 at Upper limit:runs:
is_prime()ร41shows: Primes: 11 13 17 19 23 29 31 37 41 43 47 (+3 more lines) - You type 6 at 0.Exit Enter choice:runs:
hcf_lcm()โread_int() - You type 12 at First number :runs:
read_int() - You type 18 at Second number:shows: (12, 18) -> (18, 12) (+5 more lines)
- You type 7 at 0.Exit Enter choice:runs:
digit_ops()โread_int() - You type 4096 at Enter number:shows: Sum of digits : 19 (+5 more lines)
- You type 8 at 0.Exit Enter choice:runs:
math_quiz()โread_int() - You type 3 at Number of questions:runs:
read_int() - You type 60 at Q1: 5 * 12 =runs:
read_int()shows: Correct! - You type 23 at Q2: 18 + 5 =runs:
read_int()shows: Correct! - You type 200 at Q3: 19 * 15 =shows: Wrong! Answer: 285 (+3 more lines)
- You type 9 at 0.Exit Enter choice:shows: Invalid choice (+2 more lines)
- 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Simple Library Catalogue (In-Memory)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
library | dict of dict | Book ID -> {title, author, category, total, available, issued_count} |
issued | list of dict | Current issues: book id, member, day issued |
fine_total | int | Total fine collected in the session |
FINE_PER_DAY | int | Rs. 2 for every day after 14 days |
# =====================================================================
# 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"))()
===================================================================
KV LIBRARY CATALOGUE
===================================================================
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 2
ID Title Author Category Avail
-------------------------------------------------------------------
101 Python Programming Sumita Arora Computer 3/3
102 Learn Python Basics Reema Thareja Computer 2/2
103 The Discovery of India Jawaharlal Nehru History 2/2
104 Panchatantra Vishnu Sharma Stories 1/1
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 1
Book ID: 105
Title : Wings of Fire
Author : A.P.J. Abdul Kalam
Category: Biography
Copies : 2
Book added with 2 copies.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 1
Book ID: 101
Book exists. Extra copies to add: 1
Copies updated: 4 available
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 3
Search word: python
2 book(s) found
ID Title Author Category Avail
-------------------------------------------------------------------
101 Python Programming Sumita Arora Computer 4/4
102 Learn Python Basics Reema Thareja Computer 2/2
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 4
Book ID to issue: 103
Member name: Riya
'The Discovery of India' issued to Riya. Return within 14 days.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 4
Book ID to issue: 104
Member name: Kabir
'Panchatantra' issued to Kabir. Return within 14 days.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 4
Book ID to issue: 104
Member name: Om
All copies are issued. Please try later.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 4
Book ID to issue: 101
Member name: Kabir
'Python Programming' issued to Kabir. Return within 14 days.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 6
1. The Discovery of India -> Riya
2. Panchatantra -> Kabir
3. Python Programming -> Kabir
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 5
Book ID to return: 103
Member name: Riya
Days kept: 20
Book returned. Late by 6 days. Fine Rs. 12
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 5
Book ID to return: 101
Member name: Kabir
Days kept: 7
Book returned. No fine.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 7
Category Titles Copies
Biography 1 2 ##
Computer 2 6 ######
History 1 2 ##
Stories 1 1 #
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 8
Book ID to delete: 102
Deleted: Learn Python Basics
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 8
Book ID to delete: 104
Cannot delete - copies are issued.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 4
Book ID to issue: abc
Enter a valid number.
Book ID not found.
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 9
Titles: 4 | Copies: 9 | Issued now: 1
Most issued book: Python Programming (1 times)
Total fine collected: Rs. 12
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 2
ID Title Author Category Avail
-------------------------------------------------------------------
101 Python Programming Sumita Arora Computer 4/4
103 The Discovery of India Jawaharlal Nehru History 2/2
104 Panchatantra Vishnu Sharma Stories 0/1
105 Wings of Fire A.P.J. Abdul Kalam Biography 2/2
1.Add 2.Show 3.Search 4.Issue 5.Return 6.Issued 7.Category 8.Delete 9.Stats 0.Exit
Enter choice: 0
Library closed. Happy reading!
- Start
- Load sample books into the library dictionary
- Display menu and read choice
- Choice is Issue? → No: go to the selected option
- Copies available > 0? → No: print 'not available'
- Reduce available copies, add to issued list
- Return - find issue, add copy, fine = (days - 14) x 2
- Show reports / search results
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add book 105 'Wings of Fire' | Book added with 2 copies | PASS |
| 2 | Add ID 101 again | Copies of existing book increased | PASS |
| 3 | Search 'python' | Both Python books listed | PASS |
| 4 | Issue 103 to Riya | Available copies reduce by 1 | PASS |
| 5 | Issue 104 (0 copies left) | 'All copies are issued' message | PASS |
| 6 | Return 103 after 20 days | Fine Rs. 12 charged | PASS |
| 7 | Delete issued book | 'Cannot delete - copies issued' | PASS |
| 8 | Book ID 'abc' | 'Enter a valid number' | PASS |
| 9 | Statistics | Most issued book and total fine printed | PASS |
โ 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
- Global variables / constants are created:
FINE_PER_DAY,library,issued,fine_total. - 10 functions are defined (lines 16โ133) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_int(msg) | 16โ22 | Reads an integer; returns None for invalid input. | add_book(), issue_book(), return_book(), delete_book() |
show(ids) | 25โ32 | Displays books in a table. | search(), main program (menu) |
add_book() | 35โ51 | Adds a new book or extra copies. | main program (menu) |
search() | 54โ60 | Partial search by title, author or category. | main program (menu) |
issue_book() | 63โ76 | Issues one copy of a book. | main program (menu) |
return_book() | 79โ93 | Returns a book and calculates fine. | main program (menu) |
issued_list() | 96โ101 | Shows currently issued books. | main program (menu) |
category_report() | 104โ113 | Titles and copies per category. | main program (menu) |
delete_book() | 116โ124 | Deletes a book if no copy is issued. | main program (menu) |
statistics() | 127โ133 | Library statistics. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: KV LIBRARY CATALOGUE (+1 more lines)
- You type 2 at Enter choice:runs:
show()shows: ID Title Author Category Avail (+5 more lines) - You type 1 at Enter choice:runs:
add_book()โread_int() - You type 105 at Book ID:
- You type Wings of Fire at Title :
- You type A.P.J. Abdul Kalam at Author :
- You type Biography at Category:runs:
read_int() - You type 2 at Copies :shows: Book added with 2 copies. (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 101 at Book ID:runs:
read_int() - You type 1 at Book exists. Extra copies to add:shows: Copies updated: 4 available (+1 more lines)
- You type 3 at Enter choice:runs:
search() - You type python at Search word:runs:
show()shows: 2 book(s) found (+4 more lines) - You type 4 at Enter choice:runs:
issue_book()โread_int() - You type 103 at Book ID to issue:
- You type Riya at Member name:shows: 'The Discovery of India' issued to Riya. Return within 14 days. (+1 more lines)
- You type 4 at Enter choice:runs:
issue_book()โread_int() - You type 104 at Book ID to issue:
- You type Kabir at Member name:shows: 'Panchatantra' issued to Kabir. Return within 14 days. (+1 more lines)
- You type 4 at Enter choice:runs:
issue_book()โread_int() - You type 104 at Book ID to issue:
- You type Om at Member name:shows: All copies are issued. Please try later. (+1 more lines)
- You type 4 at Enter choice:runs:
issue_book()โread_int() - You type 101 at Book ID to issue:
- You type Kabir at Member name:shows: 'Python Programming' issued to Kabir. Return within 14 days. (+1 more lines)
- You type 6 at Enter choice:runs:
issued_list()shows: 1. The Discovery of India -> Riya (+3 more lines) - You type 5 at Enter choice:runs:
return_book()โread_int() - You type 103 at Book ID to return:
- You type Riya at Member name:runs:
read_int() - You type 20 at Days kept:shows: Book returned. Late by 6 days. Fine Rs. 12 (+1 more lines)
- You type 5 at Enter choice:runs:
return_book()โread_int() - You type 101 at Book ID to return:
- You type Kabir at Member name:runs:
read_int() - You type 7 at Days kept:shows: Book returned. No fine. (+1 more lines)
- You type 7 at Enter choice:runs:
category_report()shows: Category Titles Copies (+5 more lines) - You type 8 at Enter choice:runs:
delete_book()โread_int() - You type 102 at Book ID to delete:shows: Deleted: Learn Python Basics (+1 more lines)
- You type 8 at Enter choice:runs:
delete_book()โread_int() - You type 104 at Book ID to delete:shows: Cannot delete - copies are issued. (+1 more lines)
- 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Word & Text Analyzer Tool
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
text | str | Paragraph being analysed |
words | list | Clean lower-case words of the text |
freq | dict | Word -> number of times it appears |
STOP | set | Common words ignored in frequency (the, is, a ...) |
VOWELS | str | 'aeiou' |
# =====================================================================
# 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"))()
============================================================
WORD & TEXT ANALYZER
============================================================
Sample text loaded: India is a land of diversity. India has many languages,...
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 2
Characters : 247
Letters : 199 (vowels 82, consonants 117)
Upper case : 13 | Digits: 0 | Spaces: 40
Words : 41 | Unique words: 32
Sentences : 5
Reading time (200 words/min): 12 seconds
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 3
Top words (stop words ignored):
india 5 ###############
celebrate 1 ###
changing 1 ###
child 1 ###
christmas 1 ###
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 4
Longest word : technology
Shortest word : a
Average length: 4.85 letters
Palindromes : ['level']
Capitalised : Christmas, Diwali, Education, Eid, Guru, India, Is, Purab, The
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 5
Word to search: india
'india' found 5 time(s) at word positions [1, 7, 17, 28, 41]
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 6
Replace word: India
With : Bharat
5 replacement(s) done.
Bharat is a land of diversity. Bharat has many languages, festivals and foods. The people of Bharat celebrate Diwali, Eid, Christmas and Guru Purab with joy! Is Bharat a level playing field for every child? Education and technology are changing Bharat.
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 7
Title case : Bharat Is A Land Of Diversity. Bharat Has Many Languages, Festivals And Foods. The People ...
Reverse words: Bharat. changing are technology and Education child? every for field playing level a Bhara...
No vowels : Bhrt s lnd f dvrsty. Bhrt hs mny lnggs, fstvls nd fds. Th ppl f Bhrt clbrt Dwl, d, Chrstm...
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 8
a:29 b:7 c:6 d:11 e:18 f:6
g:7 h:12 i:15 j:1 l:12 m:2
n:11 o:10 p:4 r:13 s:10 t:13
u:5 v:4 w:2 y:6
Most frequent letter: a (29 times)
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 1
Enter a paragraph (blank = keep sample):
Text cannot be empty - sample text kept.
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 1
Enter a paragraph (blank = keep sample):
Madam Anna saw a level racecar at noon. Wow! 2 kids, 3 dogs.
Text saved: 60 characters
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 2
Characters : 60
Letters : 42 (vowels 17, consonants 25)
Upper case : 3 | Digits: 2 | Spaces: 12
Words : 13 | Unique words: 13
Sentences : 3
Reading time (200 words/min): 4 seconds
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 4
Longest word : racecar
Shortest word : a
Average length: 3.38 letters
Palindromes : ['anna', 'level', 'madam', 'noon', 'racecar', 'wow']
Capitalised : Anna, Madam, Wow
1.Enter Text 2.Stats 3.Frequency 4.Insights 5.Search 6.Replace
7.Text Tools 8.Char Frequency 0.Exit
Enter choice: 0
Thank you for using Text Analyzer.
- Start
- Load sample text
- Display menu and read choice
- Choice is 1? → No: run the selected analysis
- Read new paragraph
- Clean words - lower case, strip punctuation
- Count characters / build frequency dictionary
- Display statistics, charts or modified text
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Sample text statistics | Counts of letters, vowels, words, sentences printed | PASS |
| 2 | Word frequency | Top-5 words without stop words | PASS |
| 3 | Search 'india' | Count and word positions shown | PASS |
| 4 | Replace 'India' by 'Bharat' | All occurrences replaced | PASS |
| 5 | Word 'level' in text | Listed as palindrome | PASS |
| 6 | Empty paragraph | 'Text cannot be empty' message | PASS |
| 7 | Text tools | Title case, reversed words and vowel-less text printed | PASS |
| 8 | Character frequency | Letters with counts in alphabetical order | PASS |
โ 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
- Global variables / constants are created:
VOWELS,STOP,text. - 9 functions are defined (lines 14โ105) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
words_of(t) | 14โ16 | Returns clean lower-case words. | basic_stats(), word_frequency(), word_insights(), search_word() |
enter_text() | 19โ27 | Reads a new paragraph. | main program (menu) |
basic_stats() | 30โ44 | Counts different kinds of characters, words and sentences. | main program (menu) |
word_frequency() | 47โ56 | Top words with a bar chart. | main program (menu) |
word_insights() | 59โ68 | Longest, shortest, average length, palindromes, capitals. | main program (menu) |
search_word() | 71โ75 | Finds positions of a word. | main program (menu) |
replace_word() | 78โ85 | Replaces a word everywhere. | main program (menu) |
text_tools() | 88โ92 | Title case, reverse words, remove vowels. | main program (menu) |
char_frequency() | 95โ105 | Frequency of each letter. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: WORD & TEXT ANALYZER (+3 more lines)
- You type 2 at Enter choice:runs:
basic_stats()โwords_of()shows: Characters : 247 (+7 more lines) - You type 3 at Enter choice:runs:
word_frequency()โwords_of()shows: Top words (stop words ignored): (+7 more lines) - You type 4 at Enter choice:runs:
word_insights()โwords_of()shows: Longest word : technology (+6 more lines) - You type 5 at Enter choice:runs:
search_word() - 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) - You type 6 at Enter choice:runs:
replace_word() - You type India at Replace word:
- You type Bharat at With :shows: 5 replacement(s) done. (+3 more lines)
- 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) - 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) - You type 1 at Enter choice:runs:
enter_text() - You type (Enter) at Enter a paragraph (blank = keep sample):shows: Text cannot be empty - sample text kept. (+2 more lines)
- You type 1 at Enter choice:runs:
enter_text() - 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)
- You type 2 at Enter choice:runs:
basic_stats()โwords_of()shows: Characters : 60 (+7 more lines) - You type 4 at Enter choice:runs:
word_insights()โwords_of()shows: Longest word : racecar (+6 more lines) - You type 0 at Enter choice:shows: Thank you for using Text Analyzer.
โค Inside each function - line by line
words_of() - lines 14โ16
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Contact Book Manager
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
๐ฏ Objectives
- Validate input with isdigit() and len()
- Use sorted() to display data in alphabetical order
- Build CRUD operations around a dictionary
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
contacts | dict of dict | Name -> {mobile, email, city, group, fav} |
GROUPS | tuple | Allowed groups |
valid_mobile() | function | True for 10-digit numbers starting with 6-9 |
valid_email() | function | Checks one '@' and a '.' after it |
# =====================================================================
# 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"))()
================================================================
CONTACT BOOK MANAGER
================================================================
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Asha
Mobile : 9876543210
E-mail : asha@kvs.in
City : Delhi
Group ('Family', 'Friends', 'School', 'Work'): Family
Contact saved: Asha
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Ravi
Mobile : 12345
Invalid mobile! 10 digits starting with 6-9 required.
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Ravi
Mobile : 5876543210
Invalid mobile! 10 digits starting with 6-9 required.
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Ravi
Mobile : 9123456780
E-mail : ravi.gmail.com
Invalid e-mail address.
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Ravi
Mobile : 9123456780
E-mail : ravi@gmail.com
City : Noida
Group ('Family', 'Friends', 'School', 'Work'): Friends
Contact saved: Ravi
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Neha
Mobile : 9876543210
Number already saved for Asha
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Neha
Mobile : 8800112233
E-mail : neha@school.org
City : Delhi
Group ('Family', 'Friends', 'School', 'Work'): School
Contact saved: Neha
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 1
Name : Tarun
Mobile : 7011223344
E-mail : tarun@work.com
City : Gurugram
Group ('Family', 'Friends', 'School', 'Work'): Work
Contact saved: Tarun
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 2
Name Mobile E-mail City Group Fav
----------------------------------------------------------------
Asha 9876543210 asha@kvs.in Delhi Family
Neha 8800112233 neha@school.org Delhi School
Ravi 9123456780 ravi@gmail.com Noida Friends
Tarun 7011223344 tarun@work.com Gurugram Work
Total contacts: 4
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 3
Search (name / number / city): del
Name Mobile E-mail City Group Fav
----------------------------------------------------------------
Asha 9876543210 asha@kvs.in Delhi Family
Neha 8800112233 neha@school.org Delhi School
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 4
Group: School
1 contact(s) in School
Name Mobile E-mail City Group Fav
----------------------------------------------------------------
Neha 8800112233 neha@school.org Delhi School
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 5
Name to update: Ravi
1.Mobile 2.E-mail 3.City 4.Group
Field: 3
New value: Delhi
Ravi updated: Delhi
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 7
Name to mark (or L to list): Asha
Asha is now a favourite
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 7
Name to mark (or L to list): L
Favourites: Asha
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 6
Name to delete: Tarun
Delete Tarun? (Y/N): N
Not deleted.
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 6
Name to delete: Tarun
Delete Tarun? (Y/N): Y
Deleted.
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 8
Family # 1
Friends # 1
School # 1
Work 0
City-wise: {'Delhi': 3}
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 2
Name Mobile E-mail City Group Fav
----------------------------------------------------------------
Asha 9876543210 asha@kvs.in Delhi Family *
Neha 8800112233 neha@school.org Delhi School
Ravi 9123456780 ravi@gmail.com Delhi Friends
Total contacts: 3
1.Add 2.Show 3.Search 4.Group 5.Update 6.Delete 7.Favourite 8.Stats 0.Exit
Enter choice: 0
Contact book closed.
- Start
- Display menu and read choice
- Choice is Add? → No: run selected option
- Read name, mobile, e-mail, city, group
- Mobile and e-mail valid? → No: show error and stop adding
- Mobile already saved? → No: save contact
- Search / filter / update / delete as chosen
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add Asha 9876543210 | Contact saved | PASS |
| 2 | Mobile 12345 | 'Invalid mobile' message | PASS |
| 3 | Mobile starting with 5 | Rejected | PASS |
| 4 | E-mail 'ravi.gmail.com' | 'Invalid e-mail' message | PASS |
| 5 | Same mobile for another name | 'Number already saved for ...' | PASS |
| 6 | Search 'del' | Contacts from Delhi listed | PASS |
| 7 | Filter group School | Only School contacts | PASS |
| 8 | Update city of Ravi | City changed | PASS |
| 9 | Delete with 'N' | Contact kept | PASS |
| 10 | Statistics | Group-wise and city-wise counts | PASS |
โ 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
- Global variables / constants are created:
GROUPS,contacts. - 11 functions are defined (lines 11โ135) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
valid_mobile(m) | 11โ13 | 10 digits starting with 6, 7, 8 or 9. | add_contact(), update_contact() |
valid_email(e) | 16โ18 | Very simple e-mail check. | add_contact() |
table(names) | 21โ27 | Prints contacts as a table. | show_all(), search(), by_group() |
add_contact() | 30โ50 | Adds a contact with validation. | main program (menu) |
show_all() | 53โ59 | All contacts A-Z. | main program (menu) |
search() | 62โ69 | Search by name, number or city. | main program (menu) |
by_group() | 72โ78 | Contacts of one group. | main program (menu) |
update_contact() | 81โ98 | Updates one field of a contact. | main program (menu) |
delete_contact() | 101โ111 | Deletes after confirmation. | main program (menu) |
favourites() | 114โ124 | Toggle a favourite or list favourites. | main program (menu) |
statistics() | 127โ135 | Group-wise and city-wise counts. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CONTACT BOOK MANAGER (+1 more lines)
- You type 1 at Enter choice:runs:
add_contact() - You type Asha at Name :
- You type 9876543210 at Mobile :runs:
valid_mobile() - You type asha@kvs.in at E-mail :runs:
valid_email() - You type Delhi at City :
- You type Family at Group ('Family', 'Friends', 'School', 'Work'):shows: Contact saved: Asha (+1 more lines)
- You type 1 at Enter choice:runs:
add_contact() - You type Ravi at Name :
- You type 12345 at Mobile :runs:
valid_mobile()shows: Invalid mobile! 10 digits starting with 6-9 required. (+1 more lines) - You type 1 at Enter choice:runs:
add_contact() - You type Ravi at Name :
- You type 5876543210 at Mobile :runs:
valid_mobile()shows: Invalid mobile! 10 digits starting with 6-9 required. (+1 more lines) - You type 1 at Enter choice:runs:
add_contact() - You type Ravi at Name :
- You type 9123456780 at Mobile :runs:
valid_mobile() - You type ravi.gmail.com at E-mail :runs:
valid_email()shows: Invalid e-mail address. (+1 more lines) - You type 1 at Enter choice:runs:
add_contact() - You type Ravi at Name :
- You type 9123456780 at Mobile :runs:
valid_mobile() - You type ravi@gmail.com at E-mail :runs:
valid_email() - You type Noida at City :
- You type Friends at Group ('Family', 'Friends', 'School', 'Work'):shows: Contact saved: Ravi (+1 more lines)
- You type 1 at Enter choice:runs:
add_contact() - You type Neha at Name :
- You type 9876543210 at Mobile :runs:
valid_mobile()shows: Number already saved for Asha (+1 more lines) - You type 1 at Enter choice:runs:
add_contact() - You type Neha at Name :
- You type 8800112233 at Mobile :runs:
valid_mobile() - You type neha@school.org at E-mail :runs:
valid_email() - You type Delhi at City :
- You type School at Group ('Family', 'Friends', 'School', 'Work'):shows: Contact saved: Neha (+1 more lines)
- You type 1 at Enter choice:runs:
add_contact() - You type Tarun at Name :
- You type 7011223344 at Mobile :runs:
valid_mobile() - You type tarun@work.com at E-mail :runs:
valid_email() - You type Gurugram at City :
- You type Work at Group ('Family', 'Friends', 'School', 'Work'):shows: Contact saved: Tarun (+1 more lines)
- You type 2 at Enter choice:runs:
show_all()โtable()shows: Name Mobile E-mail City Group Fav (+6 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Tic-Tac-Toe (Two Player Game)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
board | list of 9 str | Cells of the board: 'X', 'O' or ' ' |
WINS | tuple of tuples | The 8 winning lines (rows, columns, diagonals) |
scores | dict | Player name -> wins, plus 'Draw' |
moves | list | Positions played in the current round |
# =====================================================================
# 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")
========================================
TIC - TAC - TOE
========================================
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 4
Get three of your marks in a row, column or diagonal.
Cells are numbered:
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 1
Player X name: Rahul
Player O name: Priya
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Rahul (X), choose cell (1-9): 1
X | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Priya (O), choose cell (1-9): 5
X | 2 | 3
---+---+---
4 | O | 6
---+---+---
7 | 8 | 9
Rahul (X), choose cell (1-9): 2
X | X | 3
---+---+---
4 | O | 6
---+---+---
7 | 8 | 9
Priya (O), choose cell (1-9): 5
Cell already taken!
Priya (O), choose cell (1-9): 9
X | X | 3
---+---+---
4 | O | 6
---+---+---
7 | 8 | O
Rahul (X), choose cell (1-9): 10
Enter 1-9.
Rahul (X), choose cell (1-9): 3
X | X | X
---+---+---
4 | O | 6
---+---+---
7 | 8 | O
*** Rahul wins in 5 moves! ***
Moves: [1, 5, 2, 9, 3]
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 1
Player X name: Rahul
Player O name: Priya
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Rahul (X), choose cell (1-9): 5
1 | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Priya (O), choose cell (1-9): 1
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Rahul (X), choose cell (1-9): 9
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | X
Priya (O), choose cell (1-9): 3
O | 2 | O
---+---+---
4 | X | 6
---+---+---
7 | 8 | X
Rahul (X), choose cell (1-9): 2
O | X | O
---+---+---
4 | X | 6
---+---+---
7 | 8 | X
Priya (O), choose cell (1-9): 8
O | X | O
---+---+---
4 | X | 6
---+---+---
7 | O | X
Rahul (X), choose cell (1-9): 4
O | X | O
---+---+---
X | X | 6
---+---+---
7 | O | X
Priya (O), choose cell (1-9): 6
O | X | O
---+---+---
X | X | O
---+---+---
7 | O | X
Rahul (X), choose cell (1-9): 7
O | X | O
---+---+---
X | X | O
---+---+---
X | O | X
Match drawn! Moves: [5, 1, 9, 3, 2, 8, 4, 6, 7]
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 2
Your name: Anu
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Anu (X), choose cell (1-9): 1
X | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Computer chooses 5
X | 2 | 3
---+---+---
4 | O | 6
---+---+---
7 | 8 | 9
Anu (X), choose cell (1-9): 2
X | X | 3
---+---+---
4 | O | 6
---+---+---
7 | 8 | 9
Computer chooses 3
X | X | O
---+---+---
4 | O | 6
---+---+---
7 | 8 | 9
Anu (X), choose cell (1-9): 6
X | X | O
---+---+---
4 | O | X
---+---+---
7 | 8 | 9
Computer chooses 7
X | X | O
---+---+---
4 | O | X
---+---+---
O | 8 | 9
*** Computer wins in 6 moves! ***
Moves: [1, 5, 2, 3, 6, 7]
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 7
Invalid choice
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 3
SCORE BOARD
Draw 1 *
Rahul 1 *
Computer 1 *
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 5
Scores reset.
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 3
SCORE BOARD
Draw 0
1.Two Players 2.Vs Computer 3.Scores 4.Rules 5.Reset 0.Exit
Enter choice: 0
SCORE BOARD
Draw 0
Thanks for playing!
- Start
- Display menu and read choice
- Choice is a game mode? → No: show scores / rules / exit
- Create empty board and set first player
- Read move (or computer chooses move)
- Cell free and valid? → No: ask again
- Place mark and check winning lines
- Winner or board full? → No: switch player
- Update score board
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Rahul X: 1,2,3 vs Priya O: 5,9 | Rahul wins (top row) | PASS |
| 2 | Move on occupied cell | 'Cell already taken' and ask again | PASS |
| 3 | Move 10 | 'Enter 1-9' | PASS |
| 4 | All 9 cells filled, no line | 'Match drawn' | PASS |
| 5 | Computer can win in one move | Computer completes its line | PASS |
| 6 | Player about to win | Computer blocks the cell | PASS |
| 7 | Score board after 3 games | Wins and draws counted correctly | PASS |
| 8 | Reset scores | All scores 0 | PASS |
โ 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
- Global variables / constants are created:
WINS,scores. - 8 functions are defined (lines 11โ97) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
show(board) | 11โ18 | Draws the board. | play(), rules() |
winner(board, mark) | 21โ23 | True if mark has three in a line. | computer_move(), play() |
read_move(board, name) | 26โ39 | Reads a valid free cell. | play() |
computer_move(board, me, opp) | 42โ54 | Win, else block, else centre, corners, sides. | play() |
play(p1, p2, vs_computer) | 57โ78 | Plays one round and returns the winner's name or 'Draw'. | main program |
record(result) | 81โ83 | Updates the score board. | main program |
score_board() | 86โ90 | Displays scores. | main program |
rules() | 93โ97 | Shows how to play. | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: TIC - TAC - TOE (+1 more lines)
- You type 4 at Enter choice:runs:
rules()โshow()shows: Get three of your marks in a row, column or diagonal. (+7 more lines) - You type 1 at Enter choice:
- You type Rahul at Player X name:
- You type Priya at Player O name:runs:
play()โshow()โread_move()shows: 1 | 2 | 3 (+4 more lines) - You type 1 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: X | 2 | 3 (+4 more lines) - You type 5 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: X | 2 | 3 (+4 more lines) - You type 2 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: X | X | 3 (+4 more lines) - You type 5 at Priya (O), choose cell (1-9):shows: Cell already taken!
- You type 9 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: X | X | 3 (+4 more lines) - You type 10 at Rahul (X), choose cell (1-9):shows: Enter 1-9.
- You type 3 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โrecord()shows: X | X | X (+7 more lines) - You type 1 at Enter choice:
- You type Rahul at Player X name:
- You type Priya at Player O name:runs:
play()โshow()โread_move()shows: 1 | 2 | 3 (+4 more lines) - You type 5 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: 1 | 2 | 3 (+4 more lines) - You type 1 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | 2 | 3 (+4 more lines) - You type 9 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | 2 | 3 (+4 more lines) - You type 3 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | 2 | O (+4 more lines) - You type 2 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | X | O (+4 more lines) - You type 8 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | X | O (+4 more lines) - You type 4 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | X | O (+4 more lines) - You type 6 at Priya (O), choose cell (1-9):runs:
winner()โshow()โread_move()shows: O | X | O (+4 more lines) - You type 7 at Rahul (X), choose cell (1-9):runs:
winner()โshow()โrecord()shows: O | X | O (+6 more lines) - You type 2 at Enter choice:
- You type Anu at Your name:runs:
play()โshow()โread_move()shows: 1 | 2 | 3 (+4 more lines) - 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) - 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) - 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) - You type 7 at Enter choice:shows: Invalid choice (+1 more lines)
- You type 3 at Enter choice:runs:
score_board()shows: SCORE BOARD (+4 more lines) - You type 5 at Enter choice:shows: Scores reset. (+1 more lines)
- You type 3 at Enter choice:runs:
score_board()shows: SCORE BOARD (+2 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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'.
Hangman Word Game
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
WORDS | dict of list | Category -> list of (word, hint) tuples |
STAGES | list of str | Hangman drawings for 0 to 6 wrong guesses |
guessed | set | Letters guessed in the current game |
history | list of tuple | (word, result, score) of each game |
lives | int | Remaining lives (starts at 6) |
# =====================================================================
# 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"))()
==================================================
H A N G M A N
==================================================
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 5
Guess the hidden word one letter at a time. You have 6 lives.
Each wrong letter or hint costs a life. Type the full word to win at once.
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 1
1.Computer 2.Science 3.Geography
Category: 1
Category: Computer | The word has 8 letters.
Word : _ _ _ _ _ _ _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': e
Good guess! e appears 1 time(s)
Word : _ e _ _ _ _ _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': a
Good guess! a appears 1 time(s)
Word : _ e _ _ _ a _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': ab
Enter one letter or the full word.
Word : _ e _ _ _ a _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': o
Good guess! o appears 1 time(s)
Word : _ e _ _ o a _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': e
Already guessed e
Word : _ e _ _ o a _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': r
Good guess! r appears 1 time(s)
Word : _ e _ _ o a r _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': k
Good guess! k appears 1 time(s)
Word : k e _ _ o a r _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': y
Good guess! y appears 1 time(s)
Word : k e y _ o a r _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': b
Good guess! b appears 1 time(s)
Word : k e y b o a r _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': d
Good guess! d appears 1 time(s)
Word: KEYBOARD - YOU WIN! Score: 68
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 1
1.Computer 2.Science 3.Geography
Category: 2
Category: Science | The word has 7 letters.
Word : _ _ _ _ _ _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': hint
Hint: Force that pulls objects down (1 life used)
O
Word : _ _ _ _ _ _ _
Lives: <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': o
Wrong guess!
O
|
Word : _ _ _ _ _ _ _
Lives: <3 <3 <3 <3 | Wrong: o
Guess a letter / the word / 'hint': n
Wrong guess!
O
/|
Word : _ _ _ _ _ _ _
Lives: <3 <3 <3 | Wrong: o n
Guess a letter / the word / 'hint': z
Wrong guess!
O
/|\
Word : _ _ _ _ _ _ _
Lives: <3 <3 | Wrong: o n z
Guess a letter / the word / 'hint': x
Wrong guess!
O
/|\
/
Word : _ _ _ _ _ _ _
Lives: <3 | Wrong: o n z x
Guess a letter / the word / 'hint': q
Wrong guess!
O
/|\
/ \
GAME OVER! The word was: GRAVITY
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 4
Category: Science
New word: atom
Hint : Smallest unit of an element
Added to Science - words now: 4
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 1
1.Computer 2.Science 3.Geography
Category: 3
Category: Geography | The word has 6 letters.
Word : _ _ _ _ _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': c
Good guess! c appears 2 time(s)
Word : _ _ c c _ _
Lives: <3 <3 <3 <3 <3 <3 | Wrong: -
Guess a letter / the word / 'hint': x
Wrong guess!
O
Word : _ _ c c _ _
Lives: <3 <3 <3 <3 <3 | Wrong: x
Guess a letter / the word / 'hint': deccan
Word: DECCAN - YOU WIN! Score: 56
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 2
Games played: 3 | Won: 2 | Lost: 1
Win percentage: 66.7% | Best score: 68
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 3
1. keyboard Won 68
2. gravity Lost 0
3. deccan Won 56
1.Play 2.Statistics 3.History 4.Add Word 5.Rules 0.Exit
Enter choice: 0
Games played: 3 | Won: 2 | Lost: 1
Win percentage: 66.7% | Best score: 68
Bye! Keep learning new words.
- Start
- Display menu and read choice
- Choice is Play? → No: show stats / history / add word
- Choose category; computer picks a random word
- Show drawing, masked word and read guess
- Guess correct? → No: lose a life
- Word complete or lives = 0? → No: read next guess
- Calculate score and save history
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Correct letter | Letter revealed in the word | PASS |
| 2 | Wrong letter | Life reduced and drawing grows | PASS |
| 3 | Same letter twice | 'Already guessed' - no life lost | PASS |
| 4 | Input '7' or 'ab' | 'Enter one letter or the full word' | PASS |
| 5 | Ask hint | Hint shown, one life deducted | PASS |
| 6 | Whole word typed correctly | Game won immediately | PASS |
| 7 | Lives become 0 | Game over and word revealed | PASS |
| 8 | Statistics | Win % and best score correct | PASS |
โ 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
- Imports (line 6):
random- random number functions are loaded. - Global variables / constants are created:
WORDS,STAGES,history. - 5 functions are defined (lines 18โ93) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
play() | 18โ58 | Plays one game and stores the result. | main program (menu) |
statistics() | 61โ67 | Games played, won, lost and best score. | main program (menu), main program |
show_history() | 70โ75 | Shows every game played. | main program (menu) |
add_word() | 78โ87 | Adds a new word and hint. | main program (menu) |
rules() | 90โ93 | How to play. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: H A N G M A N (+1 more lines)
- 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) - You type 1 at Enter choice:runs:
play()shows: 1.Computer 2.Science 3.Geography - You type 1 at Category:shows: Category: Computer | The word has 8 letters. (+2 more lines)
- You type e at Guess a letter / the word / 'hint':shows: Good guess! e appears 1 time(s) (+2 more lines)
- You type a at Guess a letter / the word / 'hint':shows: Good guess! a appears 1 time(s) (+2 more lines)
- You type ab at Guess a letter / the word / 'hint':shows: Enter one letter or the full word. (+2 more lines)
- You type o at Guess a letter / the word / 'hint':shows: Good guess! o appears 1 time(s) (+2 more lines)
- You type e at Guess a letter / the word / 'hint':shows: Already guessed e (+2 more lines)
- You type r at Guess a letter / the word / 'hint':shows: Good guess! r appears 1 time(s) (+2 more lines)
- You type k at Guess a letter / the word / 'hint':shows: Good guess! k appears 1 time(s) (+2 more lines)
- You type y at Guess a letter / the word / 'hint':shows: Good guess! y appears 1 time(s) (+2 more lines)
- You type b at Guess a letter / the word / 'hint':shows: Good guess! b appears 1 time(s) (+2 more lines)
- You type d at Guess a letter / the word / 'hint':shows: Good guess! d appears 1 time(s) (+2 more lines)
- You type 1 at Enter choice:runs:
play()shows: 1.Computer 2.Science 3.Geography - You type 2 at Category:shows: Category: Science | The word has 7 letters. (+2 more lines)
- You type hint at Guess a letter / the word / 'hint':shows: Hint: Force that pulls objects down (1 life used) (+3 more lines)
- You type o at Guess a letter / the word / 'hint':shows: Wrong guess! (+4 more lines)
- You type n at Guess a letter / the word / 'hint':shows: Wrong guess! (+4 more lines)
- You type z at Guess a letter / the word / 'hint':shows: Wrong guess! (+4 more lines)
- You type x at Guess a letter / the word / 'hint':shows: Wrong guess! (+5 more lines)
- You type q at Guess a letter / the word / 'hint':shows: Wrong guess! (+5 more lines)
- You type 4 at Enter choice:runs:
add_word() - You type Science at Category:
- You type atom at New word:
- You type Smallest unit of an element at Hint :shows: Added to Science - words now: 4 (+1 more lines)
- You type 1 at Enter choice:runs:
play()shows: 1.Computer 2.Science 3.Geography - You type 3 at Category:shows: Category: Geography | The word has 6 letters. (+2 more lines)
- You type c at Guess a letter / the word / 'hint':shows: Good guess! c appears 2 time(s) (+2 more lines)
- You type x at Guess a letter / the word / 'hint':shows: Wrong guess! (+3 more lines)
- You type deccan at Guess a letter / the word / 'hint':shows: Word: DECCAN - YOU WIN! Score: 56 (+1 more lines)
- You type 2 at Enter choice:runs:
statistics()shows: Games played: 3 | Won: 2 | Lost: 1 (+2 more lines) - You type 3 at Enter choice:runs:
show_history()shows: 1. keyboard Won 68 (+3 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Student Attendance Register
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
๐ฏ Objectives
- Store lists inside a dictionary
- Compute percentage with count() and formatted output
- Validate P/A entries with a while loop
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
register | dict | Roll no -> {'name': str, 'marks': list of 'P'/'A'/'L'} |
days | list of str | Dates / day labels marked so far |
CODES | dict | 'P' Present, 'A' Absent, 'L' Leave |
LIMIT | int | Minimum attendance percentage - 75 |
# =====================================================================
# 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"))()
==================================================
CLASS XI-A ATTENDANCE REGISTER
==================================================
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 1
Day / date label: Mon
1. Aman (P/A/L): P
2. Bhavna (P/A/L): P
3. Chirag (P/A/L): A
4. Deepa (P/A/L): P
5. Eshan (P/A/L): P
6. Farah (P/A/L): P
Attendance saved for Mon - present: 5
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 1
Day / date label: Tue
1. Aman (P/A/L): P
2. Bhavna (P/A/L): A
3. Chirag (P/A/L): A
4. Deepa (P/A/L): P
5. Eshan (P/A/L): X
Enter P, A or L.
5. Eshan (P/A/L): L
6. Farah (P/A/L): P
Attendance saved for Tue - present: 3
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 1
Day / date label: Wed
1. Aman (P/A/L): P
2. Bhavna (P/A/L): P
3. Chirag (P/A/L): A
4. Deepa (P/A/L): P
5. Eshan (P/A/L): P
6. Farah (P/A/L): A
Attendance saved for Wed - present: 4
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 1
Day / date label: Thu
1. Aman (P/A/L): P
2. Bhavna (P/A/L): A
3. Chirag (P/A/L): A
4. Deepa (P/A/L): P
5. Eshan (P/A/L): P
6. Farah (P/A/L): P
Attendance saved for Thu - present: 4
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 1
Day / date label: Fri
1. Aman (P/A/L): A
2. Bhavna (P/A/L): P
3. Chirag (P/A/L): P
4. Deepa (P/A/L): P
5. Eshan (P/A/L): P
6. Farah (P/A/L): A
Attendance saved for Fri - present: 4
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 2
Roll Name P A L % Status
------------------------------------------
1 Aman 4 1 0 80.0% OK
2 Bhavna 3 2 0 60.0% SHORTAGE
3 Chirag 1 4 0 20.0% SHORTAGE
4 Deepa 5 0 0 100.0% OK
5 Eshan 4 0 1 100.0% OK
6 Farah 3 2 0 60.0% SHORTAGE
Days marked: 5 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 3
Mon 5/6 ###############
Tue 3/6 #########
Wed 4/6 ############
Thu 4/6 ############
Fri 4/6 ############
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 4
Roll 2 Bhavna 60.0% -> needs 75% ; inform parents
Roll 3 Chirag 20.0% -> needs 75% ; inform parents
Roll 6 Farah 60.0% -> needs 75% ; inform parents
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 5
ALERT: Roll 3 Chirag was absent 3 days in a row!
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 6
Roll number: 3
Chirag : Mon-A Tue-A Wed-A Thu-A Fri-P
Attendance 20.0%
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 7
Roll number: 3
Day number (1-5): 2
Correct mark (P/A/L): P
Updated: Chirag Tue -> Present
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 6
Roll number: 3
Chirag : Mon-A Tue-P Wed-A Thu-A Fri-P
Attendance 40.0%
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 6
Roll number: 9
Roll number not found.
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 8
Name: Kavya
Kavya added with roll number 7 (attendance starts from the next day)
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 2
Roll Name P A L % Status
------------------------------------------
1 Aman 4 1 0 80.0% OK
2 Bhavna 3 2 0 60.0% SHORTAGE
3 Chirag 2 3 0 40.0% SHORTAGE
4 Deepa 5 0 0 100.0% OK
5 Eshan 4 0 1 100.0% OK
6 Farah 3 2 0 60.0% SHORTAGE
7 Kavya 0 0 0 0.0% SHORTAGE
Days marked: 5 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
1.Mark 2.Student Report 3.Day Report 4.Defaulters 5.Alert
6.Search 7.Edit 8.Add Student 0.Exit
Enter choice: 0
Register closed. Total days: 5
- Start
- Load class register
- Display menu and read choice
- Choice is Mark Attendance? → No: run selected report
- Read day label and P/A/L for each student
- Code valid? → No: ask again
- Append mark to each student's list
- Reports - % = (P + L) / days x 100
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Mark day with code 'X' | 'Enter P, A or L' and asked again | PASS |
| 2 | Student present 4 of 5 days | 80.0 % - OK | PASS |
| 3 | Student present 2 of 5 | 40.0 % - SHORTAGE | PASS |
| 4 | Leave days | Counted as attended in % | PASS |
| 5 | 3 consecutive A | Alert printed for the student | PASS |
| 6 | Day-wise report | Presents per day with bar chart | PASS |
| 7 | Edit roll 3 day 2 to P | Record and % updated | PASS |
| 8 | Search 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
- Global variables / constants are created:
CODES,LIMIT,register,days. - 9 functions are defined (lines 15โ107) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
pct(marks) | 15โ17 | Attendance % - leave counts as attended. | student_report(), defaulters(), search() |
mark_attendance() | 20โ32 | Marks P / A / L for a new day. | main program (menu) |
student_report() | 35โ43 | Report of all students. | main program (menu) |
day_report() | 46โ50 | Presents per day. | main program (menu) |
defaulters() | 53โ59 | Students below the limit. | main program (menu) |
absence_alert() | 62โ70 | 3 consecutive absences. | main program (menu) |
search() | 73โ85 | Record of one student. | main program (menu) |
edit_entry() | 88โ99 | Corrects one entry. | main program (menu) |
add_student() | 102โ107 | Adds a student to the register. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CLASS XI-A ATTENDANCE REGISTER (+2 more lines)
- You type 1 at Enter choice:runs:
mark_attendance() - You type Mon at Day / date label:
- You type P at 1. Aman (P/A/L):
- You type P at 2. Bhavna (P/A/L):
- You type A at 3. Chirag (P/A/L):
- You type P at 4. Deepa (P/A/L):
- You type P at 5. Eshan (P/A/L):
- You type P at 6. Farah (P/A/L):shows: Attendance saved for Mon - present: 5 (+2 more lines)
- You type 1 at Enter choice:runs:
mark_attendance() - You type Tue at Day / date label:
- You type P at 1. Aman (P/A/L):
- You type A at 2. Bhavna (P/A/L):
- You type A at 3. Chirag (P/A/L):
- You type P at 4. Deepa (P/A/L):
- You type X at 5. Eshan (P/A/L):shows: Enter P, A or L.
- You type L at 5. Eshan (P/A/L):
- You type P at 6. Farah (P/A/L):shows: Attendance saved for Tue - present: 3 (+2 more lines)
- You type 1 at Enter choice:runs:
mark_attendance() - You type Wed at Day / date label:
- You type P at 1. Aman (P/A/L):
- You type P at 2. Bhavna (P/A/L):
- You type A at 3. Chirag (P/A/L):
- You type P at 4. Deepa (P/A/L):
- You type P at 5. Eshan (P/A/L):
- You type A at 6. Farah (P/A/L):shows: Attendance saved for Wed - present: 4 (+2 more lines)
- You type 1 at Enter choice:runs:
mark_attendance() - You type Thu at Day / date label:
- You type P at 1. Aman (P/A/L):
- You type A at 2. Bhavna (P/A/L):
- You type A at 3. Chirag (P/A/L):
- You type P at 4. Deepa (P/A/L):
- You type P at 5. Eshan (P/A/L):
- You type P at 6. Farah (P/A/L):shows: Attendance saved for Thu - present: 4 (+2 more lines)
- You type 1 at Enter choice:runs:
mark_attendance() - You type Fri at Day / date label:
- You type A at 1. Aman (P/A/L):
- You type P at 2. Bhavna (P/A/L):
- You type P at 3. Chirag (P/A/L):
- 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Password Strength Checker & Generator
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
๐ฏ Objectives
- Apply string methods like isupper(), isdigit(), isalnum()
- Return multiple values from a function
- Generate random strings with random.choice() and shuffle()
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
COMMON | set | Very common weak passwords (123456, password ...) |
LOWER / UPPER / DIGITS / SYMBOLS | str | Character groups used for checking and generating |
WORDS | list | Simple words used in passphrases |
score | int | Strength score from 0 to 10 |
# =====================================================================
# 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")
========================================================
PASSWORD STRENGTH CHECKER & GENERATOR
========================================================
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 1
Enter password: password
password [..........] 0/10 VERY WEAK (common password)
Tip: Never use common passwords.
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 1
Enter password: Kv@2026School
Kv@2026School [##########] 10/10 VERY STRONG
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 1
Enter password: aaaaaaa1
aaaaaaa1 [##........] 2/10 WEAK
Tip: Add at least one uppercase letter
Tip: Add at least one symbol
Tip: Avoid repeating the same character
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 2
Length (min 8): 12
Include symbols? (Y/N): Y
Generated: 1_8C_E-n4K@d
1_8C_E-n4K@d [##########] 10/10 VERY STRONG
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 2
Length (min 8): 4
Include symbols? (Y/N): N
Generated: zKw3vqw7
zKw3vqw7 [######....] 6/10 MEDIUM
Tip: Add at least one symbol
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 3
Passphrase: Pixel-Ocean-28$
Pixel-Ocean-28$ [##########] 10/10 VERY STRONG
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 4
Password: abc123
Time to crack by brute force: less than a second
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 4
Password: Kv@2026School
Time to crack by brute force: about 4,431,143.8 years
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 5
Password: kv2026
[FAIL] At least 8 characters
[FAIL] One capital letter
[PASS] One digit
[FAIL] One symbol
[PASS] No spaces
Policy result: REJECTED
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 6
Passwords (comma separated): india123,Delhi@2026,qwerty,T!ger_Run9
india123 [..........] 0/10 VERY WEAK (common password)
Tip: Never use common passwords.
Delhi@2026 [########..] 8/10 STRONG
qwerty [..........] 0/10 VERY WEAK (common password)
Tip: Never use common passwords.
T!ger_Run9 [########..] 8/10 STRONG
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 7
* 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.
1.Check 2.Generate 3.Passphrase 4.Crack Time 5.Policy 6.Bulk 7.Tips 0.Exit
Enter choice: 0
Stay safe online!
- Start
- Display menu and read choice
- Choice is Check? → No: generate / estimate / policy / tips
- Read password
- Score length, cases, digits, symbols; penalise repeats and common words
- Show level, bar and tips
- Generate random password / passphrase when chosen
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | 'password' | Common password - VERY WEAK | PASS |
| 2 | 'Kv@2026School' | Score 10/10 - VERY STRONG | PASS |
| 3 | 'aaaaaaa1' | Repeated characters penalty | PASS |
| 4 | Generate length 12 | 12-character password with all groups | PASS |
| 5 | Generate length 4 | Length raised to the minimum 8 | PASS |
| 6 | Passphrase | Word-Word-Number pattern | PASS |
| 7 | Crack time of 'abc123' | Seconds or less | PASS |
| 8 | Policy check 'kv2026' | Lists the rules that fail | PASS |
โ 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
- Imports (line 6):
random- random number functions are loaded. - Global variables / constants are created:
LOWER,UPPER,DIGITS,SYMBOLS,COMMON,WORDS. - 6 functions are defined (lines 16โ80) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
check(pw) | 16โ34 | Returns score (0-10), level and tips. | show_check() |
show_check(pw) | 37โ42 | Prints the result of check(). | main program |
generate(n, symbols) | 45โ54 | Random password with every character group. | main program |
passphrase() | 57โ60 | Word-Word-Number passphrase. | main program |
crack_time(pw) | 63โ70 | Approximate brute-force time. | main program |
policy(pw) | 73โ80 | School account policy. | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: PASSWORD STRENGTH CHECKER & GENERATOR (+1 more lines)
- You type 1 at Enter choice:
- You type password at Enter password:runs:
show_check()โcheck()shows: password [..........] 0/10 VERY WEAK (common password) (+2 more lines) - You type 1 at Enter choice:
- You type Kv@2026School at Enter password:runs:
show_check()โcheck()shows: Kv@2026School [##########] 10/10 VERY STRONG (+1 more lines) - You type 1 at Enter choice:
- You type aaaaaaa1 at Enter password:runs:
show_check()โcheck()shows: aaaaaaa1 [##........] 2/10 WEAK (+4 more lines) - You type 2 at Enter choice:
- You type 12 at Length (min 8):
- You type Y at Include symbols? (Y/N):runs:
generate()โshow_check()โcheck()shows: Generated: 1_8C_E-n4K@d (+2 more lines) - You type 2 at Enter choice:
- You type 4 at Length (min 8):
- You type N at Include symbols? (Y/N):runs:
generate()โshow_check()โcheck()shows: Generated: zKw3vqw7 (+3 more lines) - You type 3 at Enter choice:runs:
passphrase()โshow_check()โcheck()shows: Passphrase: Pixel-Ocean-28$ (+2 more lines) - You type 4 at Enter choice:
- You type abc123 at Password:runs:
crack_time()shows: Time to crack by brute force: less than a second (+1 more lines) - You type 4 at Enter choice:
- 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) - You type 5 at Enter choice:
- You type kv2026 at Password:runs:
policy()shows: [FAIL] At least 8 characters (+6 more lines) - You type 6 at Enter choice:
- 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) - You type 7 at Enter choice:shows: * Use a different password for every account. (+5 more lines)
- You type 0 at Enter choice:shows: Stay safe online!
โค Inside each function - line by line
check() - lines 16โ34
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Loan/EMI Comparison Calculator
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
emi | float | Monthly instalment = P x r x (1+r)^n / ((1+r)^n - 1) |
banks | dict | Bank name -> (rate, years, emi, total) |
r | float | Monthly interest rate = annual rate / 1200 |
n | int | Number of monthly instalments = years x 12 |
# =====================================================================
# 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"))()
==================================================
LOAN / EMI COMPARISON CALCULATOR
==================================================
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 1
Loan amount (Rs.): 500000
Annual interest rate (%): 8.5
Tenure (years): 5
Monthly EMI : Rs. 10,258.27
Total interest : Rs. 115,495.94
Total payment : Rs. 615,495.94
Interest share : 18.8% of the total payment
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 2
Loan amount (Rs.): 500000
How many banks? 3
Bank 1 name: SBI
Rate (%) : 8.5
Tenure (yrs) : 5
Bank 2 name: HDFC
Rate (%) : 9.1
Tenure (yrs) : 5
Bank 3 name: PNB
Rate (%) : 8.25
Tenure (yrs) : 6
Bank Rate Years EMI Total cost
----------------------------------------------
SBI 8.5 5 10,258.27 615,495.94
HDFC 9.1 5 10,403.46 624,207.66
PNB 8.25 6 8,827.78 635,600.20
Lowest total cost : SBI
Lowest monthly EMI: PNB (longer tenure may cost more)
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 3
Loan amount (Rs.): 500000
Rate (%): 8.5
Tenure (years): 5
EMI Rs. 10,258.27
Year Interest Principal Balance
1 39,285 83,815 416,185
2 31,876 91,223 324,962
3 23,813 99,286 225,676
4 15,037 108,062 117,614
5 5,485 117,614 0
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 4
Monthly income (Rs.): 30000
EMI (Rs.): 10258.27
EMI is 34.2% of income.
AFFORDABLE
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 4
Monthly income (Rs.): 20000
EMI (Rs.): 10258.27
EMI is 51.3% of income.
NOT AFFORDABLE - reduce loan or increase tenure
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 5
Loan amount: 500000
Rate (%): 8.5
Tenure (years): 5
Prepay after how many years: 2
Prepayment amount: 100000
Loan closes 12 months earlier.
Interest saved: Rs. 23,099.19
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 6
EMI you can pay (Rs.): 12000
Rate (%): 9
Tenure (years): 5
You are eligible for a loan of about Rs. 578,080
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 1
Loan amount (Rs.): abc
Enter a valid number.
1.EMI 2.Compare 3.Schedule 4.Affordable? 5.Prepay 6.Eligibility 0.Exit
Enter choice: 0
Borrow wisely!
- Start
- Display menu and read choice
- Choice is Compare? → No: run the selected calculator
- Read loan amount and number of banks
- Read bank name, rate and tenure for each bank
- EMI and total payment for every bank
- Best bank = minimum total payment
- Display comparison table and recommendation
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | P = 500000, 8.5 %, 5 years | EMI Rs. 10258.27 | PASS |
| 2 | Rate 0 % | EMI = P / n (no interest) | PASS |
| 3 | Compare 3 banks | Lowest total cost recommended | PASS |
| 4 | Schedule for 5 years | Balance becomes 0 in year 5 | PASS |
| 5 | Income 30000, EMI 10258 | Affordable (34.2 %) | PASS |
| 6 | Income 20000, EMI 10258 | Not affordable warning | PASS |
| 7 | Prepay 100000 after 2 years | Interest saved shown | PASS |
| 8 | Amount '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
- 8 functions are defined (lines 8โ119) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_num(msg) | 8โ15 | Reads a positive number; returns None if invalid. | single_emi(), compare_banks(), schedule(), affordability() |
calc_emi(p, rate, years) | 18โ23 | EMI by the reducing-balance formula. | single_emi(), compare_banks(), schedule(), prepayment() |
single_emi() | 26โ38 | EMI, interest and total of one loan. | main program (menu) |
compare_banks() | 41โ59 | Compares several banks. | main program (menu) |
schedule() | 62โ77 | Year-wise amortisation schedule. | main program (menu) |
affordability() | 80โ86 | EMI should be at most 40 % of income. | main program (menu) |
prepayment() | 89โ109 | Interest saved by a part payment. | main program (menu) |
eligibility() | 112โ119 | Maximum loan for an affordable EMI. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: LOAN / EMI COMPARISON CALCULATOR (+1 more lines)
- You type 1 at Enter choice:runs:
single_emi()โread_num() - You type 500000 at Loan amount (Rs.):runs:
read_num() - You type 8.5 at Annual interest rate (%):runs:
read_num() - You type 5 at Tenure (years):runs:
calc_emi()shows: Monthly EMI : Rs. 10,258.27 (+4 more lines) - You type 2 at Enter choice:runs:
compare_banks()โread_num() - You type 500000 at Loan amount (Rs.):runs:
read_num() - You type 3 at How many banks?
- You type SBI at Bank 1 name:runs:
read_num() - You type 8.5 at Rate (%) :runs:
read_num() - You type 5 at Tenure (yrs) :runs:
calc_emi() - You type HDFC at Bank 2 name:runs:
read_num() - You type 9.1 at Rate (%) :runs:
read_num() - You type 5 at Tenure (yrs) :runs:
calc_emi() - You type PNB at Bank 3 name:runs:
read_num() - You type 8.25 at Rate (%) :runs:
read_num() - You type 6 at Tenure (yrs) :runs:
calc_emi()shows: Bank Rate Years EMI Total cost (+6 more lines) - You type 3 at Enter choice:runs:
schedule()โread_num() - You type 500000 at Loan amount (Rs.):runs:
read_num() - You type 8.5 at Rate (%):runs:
read_num() - You type 5 at Tenure (years):runs:
calc_emi()shows: EMI Rs. 10,258.27 (+7 more lines) - You type 4 at Enter choice:runs:
affordability()โread_num() - You type 30000 at Monthly income (Rs.):runs:
read_num() - You type 10258.27 at EMI (Rs.):shows: EMI is 34.2% of income. (+2 more lines)
- You type 4 at Enter choice:runs:
affordability()โread_num() - You type 20000 at Monthly income (Rs.):runs:
read_num() - You type 10258.27 at EMI (Rs.):shows: EMI is 51.3% of income. (+2 more lines)
- You type 5 at Enter choice:runs:
prepayment()โread_num() - You type 500000 at Loan amount:runs:
read_num() - You type 8.5 at Rate (%):runs:
read_num() - You type 5 at Tenure (years):runs:
read_num() - You type 2 at Prepay after how many years:runs:
read_num() - You type 100000 at Prepayment amount:runs:
calc_emi()shows: Loan closes 12 months earlier. (+2 more lines) - You type 6 at Enter choice:runs:
eligibility()โread_num() - You type 12000 at EMI you can pay (Rs.):runs:
read_num() - You type 9 at Rate (%):runs:
read_num() - You type 5 at Tenure (years):shows: You are eligible for a loan of about Rs. 578,080 (+1 more lines)
- You type 1 at Enter choice:runs:
single_emi()โread_num() - You type abc at Loan amount (Rs.):shows: Enter a valid number. (+1 more lines)
- You type 0 at Enter choice:shows: Borrow wisely!
โค Inside each function - line by line
read_num() - lines 8โ15
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Shop Billing & GST Calculator
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
๐ฏ Objectives
- Use lists of tuples to store bill items
- Apply percentage and tax calculations
- Format tabular output using f-strings
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
catalogue | dict | Code -> [name, price, gst %, stock] |
cart | dict | Code -> quantity in the current bill |
sales | list of tuple | (invoice no, customer, amount, gst) of each bill |
DISCOUNT_LIMIT | int | Bills above Rs. 2000 get 5 % discount |
# =====================================================================
# 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"))()
==============================================================
SHOP BILLING & GST CALCULATOR
==============================================================
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 1
Code Item Price GST% Stock
-------------------------------------------------
101 Notebook (pack of 6) 240.00 12 30
102 Geometry Box 180.00 18 12
103 Ball Pen (box) 120.00 18 6
104 School Bag 1450.00 18 8
105 Water Bottle 350.00 12 4
106 Story Book 199.00 0 15
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 101
Quantity : 3
Added 3 x Notebook (pack of 6)
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 104
Quantity : 1
Added 1 x School Bag
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 999
Quantity : 2
Item not found.
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 103
Invalid choice
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 50
Invalid choice
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 103
Quantity : 3
Added 3 x Ball Pen (box)
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 3
101 Notebook (pack of 6) x 3 = Rs. 720.00
104 School Bag x 1 = Rs. 1450.00
103 Ball Pen (box) x 3 = Rs. 360.00
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 4
Code to remove: 103
Removed.
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 5
Customer name: Neha Gupta
==============================================================
KV STATIONERY MART - TAX INVOICE
Invoice No: 1001 Customer: Neha Gupta
==============================================================
Item Qty Rate Amount GST% GST
Notebook (pack of 6) 3 240.00 720.00 12 86.40
School Bag 1 1450.00 1450.00 18 261.00
--------------------------------------------------------------
Sub-total 2170.00
Discount 5% (bill above Rs. 2000) -108.50
CGST 165.01
SGST 165.01
Round off 0.47
NET PAYABLE 2392.00
==============================================================
LOW STOCK: Water Bottle - only 4 left
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 102
Quantity : 1
Added 1 x Geometry Box
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 2
Item code: 105
Quantity : 4
Added 4 x Water Bottle
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 5
Customer name: Arjun
==============================================================
KV STATIONERY MART - TAX INVOICE
Invoice No: 1002 Customer: Arjun
==============================================================
Item Qty Rate Amount GST% GST
Geometry Box 1 180.00 180.00 18 32.40
Water Bottle 4 350.00 1400.00 12 168.00
--------------------------------------------------------------
Sub-total 1580.00
CGST 100.20
SGST 100.20
Round off -0.40
NET PAYABLE 1780.00
==============================================================
LOW STOCK: Water Bottle - only 0 left
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 5
Cart is empty.
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: X
Invalid choice
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 6
Bill 1001 Neha Gupta Rs. 2392 (GST 330.03)
Bill 1002 Arjun Rs. 1780 (GST 200.40)
Bills: 2 | Sales: Rs. 4172 | GST collected: Rs. 530.43
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 7
LOW STOCK: Water Bottle - only 0 left
1.Catalogue 2.Add 3.Cart 4.Remove 5.Invoice 6.Summary 7.Low Stock 0.Exit
Enter choice: 0
Bill 1001 Neha Gupta Rs. 2392 (GST 330.03)
Bill 1002 Arjun Rs. 1780 (GST 200.40)
Bills: 2 | Sales: Rs. 4172 | GST collected: Rs. 530.43
Shop closed.
- Start
- Display menu and read choice
- Choice is Add to cart? → No: run selected option
- Read item code and quantity
- Code exists and stock enough? → No: show message
- Add to cart
- Invoice - amount, GST (CGST/SGST), discount, round off
- Reduce stock and save sale
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add code 101 qty 2 | Added to cart | PASS |
| 2 | Code 999 | 'Item not found' | PASS |
| 3 | Qty more than stock | 'Only n in stock' | PASS |
| 4 | Invoice of Rs. 2400 | 5 % discount applied | PASS |
| 5 | GST 18 % on Rs. 1000 | CGST 90 + SGST 90 | PASS |
| 6 | Remove item from cart | Item removed | PASS |
| 7 | Invoice with empty cart | 'Cart is empty' | PASS |
| 8 | Sales summary | Bills, sales and GST totals | PASS |
โ 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
- Global variables / constants are created:
catalogue,cart,sales,bill_no. - 7 functions are defined (lines 15โ116) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
show_catalogue() | 15โ20 | Displays all items. | main program (menu) |
add_to_cart() | 23โ39 | Adds an item to the cart. | main program (menu) |
view_cart() | 42โ48 | Shows the cart. | main program (menu) |
remove_item() | 51โ57 | Removes an item from the cart. | main program (menu) |
invoice() | 60โ97 | Generates a GST invoice. | main program (menu) |
summary() | 100โ107 | Sales of the day. | main program (menu), main program |
low_stock() | 110โ116 | Items with stock below 5. | invoice(), main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: SHOP BILLING & GST CALCULATOR (+1 more lines)
- You type 1 at Enter choice:runs:
show_catalogue()shows: Code Item Price GST% Stock (+7 more lines) - You type 2 at Enter choice:runs:
add_to_cart() - You type 101 at Item code:
- You type 3 at Quantity :shows: Added 3 x Notebook (pack of 6) (+1 more lines)
- You type 2 at Enter choice:runs:
add_to_cart() - You type 104 at Item code:
- You type 1 at Quantity :shows: Added 1 x School Bag (+1 more lines)
- You type 2 at Enter choice:runs:
add_to_cart() - You type 999 at Item code:
- You type 2 at Quantity :shows: Item not found. (+1 more lines)
- You type 103 at Enter choice:shows: Invalid choice (+1 more lines)
- You type 50 at Enter choice:shows: Invalid choice (+1 more lines)
- You type 2 at Enter choice:runs:
add_to_cart() - You type 103 at Item code:
- You type 3 at Quantity :shows: Added 3 x Ball Pen (box) (+1 more lines)
- You type 3 at Enter choice:runs:
view_cart()shows: 101 Notebook (pack of 6) x 3 = Rs. 720.00 (+3 more lines) - You type 4 at Enter choice:runs:
remove_item() - You type 103 at Code to remove:shows: Removed. (+1 more lines)
- You type 5 at Enter choice:runs:
invoice() - You type Neha Gupta at Customer name:runs:
low_stock()shows: KV STATIONERY MART - TAX INVOICE (+12 more lines) - You type 2 at Enter choice:runs:
add_to_cart() - You type 102 at Item code:
- You type 1 at Quantity :shows: Added 1 x Geometry Box (+1 more lines)
- You type 2 at Enter choice:runs:
add_to_cart() - You type 105 at Item code:
- You type 4 at Quantity :shows: Added 4 x Water Bottle (+1 more lines)
- You type 5 at Enter choice:runs:
invoice() - You type Arjun at Customer name:runs:
low_stock()shows: KV STATIONERY MART - TAX INVOICE (+11 more lines) - You type 5 at Enter choice:runs:
invoice()shows: Cart is empty. (+1 more lines) - You type X at Enter choice:shows: Invalid choice (+1 more lines)
- You type 6 at Enter choice:runs:
summary()shows: Bill 1001 Neha Gupta Rs. 2392 (GST 330.03) (+3 more lines) - You type 7 at Enter choice:runs:
low_stock()shows: LOW STOCK: Water Bottle - only 0 left (+1 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Class Result Dictionary System
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
๐ฏ Objectives
- Use a dictionary whose values are lists
- Sort items with sorted() and a lambda key
- Search a record by key
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
class_data | dict | Name -> list of 5 marks |
SUBJECTS | list | Subject names |
statistics | module | mean() and median() functions |
# =====================================================================
# 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"))()
========================================================================
CLASS XI RESULT SYSTEM
========================================================================
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 1
Name: Zoya
English : 91
Maths : 88
IP : 94
Physics : 86
Economics : 90
Added Zoya
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 2
Name Engl Math IP Phys Econ Total % Gr Result
------------------------------------------------------------------------
Ravi 78 85 92 70 81 406 81.2 A2 PASS
Simran 88 79 95 84 90 436 87.2 A2 PASS
Kabir 65 58 72 61 69 325 65.0 B2 PASS
Meera 92 96 98 89 94 469 93.8 A1 PASS
Tanvi 55 32 64 48 59 258 51.6 C COMPARTMENT
Arjun 78 85 92 70 81 406 81.2 A2 PASS
Zoya 91 88 94 86 90 449 89.8 A2 PASS
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 3
Rank 1: Meera Total 469
Rank 2: Zoya Total 449
Rank 3: Simran Total 436
Rank 4: Ravi Total 406
Rank 4: Arjun Total 406
Rank 6: Kabir Total 325
Rank 7: Tanvi Total 258
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 4
Subject Mean Median High Low
English 78.1 78.0 92 55
Maths 74.7 85.0 96 32
IP 86.7 92.0 98 64
Physics 72.6 70.0 89 48
Economics 80.6 81.0 94 59
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 5
Student name: Ravi
Name Engl Math IP Phys Econ Total % Gr Result
------------------------------------------------------------------------
Ravi 78 85 92 70 81 406 81.2 A2 PASS
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 6
Student name: Zoya
Subject no (1-5): 2
New marks: 99
Updated. New total: 460.0
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 8
Cut-off %: 80
Merit list: Meera (93.8%), Zoya (92.0%), Simran (87.2%), Ravi (81.2%), Arjun (81.2%)
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 7
Student name: Mohan
Student not found.
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 9
Students 7 | Passed 6 | Pass % 85.7
A1 ###### 2
A2 ######### 3
B2 ### 1
C ### 1
Class average: 78.86 %
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 3
Rank 1: Meera Total 469
Rank 2: Zoya Total 460
Rank 3: Simran Total 436
Rank 4: Ravi Total 406
Rank 4: Arjun Total 406
Rank 6: Kabir Total 325
Rank 7: Tanvi Total 258
1.Add 2.Marksheet 3.Rank 4.Subject Stats 5.Search 6.Modify 7.Delete 8.Merit 9.Summary 0.Exit
Enter choice: 0
Bye!
- Start
- Load sample class data
- Display menu and read choice
- Choice is Add? → No: run selected report
- Read name and 5 marks
- Total, %, grade for reports
- Rank list sorted by total
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add 'Zoya' with marks | Record added | PASS |
| 2 | Mark sheet | Total, % and grade of all | PASS |
| 3 | Two students with equal total | Same rank given | PASS |
| 4 | Subject statistics | Mean and median per subject | PASS |
| 5 | Search 'Ravi' | Mark sheet shown | PASS |
| 6 | Modify Zoya Maths to 99 | Total recalculated | PASS |
| 7 | Merit list cut-off 80 | Only students >= 80 % | PASS |
| 8 | Delete 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
- Imports (line 6):
statistics- mean, median, mode functions are loaded. - Global variables / constants are created:
SUBJECTS,class_data. - 13 functions are defined (lines 14โ114) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
total(name) | 14โ15 | Total | percent(), mark_sheet(), rank_list(), modify() |
percent(name) | 18โ19 | Percent | mark_sheet(), merit_list(), class_summary() |
grade(p) | 22โ24 | Grade from percentage. | mark_sheet(), class_summary() |
result(name) | 27โ28 | Result | mark_sheet(), class_summary() |
add_student() | 31โ38 | Adds a student. | main program (menu) |
mark_sheet(names) | 41โ48 | Mark sheet of all (or given) students. | search(), main program (menu) |
rank_list() | 51โ59 | Ranks with ties. | main program (menu) |
subject_stats() | 62โ67 | Mean, median, highest, lowest. | main program (menu) |
search() | 70โ76 | One student's mark sheet. | main program (menu) |
modify() | 79โ87 | Modifies one subject's marks. | main program (menu) |
delete() | 90โ93 | Deletes a student. | main program (menu) |
merit_list() | 96โ100 | Students above a cut-off. | main program (menu) |
class_summary() | 103โ114 | Pass % and grade counts. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CLASS XI RESULT SYSTEM (+1 more lines)
- You type 1 at Enter choice:runs:
add_student() - You type Zoya at Name:
- You type 91 at English :
- You type 88 at Maths :
- You type 94 at IP :
- You type 86 at Physics :
- You type 90 at Economics :shows: Added Zoya (+1 more lines)
- 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) - You type 3 at Enter choice:runs:
rank_list()โtotal()ร28shows: Rank 1: Meera Total 469 (+7 more lines) - You type 4 at Enter choice:runs:
subject_stats()shows: Subject Mean Median High Low (+6 more lines) - You type 5 at Enter choice:runs:
search() - 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) - You type 6 at Enter choice:runs:
modify() - You type Zoya at Student name:
- You type 2 at Subject no (1-5):
- You type 99 at New marks:runs:
total()shows: Updated. New total: 460.0 (+1 more lines) - You type 8 at Enter choice:runs:
merit_list() - 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) - You type 7 at Enter choice:runs:
delete() - You type Mohan at Student name:shows: Student not found. (+1 more lines)
- 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) - You type 3 at Enter choice:runs:
rank_list()โtotal()ร28shows: Rank 1: Meera Total 469 (+7 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
total() - lines 14โ15
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
School Student Database (SQL)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
student | TABLE | student_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) |
activity | TABLE | act_id INT PK, student_id INT (refers student), club VARCHAR(20), position VARCHAR(15) DEFAULT 'Member' |
grade | CHAR(2) | Column added later with ALTER TABLE and filled by UPDATE |
-- =====================================================================
-- 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;
mysql> DROP DATABASE IF EXISTS kv_office;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE DATABASE kv_office;
Query OK, 1 row affected (0.00 sec)
mysql> USE kv_office;
Database changed
mysql> 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)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE activity (
-> act_id INT PRIMARY KEY,
-> student_id INT,
-> club VARCHAR(20),
-> position VARCHAR(15) DEFAULT 'Member'
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> DESC student;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| student_id | int | NO | PRI | NULL | |
| name | varchar(30) | NO | | NULL | |
| section | char(1) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| dob | date | YES | | NULL | |
| marks | decimal(5,2) | YES | | NULL | |
| city | varchar(20) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
mysql> 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');
Query OK, 15 rows affected (0.00 sec)
Records: 15 Duplicates: 0 Warnings: 0
mysql> 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');
Query OK, 10 rows affected (0.00 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> INSERT INTO activity (act_id, student_id, club) VALUES (11,4,'Literary'), (12,12,'Eco Club');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> INSERT INTO student VALUES (16,'Test','A','M','2009-01-01',105,'Delhi');
ERROR 3819 (HY000): Check constraint 'student_chk_1' is violated.
mysql> SELECT * FROM student;
+------------+--------+---------+--------+------------+-------+-----------+
| student_id | name | section | gender | dob | marks | city |
+------------+--------+---------+--------+------------+-------+-----------+
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi |
+------------+--------+---------+--------+------------+-------+-----------+
15 rows in set (0.00 sec)
mysql> SELECT name, marks FROM student ORDER BY marks DESC LIMIT 5;
+-------+-------+
| name | marks |
+-------+-------+
| Imran | 94.50 |
| Sara | 92.00 |
| Amit | 88.50 |
| Divya | 85.00 |
| Neha | 81.50 |
+-------+-------+
5 rows in set (0.00 sec)
mysql> SELECT DISTINCT city FROM student;
+-----------+
| city |
+-----------+
| Delhi |
| Noida |
| NULL |
| Gurugram |
| Faridabad |
+-----------+
5 rows in set (0.00 sec)
mysql> SELECT name AS Student, section AS Sec, marks AS Score FROM student WHERE section = 'B' ORDER BY name;
+---------+-----+-------+
| Student | Sec | Score |
+---------+-----+-------+
| Anita | B | 70.00 |
| Divya | B | 85.00 |
| Farhan | B | 58.50 |
| Priya | B | 78.00 |
| Sara | B | 92.00 |
+---------+-----+-------+
5 rows in set (0.00 sec)
mysql> SELECT name, dob FROM student WHERE MONTH(dob) = 7;
+--------+------------+
| name | dob |
+--------+------------+
| Amit | 2009-07-14 |
| Rahul | 2009-07-25 |
| Neha | 2009-07-30 |
| Farhan | 2009-07-03 |
+--------+------------+
4 rows in set (0.00 sec)
mysql> SELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;
+--------+-------+
| name | marks |
+--------+-------+
| Rahul | 65.50 |
| Priya | 78.00 |
| Anita | 70.00 |
| Tina | 66.00 |
| Gaurav | 73.50 |
+--------+-------+
5 rows in set (0.00 sec)
mysql> SELECT name, city FROM student WHERE city IN ('Noida','Gurugram');
+-------+----------+
| name | city |
+-------+----------+
| Sara | Noida |
| Karan | Gurugram |
| Pooja | Noida |
| Tina | Gurugram |
| Divya | Noida |
+-------+----------+
5 rows in set (0.00 sec)
mysql> SELECT name FROM student WHERE name LIKE '_a%';
+--------+
| name |
+--------+
| Sara |
| Rahul |
| Karan |
| Farhan |
| Gaurav |
| Harsh |
+--------+
6 rows in set (0.00 sec)
mysql> SELECT name, section FROM student WHERE city IS NULL;
+-------+---------+
| name | section |
+-------+---------+
| Priya | B |
| Vikas | C |
+-------+---------+
2 rows in set (0.00 sec)
mysql> SELECT name, marks FROM student WHERE marks < 40 OR (section = 'C' AND gender = 'F');
+-------+-------+
| name | marks |
+-------+-------+
| Karan | 35.00 |
| Neha | 81.50 |
| Vikas | 29.00 |
| Tina | 66.00 |
| Harsh | 39.50 |
+-------+-------+
5 rows in set (0.00 sec)
mysql> SELECT COUNT(*) AS Total, AVG(marks) AS Average, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student;
+-------+-----------+---------+--------+
| Total | Average | Highest | Lowest |
+-------+-----------+---------+--------+
| 15 | 66.900000 | 94.50 | 29.00 |
+-------+-----------+---------+--------+
1 row in set (0.00 sec)
mysql> SELECT section, COUNT(*) AS Strength FROM student GROUP BY section;
+---------+----------+
| section | Strength |
+---------+----------+
| A | 5 |
| B | 5 |
| C | 5 |
+---------+----------+
3 rows in set (0.00 sec)
mysql> SELECT section, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student GROUP BY section;
+---------+---------+--------+
| section | Highest | Lowest |
+---------+---------+--------+
| A | 88.50 | 35.00 |
| B | 92.00 | 58.50 |
| C | 94.50 | 29.00 |
+---------+---------+--------+
3 rows in set (0.00 sec)
mysql> SELECT gender, ROUND(AVG(marks),2) AS Avg_Marks FROM student GROUP BY gender;
+--------+-----------+
| gender | Avg_Marks |
+--------+-----------+
| F | 74.21 |
| M | 60.50 |
+--------+-----------+
2 rows in set (0.00 sec)
mysql> SELECT section, ROUND(AVG(marks),2) AS Average FROM student GROUP BY section HAVING AVG(marks) > 65;
+---------+---------+
| section | Average |
+---------+---------+
| B | 76.70 |
+---------+---------+
1 row in set (0.00 sec)
mysql> SELECT city, COUNT(*) AS Students FROM student WHERE city IS NOT NULL GROUP BY city ORDER BY Students DESC;
+-----------+----------+
| city | Students |
+-----------+----------+
| Delhi | 7 |
| Noida | 3 |
| Gurugram | 2 |
| Faridabad | 1 |
+-----------+----------+
4 rows in set (0.00 sec)
mysql> SELECT UPPER(name) AS Name, LENGTH(name) AS Letters, SUBSTR(name,1,3) AS Short FROM student WHERE section = 'A';
+--------+---------+-------+
| Name | Letters | Short |
+--------+---------+-------+
| AMIT | 4 | Ami |
| RAHUL | 5 | Rah |
| KARAN | 5 | Kar |
| POOJA | 5 | Poo |
| GAURAV | 6 | Gau |
+--------+---------+-------+
5 rows in set (0.00 sec)
mysql> SELECT CONCAT(name, ' (', section, ')') AS Student, ROUND(marks/100*500) AS Out_of_500 FROM student LIMIT 6;
+-----------+------------+
| Student | Out_of_500 |
+-----------+------------+
| Amit (A) | 443 |
| Sara (B) | 460 |
| Rahul (A) | 328 |
| Priya (B) | 390 |
| Karan (A) | 175 |
| Neha (C) | 408 |
+-----------+------------+
6 rows in set (0.00 sec)
mysql> SELECT name, YEAR(dob) AS Birth_Year, MONTHNAME(dob) AS Month FROM student WHERE YEAR(dob) = 2008;
+--------+------------+----------+
| name | Birth_Year | Month |
+--------+------------+----------+
| Vikas | 2008 | December |
| Gaurav | 2008 | August |
+--------+------------+----------+
2 rows in set (0.00 sec)
mysql> SELECT name, DATEDIFF('2026-04-01', dob) DIV 365 AS Age_on_1_April FROM student ORDER BY dob LIMIT 5;
+--------+----------------+
| name | Age_on_1_April |
+--------+----------------+
| Gaurav | 17 |
| Vikas | 17 |
| Karan | 17 |
| Pooja | 17 |
| Sara | 17 |
+--------+----------------+
5 rows in set (0.00 sec)
mysql> ALTER TABLE student ADD grade CHAR(2);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> UPDATE student SET grade = 'A1' WHERE marks >= 90;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> UPDATE student SET grade = 'A2' WHERE marks >= 75 AND marks < 90;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> UPDATE student SET grade = 'B' WHERE marks >= 60 AND marks < 75;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> UPDATE student SET grade = 'C' WHERE marks >= 40 AND marks < 60;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> UPDATE student SET grade = 'D' WHERE marks < 40;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> SELECT grade, COUNT(*) AS Students FROM student GROUP BY grade ORDER BY grade;
+-------+----------+
| grade | Students |
+-------+----------+
| A1 | 2 |
| A2 | 4 |
| B | 4 |
| C | 2 |
| D | 3 |
+-------+----------+
5 rows in set (0.00 sec)
mysql> UPDATE student SET city = 'Delhi' WHERE city IS NULL;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> DELETE FROM student WHERE student_id = 7;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT COUNT(*) AS Remaining FROM student;
+-----------+
| Remaining |
+-----------+
| 14 |
+-----------+
1 row in set (0.00 sec)
mysql> 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;
+--------+---------+----------+--------------+
| name | section | club | position |
+--------+---------+----------+--------------+
| Divya | B | Eco Club | Member |
| Sara | B | Eco Club | Secretary |
| Tina | C | Eco Club | Member |
| Anita | B | Literary | Editor |
| Priya | B | Literary | Member |
| Farhan | B | Music | Leader |
| Neha | C | Music | Member |
| Amit | A | Robotics | Captain |
| Imran | C | Robotics | Member |
| Sara | B | Robotics | Member |
| Gaurav | A | Sports | Captain |
| Rahul | A | Sports | Vice Captain |
+--------+---------+----------+--------------+
12 rows in set (0.00 sec)
mysql> 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;
+----------+---------+-----------+
| club | Members | Avg_Marks |
+----------+---------+-----------+
| Eco Club | 3 | 81.00 |
| Literary | 2 | 74.00 |
| Music | 2 | 70.00 |
| Robotics | 3 | 91.67 |
| Sports | 2 | 69.50 |
+----------+---------+-----------+
5 rows in set (0.00 sec)
mysql> SELECT name, dob FROM student WHERE dob = (SELECT MAX(dob) FROM student) OR dob = (SELECT MIN(dob) FROM student);
+--------+------------+
| name | dob |
+--------+------------+
| Priya | 2009-11-19 |
| Gaurav | 2008-08-15 |
+--------+------------+
2 rows in set (0.00 sec)
mysql> CREATE VIEW toppers AS
-> SELECT name, section, marks, grade
-> FROM student
-> WHERE marks >= 80;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM toppers ORDER BY marks DESC;
+-------+---------+-------+-------+
| name | section | marks | grade |
+-------+---------+-------+-------+
| Imran | C | 94.50 | A1 |
| Sara | B | 92.00 | A1 |
| Amit | A | 88.50 | A2 |
| Divya | B | 85.00 | A2 |
| Neha | C | 81.50 | A2 |
+-------+---------+-------+-------+
5 rows in set (0.00 sec)
mysql> SELECT name, marks
-> FROM student
-> WHERE marks > (SELECT AVG(marks) FROM student)
-> ORDER BY marks DESC;
+--------+-------+
| name | marks |
+--------+-------+
| Imran | 94.50 |
| Sara | 92.00 |
| Amit | 88.50 |
| Divya | 85.00 |
| Neha | 81.50 |
| Priya | 78.00 |
| Gaurav | 73.50 |
| Anita | 70.00 |
+--------+-------+
8 rows in set (0.00 sec)
mysql> SELECT name, section
-> FROM student
-> WHERE student_id NOT IN (SELECT student_id FROM activity);
+-------+---------+
| name | section |
+-------+---------+
| Karan | A |
| Pooja | A |
| Harsh | C |
+-------+---------+
3 rows in set (0.00 sec)
mysql> SELECT section, name, marks
-> FROM student s1
-> WHERE marks = (SELECT MAX(marks) FROM student s2 WHERE s2.section = s1.section)
-> ORDER BY section;
+---------+-------+-------+
| section | name | marks |
+---------+-------+-------+
| A | Amit | 88.50 |
| B | Sara | 92.00 |
| C | Imran | 94.50 |
+---------+-------+-------+
3 rows in set (0.00 sec)
mysql> 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;
+------+--------+-----+-------+-------+--------+
| Roll | Name | Sec | Marks | Grade | Result |
+------+--------+-----+-------+-------+--------+
| 1 | Amit | A | 88.50 | A2 | PASS |
| 13 | Gaurav | A | 73.50 | B | PASS |
| 3 | Rahul | A | 65.50 | B | PASS |
| 10 | Pooja | A | 47.00 | C | PASS |
| 5 | Karan | A | 35.00 | D | PASS |
| 2 | Sara | B | 92.00 | A1 | PASS |
| 14 | Divya | B | 85.00 | A2 | PASS |
| 4 | Priya | B | 78.00 | A2 | PASS |
| 8 | Anita | B | 70.00 | B | PASS |
| 11 | Farhan | B | 58.50 | C | PASS |
| 9 | Imran | C | 94.50 | A1 | PASS |
| 6 | Neha | C | 81.50 | A2 | PASS |
| 12 | Tina | C | 66.00 | B | PASS |
| 15 | Harsh | C | 39.50 | D | PASS |
+------+--------+-----+-------+-------+--------+
14 rows in set (0.00 sec)
mysql> 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;
+---------+--------+--------+--------------+
| section | Passed | Failed | Pass_Percent |
+---------+--------+--------+--------------+
| A | 5 | 0 | 100.0 |
| B | 5 | 0 | 100.0 |
| C | 4 | 0 | 100.0 |
+---------+--------+--------+--------------+
3 rows in set (0.00 sec)
- Start
- CREATE DATABASE kv_office and USE it
- CREATE TABLE student and activity with constraints
- INSERT records into both tables
- Run selection and conditional queries
- Run aggregate queries with GROUP BY and HAVING
- ALTER TABLE, UPDATE grade, DELETE a record
- Run function and join queries
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Top 5 scorers | 5 rows in descending order of marks | PASS |
| 2 | Section-wise strength | A 5, B 5, C 5 | PASS |
| 3 | Birthday in July | 4 students | PASS |
| 4 | marks BETWEEN 60 AND 80 | Students in range listed | PASS |
| 5 | city IS NULL | Students without city shown | PASS |
| 6 | HAVING AVG(marks) > 65 | Only qualifying sections | PASS |
| 7 | UPDATE grades then GROUP BY grade | Grade-wise counts | PASS |
| 8 | Insert marks 105 | Rejected by CHECK constraint (error shown) | PASS |
| 9 | Equi-join | Student names with their clubs | PASS |
| 10 | DELETE student 7 and COUNT | 14 students remain | PASS |
โ 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:
DROP DATABASE IF EXISTS kv_office;
Deletes the database kv_office completely (structure + data). It cannot be undone.
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".
USE kv_office;
Selects the database kv_office - all following commands work inside it.
- MySQL replies "Database changed".
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.
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.
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.
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.
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.
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.
SELECT * FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+--------+---------+--------+------------+-------+-----------+ | student_id | name | section | gender | dob | marks | city | +------------+--------+---------+--------+------------+-------+-----------+ | 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | | 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | | 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | | 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | | 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | | 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | | 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | | 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | | 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | | 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | | 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | | 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | | 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | | 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | | 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | +------------+--------+---------+--------+------------+-------+-----------+ 15 rows in set (0.00 sec)
SELECT name, marks FROM student ORDER BY marks DESC LIMIT 5;
Fetches rows from student, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT name, marks โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
- LIMIT 5 โ shows only the first 5 row(s) of the result.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts, LIMIT cuts โ final result:
+-------+-------+ | name | marks | +-------+-------+ | Imran | 94.50 | | Sara | 92.00 | | Amit | 88.50 | | Divya | 85.00 | | Neha | 81.50 | +-------+-------+ 5 rows in set (0.00 sec)
SELECT DISTINCT city FROM student;
Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- SELECT city โ picks the columns / calculates the values to show.
- DISTINCT โ removes repeated rows, so each value appears only once.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns; DISTINCT removes repeats โ final result:
+-----------+ | city | +-----------+ | Delhi | | Noida | | NULL | | Gurugram | | Faridabad | +-----------+ 5 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE section = 'B' โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- ORDER BY name โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition section = 'B' is checked row by row: 5 row(s) pass โ, 10 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+---------+-----+-------+ | Student | Sec | Score | +---------+-----+-------+ | Anita | B | 70.00 | | Divya | B | 85.00 | | Farhan | B | 58.50 | | Priya | B | 78.00 | | Sara | B | 92.00 | +---------+-----+-------+ 5 rows in set (0.00 sec)
SELECT name, dob FROM student WHERE MONTH(dob) = 7;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE MONTH(dob) = 7 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, dob โ picks the columns / calculates the values to show.
- Functions used: MONTH() takes the month number.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition MONTH(dob) = 7 is checked row by row: 4 row(s) pass โ, 11 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+------------+ | name | dob | +--------+------------+ | Amit | 2009-07-14 | | Rahul | 2009-07-25 | | Neha | 2009-07-30 | | Farhan | 2009-07-03 | +--------+------------+ 4 rows in set (0.00 sec)
SELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks BETWEEN 60 AND 80 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, marks โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition marks BETWEEN 60 AND 80 is checked row by row: 5 row(s) pass โ, 10 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+-------+ | name | marks | +--------+-------+ | Rahul | 65.50 | | Priya | 78.00 | | Anita | 70.00 | | Tina | 66.00 | | Gaurav | 73.50 | +--------+-------+ 5 rows in set (0.00 sec)
SELECT name, city FROM student WHERE city IN ('Noida','Gurugram');Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE city IN ('Noida','Gurugram') โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, city โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition city IN ('Noida','Gurugram') is checked row by row: 5 row(s) pass โ, 10 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------+----------+ | name | city | +-------+----------+ | Sara | Noida | | Karan | Gurugram | | Pooja | Noida | | Tina | Gurugram | | Divya | Noida | +-------+----------+ 5 rows in set (0.00 sec)
SELECT name FROM student WHERE name LIKE '_a%';
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT name โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition name LIKE '_a%' is checked row by row: 6 row(s) pass โ, 9 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+ | name | +--------+ | Sara | | Rahul | | Karan | | Farhan | | Gaurav | | Harsh | +--------+ 6 rows in set (0.00 sec)
SELECT name, section FROM student WHERE city IS NULL;
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE city IS NULL โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, section โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition city IS NULL is checked row by row: 2 row(s) pass โ, 13 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------+---------+ | name | section | +-------+---------+ | Priya | B | | Vikas | C | +-------+---------+ 2 rows in set (0.00 sec)
SELECT name, marks FROM student WHERE marks < 40 OR (section = 'C' AND gender = 'F');
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks < 40 OR (section = 'C' AND gender = 'F') โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, marks โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition marks < 40 OR (section = 'C' AND gender = 'F') is checked row by row: 5 row(s) pass โ, 10 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------+-------+ | name | marks | +-------+-------+ | Karan | 35.00 | | Neha | 81.50 | | Vikas | 29.00 | | Tina | 66.00 | | Harsh | 39.50 | +-------+-------+ 5 rows in set (0.00 sec)
SELECT COUNT(*) AS Total, AVG(marks) AS Average, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: COUNT(*) counts all rows; AVG() finds the average; MAX() finds the largest value; MIN() finds the smallest value.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+-------+-----------+---------+--------+ | Total | Average | Highest | Lowest | +-------+-----------+---------+--------+ | 15 | 66.900000 | 94.50 | 29.00 | +-------+-----------+---------+--------+ 1 row in set (0.00 sec)
SELECT section, COUNT(*) AS Strength FROM student GROUP BY section;
Fetches rows from student, grouped by section.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY section โ makes groups: rows with the same section go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
GROUP BY: Rows with the same section are put in one group โ 3 group(s).
| section | rows_in_group |
|---|---|
| A | 5 |
| B | 5 |
| C | 5 |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+----------+ | section | Strength | +---------+----------+ | A | 5 | | B | 5 | | C | 5 | +---------+----------+ 3 rows in set (0.00 sec)
SELECT section, MAX(marks) AS Highest, MIN(marks) AS Lowest FROM student GROUP BY section;
Fetches rows from student, grouped by section.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY section โ makes groups: rows with the same section go into one group (one output row per group).
- 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.
- Functions used: MAX() finds the largest value; MIN() finds the smallest value.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
GROUP BY: Rows with the same section are put in one group โ 3 group(s).
| section | rows_in_group |
|---|---|
| A | 5 |
| B | 5 |
| C | 5 |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+---------+--------+ | section | Highest | Lowest | +---------+---------+--------+ | A | 88.50 | 35.00 | | B | 92.00 | 58.50 | | C | 94.50 | 29.00 | +---------+---------+--------+ 3 rows in set (0.00 sec)
SELECT gender, ROUND(AVG(marks),2) AS Avg_Marks FROM student GROUP BY gender;
Fetches rows from student, grouped by gender.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY gender โ makes groups: rows with the same gender go into one group (one output row per group).
- 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.
- Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
GROUP BY: Rows with the same gender are put in one group โ 2 group(s).
| gender | rows_in_group |
|---|---|
| F | 7 |
| M | 8 |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+-----------+ | gender | Avg_Marks | +--------+-----------+ | F | 74.21 | | M | 60.50 | +--------+-----------+ 2 rows in set (0.00 sec)
SELECT section, ROUND(AVG(marks),2) AS Average FROM student GROUP BY section HAVING AVG(marks) > 65;
Fetches rows from student, grouped by section.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY section โ makes groups: rows with the same section go into one group (one output row per group).
- HAVING AVG(marks) > 65 โ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
- 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.
- Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
GROUP BY: Rows with the same section are put in one group โ 3 group(s).
| section | rows_in_group |
|---|---|
| A | 5 |
| B | 5 |
| C | 5 |
HAVING: Group condition AVG(marks) > 65 โ 1 group(s) kept โ.
| section | rows_in_group | |
|---|---|---|
| A | 5 | โ |
| B | 5 | โ |
| C | 5 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+---------+ | section | Average | +---------+---------+ | B | 76.70 | +---------+---------+ 1 row in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE city IS NOT NULL โ checks this condition for every row; only the rows where it is TRUE are kept.
- GROUP BY city โ makes groups: rows with the same city go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY Students DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition city IS NOT NULL is checked row by row: 13 row(s) pass โ, 2 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
GROUP BY: Rows with the same city are put in one group โ 4 group(s).
| city | rows_in_group |
|---|---|
| Delhi | 7 |
| Faridabad | 1 |
| Gurugram | 2 |
| Noida | 3 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-----------+----------+ | city | Students | +-----------+----------+ | Delhi | 7 | | Noida | 3 | | Gurugram | 2 | | Faridabad | 1 | +-----------+----------+ 4 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE section = 'A' โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: UPPER() changes text to capitals; LENGTH() counts characters; SUBSTR(text, start, n) takes n characters from position start.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition section = 'A' is checked row by row: 5 row(s) pass โ, 10 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+---------+-------+ | Name | Letters | Short | +--------+---------+-------+ | AMIT | 4 | Ami | | RAHUL | 5 | Rah | | KARAN | 5 | Kar | | POOJA | 5 | Poo | | GAURAV | 6 | Gau | +--------+---------+-------+ 5 rows in set (0.00 sec)
SELECT CONCAT(name, ' (', section, ')') AS Student, ROUND(marks/100*500) AS Out_of_500 FROM student LIMIT 6;Fetches rows from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: CONCAT() joins texts together; ROUND(x, d) rounds x to d decimal places.
- LIMIT 6 โ shows only the first 6 row(s) of the result.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns; LIMIT cuts โ final result:
+-----------+------------+ | Student | Out_of_500 | +-----------+------------+ | Amit (A) | 443 | | Sara (B) | 460 | | Rahul (A) | 328 | | Priya (B) | 390 | | Karan (A) | 175 | | Neha (C) | 408 | +-----------+------------+ 6 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE YEAR(dob) = 2008 โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: YEAR() takes the year from a date; MONTHNAME() gives the month name.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
WHERE: Condition YEAR(dob) = 2008 is checked row by row: 2 row(s) pass โ, 13 fail โ.
| student_id | name | section | gender | dob | marks | city | |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+------------+----------+ | name | Birth_Year | Month | +--------+------------+----------+ | Vikas | 2008 | December | | Gaurav | 2008 | August | +--------+------------+----------+ 2 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: DATEDIFF(d1, d2) gives days between two dates.
- ORDER BY dob โ sorts the result rows in ascending (small โ big / A โ Z) order.
- LIMIT 5 โ shows only the first 5 row(s) of the result.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city |
|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts, LIMIT cuts โ final result:
+--------+----------------+ | name | Age_on_1_April | +--------+----------------+ | Gaurav | 17 | | Vikas | 17 | | Karan | 17 | | Pooja | 17 | | Sara | 17 | +--------+----------------+ 5 rows in set (0.00 sec)
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.
UPDATE student SET grade = 'A1' WHERE marks >= 90;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE marks >= 90 โ finds only the rows that match.
- SET grade = 'A1' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE marks >= 90 โ 2 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | NULL | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | NULL | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | NULL | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | NULL | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | NULL | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | NULL | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | NULL | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | NULL | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | NULL | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | NULL |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | NULL | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | NULL | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | NULL | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | NULL | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | NULL | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | NULL | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | NULL | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | NULL |
UPDATE student SET grade = 'A2' WHERE marks >= 75 AND marks < 90;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE marks >= 75 AND marks < 90 โ finds only the rows that match.
- SET grade = 'A2' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE marks >= 75 AND marks < 90 โ 4 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | NULL | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | NULL | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | NULL | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | NULL | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | NULL | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | NULL | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | NULL | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | NULL | โ |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | NULL | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | NULL | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | NULL | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | NULL | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
UPDATE student SET grade = 'B' WHERE marks >= 60 AND marks < 75;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE marks >= 60 AND marks < 75 โ finds only the rows that match.
- SET grade = 'B' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE marks >= 60 AND marks < 75 โ 4 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | NULL | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | NULL | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | NULL | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | NULL | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
UPDATE student SET grade = 'C' WHERE marks >= 40 AND marks < 60;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE marks >= 40 AND marks < 60 โ finds only the rows that match.
- SET grade = 'C' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE marks >= 40 AND marks < 60 โ 2 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | NULL | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | NULL | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
UPDATE student SET grade = 'D' WHERE marks < 40;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE marks < 40 โ finds only the rows that match.
- SET grade = 'D' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE marks < 40 โ 3 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | NULL | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | NULL | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | D | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
SELECT grade, COUNT(*) AS Students FROM student GROUP BY grade ORDER BY grade;
Fetches rows from student, grouped by grade, in sorted order.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY grade โ makes groups: rows with the same grade go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY grade โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 15 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | D |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
GROUP BY: Rows with the same grade are put in one group โ 5 group(s).
| grade | rows_in_group |
|---|---|
| A1 | 2 |
| A2 | 4 |
| B | 4 |
| C | 2 |
| D | 3 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-------+----------+ | grade | Students | +-------+----------+ | A1 | 2 | | A2 | 4 | | B | 4 | | C | 2 | | D | 3 | +-------+----------+ 5 rows in set (0.00 sec)
UPDATE student SET city = 'Delhi' WHERE city IS NULL;
Changes existing data in table student.
- UPDATE student โ picks the table.
- WHERE city IS NULL โ finds only the rows that match.
- SET city = 'Delhi' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE city IS NULL โ 2 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | NULL | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | NULL | D | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
AFTER: The matched rows now have the new values (highlighted).
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | Delhi | D | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
DELETE FROM student WHERE student_id = 7;
Removes rows from table student.
- FROM student โ picks the table.
- WHERE student_id = 7 โ finds the matching rows.
- Those rows are removed permanently โ "Query OK, n rows affected".
FIND: WHERE student_id = 7 โ 1 row(s) matched.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 7 | Vikas | C | M | 2008-12-12 | 29.00 | Delhi | D | ๐ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
AFTER: The matched rows are gone โ 14 row(s) left.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
SELECT COUNT(*) AS Remaining FROM student;
Fetches the summary values from student.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+-----------+ | Remaining | +-----------+ | 14 | +-----------+ 1 row in set (0.00 sec)
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.
- FROM student s, activity a โ takes the tables together (every row of one with every row of the other - Cartesian product).
- WHERE s.student_id = a.student_id โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT s.name, s.section, a.club, a.position โ picks the columns / calculates the values to show.
- ORDER BY a.club, s.name โ sorts the result rows in ascending (small โ big / A โ Z) order - the 2nd column breaks ties.
FROM: The tables are joined: student s, activity a โ 168 combined rows.
| student_id | name | section | gender | dob | marks | city | grade | act_id | student_id | club | position |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 1 | 1 | Robotics | Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 2 | 2 | Eco Club | Secretary |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 3 | 9 | Robotics | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 4 | 6 | Music | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 5 | 14 | Eco Club | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 6 | 3 | Sports | Vice Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 7 | 13 | Sports | Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 8 | 2 | Robotics | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 9 | 11 | Music | Leader |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 10 | 8 | Literary | Editor |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 11 | 4 | Literary | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 12 | 12 | Eco Club | Member |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 1 | 1 | Robotics | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 2 | 2 | Eco Club | Secretary |
WHERE: Only the combined rows where s.student_id = a.student_id is TRUE are kept โ 12 row(s).
| student_id | name | section | gender | dob | marks | city | grade | act_id | student_id | club | position |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 1 | 1 | Robotics | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 2 | 2 | Eco Club | Secretary |
| 9 | Imran | C | M | 2009-09-09 | 94.5 | Delhi | A1 | 3 | 9 | Robotics | Member |
| 6 | Neha | C | F | 2009-07-30 | 81.5 | Delhi | A2 | 4 | 6 | Music | Member |
| 14 | Divya | B | F | 2009-04-04 | 85 | Noida | A2 | 5 | 14 | Eco Club | Member |
| 3 | Rahul | A | M | 2009-07-25 | 65.5 | Delhi | B | 6 | 3 | Sports | Vice Captain |
| 13 | Gaurav | A | M | 2008-08-15 | 73.5 | Delhi | B | 7 | 13 | Sports | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 8 | 2 | Robotics | Member |
| 11 | Farhan | B | M | 2009-07-03 | 58.5 | Delhi | C | 9 | 11 | Music | Leader |
| 8 | Anita | B | F | 2009-05-21 | 70 | Faridabad | B | 10 | 8 | Literary | Editor |
| 4 | Priya | B | F | 2009-11-19 | 78 | Delhi | A2 | 11 | 4 | Literary | Member |
| 12 | Tina | C | F | 2009-10-28 | 66 | Gurugram | B | 12 | 12 | Eco Club | Member |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------+---------+----------+--------------+ | name | section | club | position | +--------+---------+----------+--------------+ | Divya | B | Eco Club | Member | | Sara | B | Eco Club | Secretary | | Tina | C | Eco Club | Member | | Anita | B | Literary | Editor | | Priya | B | Literary | Member | | Farhan | B | Music | Leader | | Neha | C | Music | Member | | Amit | A | Robotics | Captain | | Imran | C | Robotics | Member | | Sara | B | Robotics | Member | | Gaurav | A | Sports | Captain | | Rahul | A | Sports | Vice Captain | +--------+---------+----------+--------------+ 12 rows in set (0.00 sec)
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.
- FROM student s, activity a โ takes the tables together (every row of one with every row of the other - Cartesian product).
- WHERE s.student_id = a.student_id โ checks this condition for every row; only the rows where it is TRUE are kept.
- GROUP BY a.club โ makes groups: rows with the same a.club go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
FROM: The tables are joined: student s, activity a โ 168 combined rows.
| student_id | name | section | gender | dob | marks | city | grade | act_id | student_id | club | position |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 1 | 1 | Robotics | Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 2 | 2 | Eco Club | Secretary |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 3 | 9 | Robotics | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 4 | 6 | Music | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 5 | 14 | Eco Club | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 6 | 3 | Sports | Vice Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 7 | 13 | Sports | Captain |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 8 | 2 | Robotics | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 9 | 11 | Music | Leader |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 10 | 8 | Literary | Editor |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 11 | 4 | Literary | Member |
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 12 | 12 | Eco Club | Member |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 1 | 1 | Robotics | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 2 | 2 | Eco Club | Secretary |
WHERE: Only the combined rows where s.student_id = a.student_id is TRUE are kept โ 12 row(s).
| student_id | name | section | gender | dob | marks | city | grade | act_id | student_id | club | position |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.5 | Delhi | A2 | 1 | 1 | Robotics | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 2 | 2 | Eco Club | Secretary |
| 9 | Imran | C | M | 2009-09-09 | 94.5 | Delhi | A1 | 3 | 9 | Robotics | Member |
| 6 | Neha | C | F | 2009-07-30 | 81.5 | Delhi | A2 | 4 | 6 | Music | Member |
| 14 | Divya | B | F | 2009-04-04 | 85 | Noida | A2 | 5 | 14 | Eco Club | Member |
| 3 | Rahul | A | M | 2009-07-25 | 65.5 | Delhi | B | 6 | 3 | Sports | Vice Captain |
| 13 | Gaurav | A | M | 2008-08-15 | 73.5 | Delhi | B | 7 | 13 | Sports | Captain |
| 2 | Sara | B | F | 2009-03-02 | 92 | Noida | A1 | 8 | 2 | Robotics | Member |
| 11 | Farhan | B | M | 2009-07-03 | 58.5 | Delhi | C | 9 | 11 | Music | Leader |
| 8 | Anita | B | F | 2009-05-21 | 70 | Faridabad | B | 10 | 8 | Literary | Editor |
| 4 | Priya | B | F | 2009-11-19 | 78 | Delhi | A2 | 11 | 4 | Literary | Member |
| 12 | Tina | C | F | 2009-10-28 | 66 | Gurugram | B | 12 | 12 | Eco Club | Member |
GROUP BY: Rows with the same a.club are put in one group โ 5 group(s).
| club | rows_in_group |
|---|---|
| Eco Club | 3 |
| Literary | 2 |
| Music | 2 |
| Robotics | 3 |
| Sports | 2 |
RESULT: SELECT picks / calculates the columns โ final result:
+----------+---------+-----------+ | club | Members | Avg_Marks | +----------+---------+-----------+ | Eco Club | 3 | 81.00 | | Literary | 2 | 74.00 | | Music | 2 | 70.00 | | Robotics | 3 | 91.67 | | Sports | 2 | 69.50 | +----------+---------+-----------+ 5 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT name, dob โ picks the columns / calculates the values to show.
- Functions used: MAX() finds the largest value; MIN() finds the smallest value.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
WHERE: Condition dob = (SELECT MAX(dob) FROM student) OR dob = (SELECT MIN(dob) FROM student) is checked row by row: 2 row(s) pass โ, 12 fail โ.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+--------+------------+ | name | dob | +--------+------------+ | Priya | 2009-11-19 | | Gaurav | 2008-08-15 | +--------+------------+ 2 rows in set (0.00 sec)
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.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
WHERE: Condition marks >= 80 is checked row by row: 5 row(s) pass โ, 9 fail โ.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D | โ |
SELECT * FROM toppers ORDER BY marks DESC;
Fetches rows from toppers, in sorted order.
- FROM toppers โ MySQL first opens table toppers and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- WHERE marks > (SELECT AVG(marks) FROM student) โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT name, marks โ picks the columns / calculates the values to show.
- Functions used: AVG() finds the average.
- ORDER BY marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
WHERE: Condition marks > (SELECT AVG(marks) FROM student) is checked row by row: 8 row(s) pass โ, 6 fail โ.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row; ORDER BY sorts โ final result:
+--------+-------+ | name | marks | +--------+-------+ | Imran | 94.50 | | Sara | 92.00 | | Amit | 88.50 | | Divya | 85.00 | | Neha | 81.50 | | Priya | 78.00 | | Gaurav | 73.50 | | Anita | 70.00 | +--------+-------+ 8 rows in set (0.00 sec)
SELECT name, section FROM student WHERE student_id NOT IN (SELECT student_id FROM activity);
Fetches rows from student that satisfy a condition.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT name, section โ picks the columns / calculates the values to show.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
WHERE: Condition student_id NOT IN (SELECT student_id FROM activity) is checked row by row: 3 row(s) pass โ, 11 fail โ.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------+---------+ | name | section | +-------+---------+ | Karan | A | | Pooja | A | | Harsh | C | +-------+---------+ 3 rows in set (0.00 sec)
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.
- FROM student s1 โ MySQL first opens table student and looks at all its rows.
- 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.
- SELECT section, name, marks โ picks the columns / calculates the values to show.
- Functions used: MAX() finds the largest value.
- ORDER BY section โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
WHERE: Condition marks = (SELECT MAX(marks) FROM student s2 WHERE s2.section = s1.section) is checked row by row: 3 row(s) pass โ, 11 fail โ.
| student_id | name | section | gender | dob | marks | city | grade | |
|---|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 | โ |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 | โ |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B | โ |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 | โ |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D | โ |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 | โ |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B | โ |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 | โ |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C | โ |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C | โ |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B | โ |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B | โ |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 | โ |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row; ORDER BY sorts โ final result:
+---------+-------+-------+ | section | name | marks | +---------+-------+-------+ | A | Amit | 88.50 | | B | Sara | 92.00 | | C | Imran | 94.50 | +---------+-------+-------+ 3 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- 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.
- 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.
- ORDER BY section, marks DESC โ sorts the result rows in descending (big โ small / Z โ A) order - the 2nd column breaks ties.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+------+--------+-----+-------+-------+--------+ | Roll | Name | Sec | Marks | Grade | Result | +------+--------+-----+-------+-------+--------+ | 1 | Amit | A | 88.50 | A2 | PASS | | 13 | Gaurav | A | 73.50 | B | PASS | | 3 | Rahul | A | 65.50 | B | PASS | | 10 | Pooja | A | 47.00 | C | PASS | | 5 | Karan | A | 35.00 | D | PASS | | 2 | Sara | B | 92.00 | A1 | PASS | | 14 | Divya | B | 85.00 | A2 | PASS | | 4 | Priya | B | 78.00 | A2 | PASS | | 8 | Anita | B | 70.00 | B | PASS | | 11 | Farhan | B | 58.50 | C | PASS | | 9 | Imran | C | 94.50 | A1 | PASS | | 6 | Neha | C | 81.50 | A2 | PASS | | 12 | Tina | C | 66.00 | B | PASS | | 15 | Harsh | C | 39.50 | D | PASS | +------+--------+-----+-------+-------+--------+ 14 rows in set (0.00 sec)
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.
- FROM student โ MySQL first opens table student and looks at all its rows.
- GROUP BY section โ makes groups: rows with the same section go into one group (one output row per group).
- 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.
- Functions used: SUM() adds the values; ROUND(x, d) rounds x to d decimal places; COUNT(*) counts all rows.
FROM: MySQL opens table student - all 14 rows are taken.
| student_id | name | section | gender | dob | marks | city | grade |
|---|---|---|---|---|---|---|---|
| 1 | Amit | A | M | 2009-07-14 | 88.50 | Delhi | A2 |
| 2 | Sara | B | F | 2009-03-02 | 92.00 | Noida | A1 |
| 3 | Rahul | A | M | 2009-07-25 | 65.50 | Delhi | B |
| 4 | Priya | B | F | 2009-11-19 | 78.00 | Delhi | A2 |
| 5 | Karan | A | M | 2009-01-08 | 35.00 | Gurugram | D |
| 6 | Neha | C | F | 2009-07-30 | 81.50 | Delhi | A2 |
| 8 | Anita | B | F | 2009-05-21 | 70.00 | Faridabad | B |
| 9 | Imran | C | M | 2009-09-09 | 94.50 | Delhi | A1 |
| 10 | Pooja | A | F | 2009-02-17 | 47.00 | Noida | C |
| 11 | Farhan | B | M | 2009-07-03 | 58.50 | Delhi | C |
| 12 | Tina | C | F | 2009-10-28 | 66.00 | Gurugram | B |
| 13 | Gaurav | A | M | 2008-08-15 | 73.50 | Delhi | B |
| 14 | Divya | B | F | 2009-04-04 | 85.00 | Noida | A2 |
| 15 | Harsh | C | M | 2009-06-11 | 39.50 | Delhi | D |
GROUP BY: Rows with the same section are put in one group โ 3 group(s).
| section | rows_in_group |
|---|---|
| A | 5 |
| B | 5 |
| C | 4 |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+--------+--------+--------------+ | section | Passed | Failed | Pass_Percent | +---------+--------+--------+--------------+ | A | 5 | 0 | 100.0 | | B | 5 | 0 | 100.0 | | C | 4 | 0 | 100.0 | +---------+--------+--------+--------------+ 3 rows in set (0.00 sec)
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.
Geography Quiz โ States & Capitals
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
STATES | dict | State -> capital |
UTS | dict | Union Territory -> capital |
RIVERS | dict | City -> river on which it is situated |
board | dict | Player -> best score |
# =====================================================================
# 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")
==================================================
INDIA GEOGRAPHY QUIZ
==================================================
Player name: Diya
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 4
Assam : Dispur Bihar : Patna
Delhi : New Delhi Goa : Panaji
Gujarat : Gandhinagar Karnataka : Bengaluru
Kerala : Thiruvananthapuram Maharashtra : Mumbai
Odisha : Bhubaneswar Punjab : Chandigarh
Rajasthan : Jaipur Sikkim : Gangtok
Tamil Nadu : Chennai Telangana : Hyderabad
Uttarakhand : Dehradun West Bengal : Kolkata
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 1
--- STATES & CAPITALS ---
Q1. What is the capital of Punjab?
A) Gandhinagar
B) Bengaluru
C) Kolkata
D) Chandigarh
Your option: B
Wrong! Answer: Chandigarh
Q2. What is the capital of Gujarat?
A) Panaji
B) Thiruvananthapuram
C) Hyderabad
D) Gandhinagar
Your option: A
Wrong! Answer: Gandhinagar
Q3. What is the capital of Goa?
A) Panaji
B) Chandigarh
C) Thiruvananthapuram
D) Mumbai
Your option: C
Wrong! Answer: Panaji
Q4. What is the capital of Telangana?
A) Chennai
B) Gandhinagar
C) Patna
D) Hyderabad
Your option: D
Correct!
Q5. What is the capital of Karnataka?
A) Kolkata
B) Bengaluru
C) Jaipur
D) Bhubaneswar
Your option: B
Correct!
Score 2/5 Accuracy 40%
Review: Punjab -> Chandigarh; Gujarat -> Gandhinagar; Goa -> Panaji
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 2
--- UNION TERRITORIES ---
Q1. What is the capital of Chandigarh UT?
A) Leh
B) Srinagar (summer)
C) Sri Vijaya Puram
D) Chandigarh
Your option: A
Wrong! Answer: Chandigarh
Q2. What is the capital of Jammu and Kashmir?
A) Sri Vijaya Puram
B) Chandigarh
C) Leh
D) Srinagar (summer)
Your option: Z
Choose A, B, C or D. Counted as wrong.
Q3. What is the capital of Ladakh?
A) Kavaratti
B) Puducherry
C) Chandigarh
D) Leh
Your option: C
Wrong! Answer: Leh
Q4. What is the capital of Andaman and Nicobar Islands?
A) Srinagar (summer)
B) Kavaratti
C) Leh
D) Sri Vijaya Puram
Your option: B
Wrong! Answer: Sri Vijaya Puram
Q5. What is the capital of Puducherry?
A) Sri Vijaya Puram
B) Puducherry
C) Chandigarh
D) Kavaratti
Your option: D
Wrong! Answer: Puducherry
Score 0/5 Accuracy 0%
Review: Chandigarh UT -> Chandigarh; Jammu and Kashmir -> Srinagar (summer); Ladakh -> Leh; Andaman and Nicobar Islands -> Sri Vijaya Puram; Puducherry -> Puducherry
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 3
--- RIVER CITIES ---
Q1. Kolkata is situated on which river?
A) Brahmaputra
B) Yamuna
C) Jhelum
D) Hooghly
Your option: A
Wrong! Answer: Hooghly
Q2. Ahmedabad is situated on which river?
A) Musi
B) Ganga
C) Jhelum
D) Sabarmati
Your option: B
Wrong! Answer: Sabarmati
Q3. Agra is situated on which river?
A) Ganga
B) Gomti
C) Yamuna
D) Sabarmati
Your option: C
Correct!
Q4. Srinagar is situated on which river?
A) Ganga
B) Gomti
C) Musi
D) Jhelum
Your option: A
Wrong! Answer: Jhelum
Q5. Lucknow is situated on which river?
A) Sabarmati
B) Musi
C) Ganga
D) Gomti
Your option: B
Wrong! Answer: Gomti
Score 1/5 Accuracy 20%
Review: Kolkata -> Hooghly; Ahmedabad -> Sabarmati; Srinagar -> Jhelum; Lucknow -> Gomti
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 6
State / UT name: kerala
Capital of Kerala: Thiruvananthapuram
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 6
State / UT name: Atlantis
Not found.
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 5
1. Diya 2/5 **
1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
Enter choice: 0
1. Diya 2/5 **
Jai Hind! Keep exploring India.
- Start
- Read player name
- Display menu and read choice
- Choice is a quiz? → No: practice / leader board / search
- Pick 5 random questions; make 4 options
- Ask question and read option A-D
- Answer correct? → No: store for review
- Score and accuracy; update leader board
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Correct option | 'Correct!' and score + 1 | PASS |
| 2 | Wrong option | Correct answer shown, kept for review | PASS |
| 3 | Option 'Z' | 'Choose A, B, C or D' and counted wrong | PASS |
| 4 | Search 'Kerala' | Thiruvananthapuram | PASS |
| 5 | Search unknown state | 'Not found' | PASS |
| 6 | Leader board | Players sorted by best score | PASS |
| 7 | Rivers quiz | City-river questions asked | PASS |
| 8 | Practice mode | Pairs displayed | PASS |
โ 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
- Imports (line 6):
random- random number functions are loaded. - Global variables / constants are created:
STATES,UTS,RIVERS,board. - 4 functions are defined (lines 19โ64) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
quiz(bank, title, question) | 19โ45 | Asks 5 multiple-choice questions from a dictionary. | main program |
practice() | 48โ51 | Shows pairs for revision. | main program |
leader_board() | 54โ57 | Best scores. | main program |
search() | 60โ64 | Finds capital of a state / UT. | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: INDIA GEOGRAPHY QUIZ
- You type Diya at Player name:shows: 1.States 2.UTs 3.Rivers 4.Practice 5.Leader Board 6.Search 0.Exit
- You type 4 at Enter choice:runs:
practice()shows: Assam : Dispur Bihar : Patna (+8 more lines) - You type 1 at Enter choice:runs:
quiz()shows: --- STATES & CAPITALS --- (+5 more lines) - You type B at Your option:shows: Wrong! Answer: Chandigarh (+5 more lines)
- You type A at Your option:shows: Wrong! Answer: Gandhinagar (+5 more lines)
- You type C at Your option:shows: Wrong! Answer: Panaji (+5 more lines)
- You type D at Your option:shows: Correct! (+5 more lines)
- You type B at Your option:shows: Correct! (+3 more lines)
- You type 2 at Enter choice:runs:
quiz()shows: --- UNION TERRITORIES --- (+5 more lines) - You type A at Your option:shows: Wrong! Answer: Chandigarh (+5 more lines)
- You type Z at Your option:shows: Choose A, B, C or D. Counted as wrong. (+5 more lines)
- You type C at Your option:shows: Wrong! Answer: Leh (+5 more lines)
- You type B at Your option:shows: Wrong! Answer: Sri Vijaya Puram (+5 more lines)
- You type D at Your option:shows: Wrong! Answer: Puducherry (+3 more lines)
- You type 3 at Enter choice:runs:
quiz()shows: --- RIVER CITIES --- (+5 more lines) - You type A at Your option:shows: Wrong! Answer: Hooghly (+5 more lines)
- You type B at Your option:shows: Wrong! Answer: Sabarmati (+5 more lines)
- You type C at Your option:shows: Correct! (+5 more lines)
- You type A at Your option:shows: Wrong! Answer: Jhelum (+5 more lines)
- You type B at Your option:shows: Wrong! Answer: Gomti (+3 more lines)
- You type 6 at Enter choice:runs:
search() - You type kerala at State / UT name:shows: Capital of Kerala: Thiruvananthapuram (+1 more lines)
- You type 6 at Enter choice:runs:
search() - You type Atlantis at State / UT name:shows: Not found. (+1 more lines)
- You type 5 at Enter choice:runs:
leader_board()shows: 1. Diya 2/5 ** (+1 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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'.
Electricity Bill Calculator
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
๐ฏ Objectives
- Apply slab-wise conditional logic
- Return several values from a function
- Use the statistics module for the mean
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
consumers | dict | Consumer no -> {name, type, prev, curr} |
SLABS | list of tuple | (upper limit, rate) for domestic tariff |
COMMERCIAL_RATE | float | Rs. 8.5 per unit |
bills | dict | Consumer no -> total bill |
# =====================================================================
# 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"))()
==================================================
ELECTRICITY BILL CALCULATOR
==================================================
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 1
Consumer name : Ramesh
Type D/C (domestic/commercial): D
Previous reading : 1200
Current reading : 1280
Consumer no 5001 created. Units used: 80
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 1
Consumer name : Sunita
Type D/C (domestic/commercial): D
Previous reading : 3400
Current reading : 3650
Consumer no 5002 created. Units used: 250
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 1
Consumer name : Gupta Store
Type D/C (domestic/commercial): C
Previous reading : 5000
Current reading : 5300
Consumer no 5003 created. Units used: 300
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 1
Consumer name : Iqbal
Type D/C (domestic/commercial): D
Previous reading : 900
Current reading : 850
Invalid reading - current is less than previous.
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 1
Consumer name : Iqbal
Type D/C (domestic/commercial): D
Previous reading : 900
Current reading : 1420
Consumer no 5004 created. Units used: 520
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 2
Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
Consumer no: 5002
--------------------------------------------------
Consumer 5002: Sunita (Domestic)
Readings 3400 -> 3650 Units 250
Units 1-100 : 100 x 3.0 = 300.00
Units 101-200 : 100 x 4.5 = 450.00
Units 201-250 : 50 x 6.5 = 325.00
Energy charge 1075.00
Fixed charge 70.00
Duty (5%) 53.75
TOTAL BILL 1198.75
--------------------------------------------------
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 2
Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
Consumer no: 5003
--------------------------------------------------
Consumer 5003: Gupta Store (Commercial)
Readings 5000 -> 5300 Units 300
Units 1-300 : 300 x 8.5 = 2550.00
Energy charge 2550.00
Fixed charge 150.00
Duty (5%) 127.50
TOTAL BILL 2827.50
--------------------------------------------------
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 3
No Name Type Units Bill
5001 Ramesh D 80 302.00
5002 Sunita D 250 1198.75
5003 Gupta Store C 300 2827.50
5004 Iqbal D 520 3197.50
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 4
No Name Type Units Bill
5001 Ramesh D 80 302.00
5002 Sunita D 250 1198.75
5003 Gupta Store C 300 2827.50
5004 Iqbal D 520 3197.50
Highest bill : Iqbal Rs. 3197.5
Average units: 287.5 | Median units: 275.0
Total revenue: Rs. 7525.75
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 5
Above 400 units: ['Iqbal']
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 6
Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
Consumer no: 5004
Bill Rs. 3197.5 + surcharge Rs. 63.95 = Rs. 3261.45
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 7
Ramesh 80 units : Excellent - keep it up!
Sunita 250 units : Switch off fans/lights when not in use.
Gupta Store 300 units : Switch off fans/lights when not in use.
Iqbal 520 units : Use 5-star AC, set it to 24 C; consider solar panels.
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 2
Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal
Consumer no: 99
Consumer not found.
1.Add 2.Bill 3.All Bills 4.Stats 5.Heavy Users 6.Late Fee 7.Tips 0.Exit
Enter choice: 0
Save electricity, save the planet!
- Start
- Display menu and read choice
- Choice is Add? → No: run selected option
- Read name, type, previous and current reading
- Current >= previous? → No: 'Invalid reading'
- Units = current - previous
- Energy charge by slabs + fixed + 5 % duty
- Print bill / reports
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Units 80 (domestic) | Energy Rs. 240 (first slab) | PASS |
| 2 | Units 250 | Slab break-up 100/100/50 | PASS |
| 3 | Current reading less than previous | 'Invalid reading' | PASS |
| 4 | Commercial 300 units | Flat Rs. 8.5 per unit | PASS |
| 5 | Late payment | 2 % surcharge added | PASS |
| 6 | Statistics | Highest bill and total revenue | PASS |
| 7 | Heavy users | Consumers above 400 units listed | PASS |
| 8 | Unknown 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
- Imports (line 6):
statistics- mean, median, mode functions are loaded. - Global variables / constants are created:
SLABS,COMMERCIAL_RATE,consumers,bills,next_no. - 9 functions are defined (lines 15โ123) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
slab_charge(units) | 15โ24 | Energy charge with break-up for domestic tariff. | compute() |
compute(no) | 27โ40 | Returns energy, fixed, duty, total and break-up. | bill_of(), all_bills(), late_payment() |
add_consumer() | 43โ59 | Adds a consumer with readings. | main program (menu) |
bill_of() | 62โ80 | Detailed bill of one consumer. | main program (menu) |
all_bills() | 83โ88 | Bills of all consumers. | stats(), main program (menu) |
stats() | 91โ98 | Highest, average and revenue. | main program (menu) |
heavy_users() | 101โ104 | Consumers above 400 units. | main program (menu) |
late_payment() | 107โ114 | 2 % surcharge. | main program (menu) |
tips() | 117โ123 | Saving tips. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: ELECTRICITY BILL CALCULATOR (+1 more lines)
- You type 1 at Enter choice:runs:
add_consumer() - You type Ramesh at Consumer name :
- You type D at Type D/C (domestic/commercial):
- You type 1200 at Previous reading :
- You type 1280 at Current reading :shows: Consumer no 5001 created. Units used: 80 (+1 more lines)
- You type 1 at Enter choice:runs:
add_consumer() - You type Sunita at Consumer name :
- You type D at Type D/C (domestic/commercial):
- You type 3400 at Previous reading :
- You type 3650 at Current reading :shows: Consumer no 5002 created. Units used: 250 (+1 more lines)
- You type 1 at Enter choice:runs:
add_consumer() - You type Gupta Store at Consumer name :
- You type C at Type D/C (domestic/commercial):
- You type 5000 at Previous reading :
- You type 5300 at Current reading :shows: Consumer no 5003 created. Units used: 300 (+1 more lines)
- You type 1 at Enter choice:runs:
add_consumer() - You type Iqbal at Consumer name :
- You type D at Type D/C (domestic/commercial):
- You type 900 at Previous reading :
- You type 850 at Current reading :shows: Invalid reading - current is less than previous. (+1 more lines)
- You type 1 at Enter choice:runs:
add_consumer() - You type Iqbal at Consumer name :
- You type D at Type D/C (domestic/commercial):
- You type 900 at Previous reading :
- You type 1420 at Current reading :shows: Consumer no 5004 created. Units used: 520 (+1 more lines)
- You type 2 at Enter choice:runs:
bill_of()shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal - You type 5002 at Consumer no:runs:
compute()โslab_charge()shows: Consumer 5002: Sunita (Domestic) (+9 more lines) - You type 2 at Enter choice:runs:
bill_of()shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal - You type 5003 at Consumer no:runs:
compute()shows: Consumer 5003: Gupta Store (Commercial) (+7 more lines) - 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) - 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) - You type 5 at Enter choice:runs:
heavy_users()shows: Above 400 units: ['Iqbal'] (+1 more lines) - You type 6 at Enter choice:runs:
late_payment()shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal - 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) - You type 7 at Enter choice:runs:
tips()shows: Ramesh 80 units : Excellent - keep it up! (+4 more lines) - You type 2 at Enter choice:runs:
bill_of()shows: Consumers: 5001-Ramesh, 5002-Sunita, 5003-Gupta Store, 5004-Iqbal - You type 99 at Consumer no:shows: Consumer not found. (+1 more lines)
- You type 0 at Enter choice:shows: Save electricity, save the planet!
โค Inside each function - line by line
slab_charge() - lines 15โ24
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
BMI & Health Tracker
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
๐ฏ Objectives
- Apply the BMI formula in a program
- Classify values with a function
- Use statistics.mean() and statistics.median()
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
records | dict | Name -> {age, gender, weight, height} |
bmi | float | weight (kg) / height (m) squared |
bmr | float | Basal metabolic rate (kcal/day) |
CATS | list of tuple | (upper limit, category) for BMI |
# =====================================================================
# 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"))()
==============================================================
BMI & HEALTH TRACKER (School Health Club)
==============================================================
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Aman
Age : 16
Gender (M/F): M
Weight (kg): 50
Height (cm): 160
Saved. BMI = 19.5 (Normal)
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Bina
Age : 16
Gender (M/F): F
Weight (kg): 42
Height (cm): 158
Saved. BMI = 16.8 (Underweight)
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Chetan
Age : 17
Gender (M/F): M
Weight (kg): 85
Height (cm): 165
Saved. BMI = 31.2 (Obese)
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Dolly
Age : 16
Gender (M/F): F
Weight (kg): 58
Height (cm): 155
Saved. BMI = 24.1 (Normal)
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Esha
Age : 17
Gender (M/F): F
Weight (kg): 50
Height (cm): 20
Invalid height (100-220 cm).
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 1
Name : Farhan
Age : 17
Gender (M/F): M
Weight (kg): 68
Height (cm): 175
Saved. BMI = 22.2 (Normal)
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 2
Name Age Wt Ht BMI Category Ideal weight
--------------------------------------------------------------
Aman 16 50 160 19.5 Normal 47-64 kg
Bina 16 42 158 16.8 Underweight 46-62 kg
Chetan 17 85 165 31.2 Obese 50-68 kg
Dolly 16 58 155 24.1 Normal 44-60 kg
Farhan 17 68 175 22.2 Normal 57-76 kg
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 3
Name: Chetan
========================================
HEALTH CARD : Chetan
BMI 31.2 - Obese
BMR 1801 kcal/day | Active-day need ~2792 kcal
Water: about 2.8 litres per day
Tip: Consult a doctor; start with brisk walking and portion control.
========================================
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 4
Mean BMI : 22.76
Median BMI : 22.2
Mode (rounded): 20
Std dev : 4.89
Underweight #### 1
Normal ############ 3
Overweight 0
Obese #### 1
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 5
Name: Chetan
New weight (kg): 80
BMI 31.2 -> 29.4 (-1.8); now Overweight
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 6
Bina BMI 16.8 Underweight
Chetan BMI 29.4 Overweight
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 7
Name: Zara
Record not found.
1.Add 2.Report 3.Health Card 4.Statistics 5.Update Weight 6.Attention 7.Delete 0.Exit
Enter choice: 0
Stay fit, stay healthy!
- Start
- Display menu and read choice
- Choice is Add? → No: run selected report
- Read name, age, gender, weight, height
- Values in valid range? → No: show error
- BMI, category, ideal weight, BMR
- Show card / report / statistics
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | W 50 kg, H 160 cm | BMI 19.5 Normal | PASS |
| 2 | W 85, H 165 | BMI 31.2 Obese | PASS |
| 3 | Height 20 cm | 'Invalid height' | PASS |
| 4 | Individual card | BMR and water intake shown | PASS |
| 5 | Class statistics | Mean, median, mode and chart | PASS |
| 6 | Update weight 85 -> 80 | BMI change displayed | PASS |
| 7 | Need attention | Students outside normal listed | PASS |
| 8 | Delete 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
- Imports (line 6):
statistics- mean, median, mode functions are loaded. - Global variables / constants are created:
CATS,records. - 10 functions are defined (lines 12โ114) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
bmi_of(r) | 12โ13 | Bmi of | add_record(), report(), card(), class_stats() |
category(b) | 16โ20 | Category | add_record(), report(), card(), class_stats() |
bmr_of(r) | 23โ26 | Mifflin-St Jeor BMR. | card() |
add_record() | 29โ47 | Adds a health record. | main program (menu) |
report() | 50โ57 | BMI report of all students. | main program (menu) |
card() | 60โ78 | Individual health card. | main program (menu) |
class_stats() | 81โ90 | Mean, median, mode of BMI and category chart. | main program (menu) |
update_weight() | 93โ102 | Progress tracking. | main program (menu) |
attention() | 105โ109 | Students outside normal BMI. | main program (menu) |
delete() | 112โ114 | Delete | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: BMI & HEALTH TRACKER (School Health Club) (+1 more lines)
- You type 1 at Enter choice:runs:
add_record() - You type Aman at Name :
- You type 16 at Age :
- You type M at Gender (M/F):
- You type 50 at Weight (kg):
- You type 160 at Height (cm):runs:
bmi_of()ร2 โcategory()shows: Saved. BMI = 19.5 (Normal) (+1 more lines) - You type 1 at Enter choice:runs:
add_record() - You type Bina at Name :
- You type 16 at Age :
- You type F at Gender (M/F):
- You type 42 at Weight (kg):
- You type 158 at Height (cm):runs:
bmi_of()ร2 โcategory()shows: Saved. BMI = 16.8 (Underweight) (+1 more lines) - You type 1 at Enter choice:runs:
add_record() - You type Chetan at Name :
- You type 17 at Age :
- You type M at Gender (M/F):
- You type 85 at Weight (kg):
- You type 165 at Height (cm):runs:
bmi_of()ร2 โcategory()shows: Saved. BMI = 31.2 (Obese) (+1 more lines) - You type 1 at Enter choice:runs:
add_record() - You type Dolly at Name :
- You type 16 at Age :
- You type F at Gender (M/F):
- You type 58 at Weight (kg):
- You type 155 at Height (cm):runs:
bmi_of()ร2 โcategory()shows: Saved. BMI = 24.1 (Normal) (+1 more lines) - You type 1 at Enter choice:runs:
add_record() - You type Esha at Name :
- You type 17 at Age :
- You type F at Gender (M/F):
- You type 50 at Weight (kg):
- You type 20 at Height (cm):shows: Invalid height (100-220 cm). (+1 more lines)
- You type 1 at Enter choice:runs:
add_record() - You type Farhan at Name :
- You type 17 at Age :
- You type M at Gender (M/F):
- You type 68 at Weight (kg):
- You type 175 at Height (cm):runs:
bmi_of()ร2 โcategory()shows: Saved. BMI = 22.2 (Normal) (+1 more lines) - 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) - You type 3 at Enter choice:runs:
card() - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Hospital Patient Records (SQL Database)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
patient | TABLE | pid 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) |
doctor | TABLE | did INT PK, dname VARCHAR(30), department VARCHAR(20), fee INT |
appointment | TABLE | app_id INT PK, pid INT, did INT, app_date DATE |
-- =====================================================================
-- 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;
mysql> DROP DATABASE IF EXISTS hospital_db;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE DATABASE hospital_db;
Query OK, 1 row affected (0.00 sec)
mysql> USE hospital_db;
Database changed
mysql> 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));
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE doctor (did INT PRIMARY KEY, dname VARCHAR(30), department VARCHAR(20), fee INT);
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE appointment (app_id INT PRIMARY KEY, pid INT, did INT, app_date DATE);
Query OK, 0 rows affected (0.00 sec)
mysql> 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);
Query OK, 12 rows affected (0.00 sec)
Records: 12 Duplicates: 0 Warnings: 0
mysql> 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);
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> 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');
Query OK, 10 rows affected (0.00 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> SELECT pid, pname, age, disease FROM patient WHERE ward = 'ICU';
+-----+--------------+-----+---------------+
| pid | pname | age | disease |
+-----+--------------+-----+---------------+
| 104 | Meena Kapoor | 62 | Heart Disease |
| 110 | Suresh Yadav | 70 | Heart Disease |
+-----+--------------+-----+---------------+
2 rows in set (0.00 sec)
mysql> SELECT pname, age FROM patient WHERE age > 50 ORDER BY age DESC;
+--------------+-----+
| pname | age |
+--------------+-----+
| Suresh Yadav | 70 |
| Meena Kapoor | 62 |
| Anita Das | 58 |
| Ramesh Gupta | 54 |
+--------------+-----+
4 rows in set (0.00 sec)
mysql> SELECT pname, disease FROM patient WHERE pname LIKE 'S%';
+--------------+---------------+
| pname | disease |
+--------------+---------------+
| Sunita Devi | Fever |
| Suresh Yadav | Heart Disease |
+--------------+---------------+
2 rows in set (0.00 sec)
mysql> SELECT pname, disease FROM patient WHERE disease IN ('Diabetes','Typhoid');
+---------------+----------+
| pname | disease |
+---------------+----------+
| Ramesh Gupta | Diabetes |
| Imran Khan | Typhoid |
| Harpreet Kaur | Diabetes |
| Anita Das | Typhoid |
+---------------+----------+
4 rows in set (0.00 sec)
mysql> SELECT pname, age, ward FROM patient WHERE gender = 'F' AND age BETWEEN 30 AND 60;
+---------------+-----+---------+
| pname | age | ward |
+---------------+-----+---------+
| Sunita Devi | 36 | General |
| Harpreet Kaur | 47 | Private |
| Anita Das | 58 | General |
+---------------+-----+---------+
3 rows in set (0.00 sec)
mysql> SELECT pname, bill FROM patient WHERE bill BETWEEN 10000 AND 30000 ORDER BY bill;
+---------------+----------+
| pname | bill |
+---------------+----------+
| Ramesh Gupta | 12500.00 |
| Harpreet Kaur | 15200.00 |
| Aarav Singh | 18000.00 |
| Kavita Rao | 21500.00 |
+---------------+----------+
4 rows in set (0.00 sec)
mysql> 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;
+----------+-----------+----------+-----------+----------+
| Patients | Total | Avg_Bill | Max_Bill | Min_Bill |
+----------+-----------+----------+-----------+----------+
| 12 | 384100.00 | 32008.33 | 120000.00 | 3600.00 |
+----------+-----------+----------+-----------+----------+
1 row in set (0.00 sec)
mysql> SELECT ward, COUNT(*) AS Patients, SUM(bill) AS Total_Bill FROM patient GROUP BY ward ORDER BY Total_Bill DESC;
+----------+----------+------------+
| ward | Patients | Total_Bill |
+----------+----------+------------+
| ICU | 2 | 216000.00 |
| Private | 4 | 113700.00 |
| General | 4 | 32800.00 |
| Children | 2 | 21600.00 |
+----------+----------+------------+
4 rows in set (0.00 sec)
mysql> SELECT ward, ROUND(AVG(bill),2) AS Avg_Bill FROM patient GROUP BY ward HAVING AVG(bill) > 20000;
+---------+-----------+
| ward | Avg_Bill |
+---------+-----------+
| ICU | 108000.00 |
| Private | 28425.00 |
+---------+-----------+
2 rows in set (0.00 sec)
mysql> SELECT MONTHNAME(admit_date) AS Month, COUNT(*) AS Admissions FROM patient GROUP BY MONTHNAME(admit_date), MONTH(admit_date) ORDER BY MONTH(admit_date);
+-----------+------------+
| Month | Admissions |
+-----------+------------+
| July | 4 |
| August | 4 |
| September | 4 |
+-----------+------------+
3 rows in set (0.00 sec)
mysql> SELECT pname, admit_date, DATEDIFF('2026-09-30', admit_date) AS Days_Admitted FROM patient ORDER BY Days_Admitted DESC LIMIT 5;
+--------------+------------+---------------+
| pname | admit_date | Days_Admitted |
+--------------+------------+---------------+
| Ramesh Gupta | 2026-07-04 | 88 |
| Sunita Devi | 2026-07-09 | 83 |
| Aarav Singh | 2026-07-12 | 80 |
| Meena Kapoor | 2026-07-15 | 77 |
| Imran Khan | 2026-08-02 | 59 |
+--------------+------------+---------------+
5 rows in set (0.00 sec)
mysql> SELECT pname, DAYNAME(admit_date) AS Admitted_On FROM patient WHERE ward = 'Private';
+---------------+-------------+
| pname | Admitted_On |
+---------------+-------------+
| Kavita Rao | Wednesday |
| Harpreet Kaur | Tuesday |
| Vikas Jain | Wednesday |
| Rohit Mehra | Monday |
+---------------+-------------+
4 rows in set (0.00 sec)
mysql> UPDATE patient SET bill = bill * 0.90 WHERE age < 18;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> SELECT pname, age, bill FROM patient WHERE age < 18;
+-------------+-----+----------+
| pname | age | bill |
+-------------+-----+----------+
| Aarav Singh | 8 | 16200.00 |
| Neha Bansal | 5 | 3240.00 |
+-------------+-----+----------+
2 rows in set (0.00 sec)
mysql> UPDATE patient SET ward = 'General' WHERE pid = 106;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> DELETE FROM patient WHERE pid = 105;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT COUNT(*) AS Remaining_Patients FROM patient;
+--------------------+
| Remaining_Patients |
+--------------------+
| 11 |
+--------------------+
1 row in set (0.00 sec)
mysql> 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;
+--------+--------------+---------------+------------------+------------+
| app_id | pname | dname | department | app_date |
+--------+--------------+---------------+------------------+------------+
| 5 | Ramesh Gupta | Dr. S. Khan | General Medicine | 2026-07-04 |
| 3 | Aarav Singh | Dr. P. Nair | Orthopaedics | 2026-07-12 |
| 9 | Aarav Singh | Dr. R. Iyer | Paediatrics | 2026-07-13 |
| 1 | Meena Kapoor | Dr. A. Sharma | Cardiology | 2026-07-15 |
| 10 | Vikas Jain | Dr. M. Gill | Surgery | 2026-08-19 |
| 8 | Neha Bansal | Dr. R. Iyer | Paediatrics | 2026-09-01 |
| 2 | Suresh Yadav | Dr. A. Sharma | Cardiology | 2026-09-06 |
| 7 | Anita Das | Dr. S. Khan | General Medicine | 2026-09-14 |
| 4 | Rohit Mehra | Dr. P. Nair | Orthopaedics | 2026-09-21 |
+--------+--------------+---------------+------------------+------------+
9 rows in set (0.00 sec)
mysql> 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;
+---------------+--------------+--------+
| dname | Appointments | Income |
+---------------+--------------+--------+
| Dr. A. Sharma | 2 | 2400 |
| Dr. P. Nair | 2 | 1800 |
| Dr. S. Khan | 3 | 1800 |
| Dr. M. Gill | 1 | 1500 |
| Dr. R. Iyer | 2 | 1400 |
+---------------+--------------+--------+
5 rows in set (0.00 sec)
mysql> SELECT disease, COUNT(*) AS Cases FROM patient GROUP BY disease ORDER BY Cases DESC, disease;
+---------------+-------+
| disease | Cases |
+---------------+-------+
| Diabetes | 2 |
| Fever | 2 |
| Fracture | 2 |
| Heart Disease | 2 |
| Appendicitis | 1 |
| Dengue | 1 |
| Typhoid | 1 |
+---------------+-------+
7 rows in set (0.00 sec)
mysql> SELECT gender, COUNT(*) AS Patients, ROUND(AVG(age),1) AS Avg_Age FROM patient GROUP BY gender;
+--------+----------+---------+
| gender | Patients | Avg_Age |
+--------+----------+---------+
| F | 6 | 39.5 |
| M | 5 | 38.0 |
+--------+----------+---------+
2 rows in set (0.00 sec)
mysql> CREATE VIEW icu_patients AS
-> SELECT pid, pname, age, bill
-> FROM patient
-> WHERE ward = 'ICU';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM icu_patients;
+-----+--------------+-----+-----------+
| pid | pname | age | bill |
+-----+--------------+-----+-----------+
| 104 | Meena Kapoor | 62 | 96000.00 |
| 110 | Suresh Yadav | 70 | 120000.00 |
+-----+--------------+-----+-----------+
2 rows in set (0.00 sec)
mysql> SELECT pname, bill
-> FROM patient
-> WHERE bill > (SELECT AVG(bill) FROM patient)
-> ORDER BY bill DESC;
+--------------+-----------+
| pname | bill |
+--------------+-----------+
| Suresh Yadav | 120000.00 |
| Meena Kapoor | 96000.00 |
| Vikas Jain | 45000.00 |
+--------------+-----------+
3 rows in set (0.00 sec)
mysql> SELECT pname, age
-> FROM patient
-> WHERE age = (SELECT MIN(age) FROM patient)
-> OR age = (SELECT MAX(age) FROM patient);
+--------------+-----+
| pname | age |
+--------------+-----+
| Neha Bansal | 5 |
| Suresh Yadav | 70 |
+--------------+-----+
2 rows in set (0.00 sec)
mysql> SELECT dname, department
-> FROM doctor
-> WHERE did NOT IN (SELECT did FROM appointment WHERE app_date >= '2026-09-01');
+-------------+------------+
| dname | department |
+-------------+------------+
| Dr. M. Gill | Surgery |
+-------------+------------+
1 row in set (0.00 sec)
mysql> 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;
+---------------+------------+------------------+
| Patient | Age_Gender | Bill_in_Thousand |
+---------------+------------+------------------+
| SURESH YADAV | 70 yrs / M | 120.0 |
| MEENA KAPOOR | 62 yrs / F | 96.0 |
| VIKAS JAIN | 33 yrs / M | 45.0 |
| ROHIT MEHRA | 25 yrs / M | 32.0 |
| HARPREET KAUR | 47 yrs / F | 15.2 |
+---------------+------------+------------------+
5 rows in set (0.00 sec)
mysql> 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;
+----------+----------+-----------------+
| ward | Patients | Revenue_Percent |
+----------+----------+-----------------+
| ICU | 2 | 57.7 |
| Private | 3 | 24.6 |
| General | 4 | 12.4 |
| Children | 2 | 5.2 |
+----------+----------+-----------------+
4 rows in set (0.00 sec)
mysql> SELECT LEFT(pname, LOCATE(' ', pname) - 1) AS First_Name, LENGTH(pname) AS Name_Length
-> FROM patient
-> WHERE LENGTH(pname) > 11;
+------------+-------------+
| First_Name | Name_Length |
+------------+-------------+
| Ramesh | 12 |
| Meena | 12 |
| Harpreet | 13 |
| Suresh | 12 |
+------------+-------------+
4 rows in set (0.00 sec)
- Start
- Create hospital_db and three tables
- Insert patients, doctors and appointments
- Run patient and billing queries
- Run date-based reports
- UPDATE bills and DELETE discharged patient
- Run join queries for doctor reports
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | ICU patients | Meena Kapoor and Suresh Yadav | PASS |
| 2 | Age > 50 ordered | Eldest first | PASS |
| 3 | Ward-wise revenue | Totals per ward | PASS |
| 4 | Bill BETWEEN 10000 AND 30000 | Matching patients | PASS |
| 5 | Month-wise admissions | Jul, Aug, Sep counts | PASS |
| 6 | 10 % child discount | Bills of age < 18 reduced | PASS |
| 7 | Join doctor-patient | Each appointment with both names | PASS |
| 8 | Doctor-wise income | fee x appointments | PASS |
| 9 | Delete patient 105 | 11 patients remain | PASS |
โ 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:
DROP DATABASE IF EXISTS hospital_db;
Deletes the database hospital_db completely (structure + data). It cannot be undone.
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".
USE hospital_db;
Selects the database hospital_db - all following commands work inside it.
- MySQL replies "Database changed".
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.
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.
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.
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.
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.
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.
SELECT pid, pname, age, disease FROM patient WHERE ward = 'ICU';
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, disease โ picks the columns / calculates the values to show.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition ward = 'ICU' is checked row by row: 2 row(s) pass โ, 10 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-----+--------------+-----+---------------+ | pid | pname | age | disease | +-----+--------------+-----+---------------+ | 104 | Meena Kapoor | 62 | Heart Disease | | 110 | Suresh Yadav | 70 | Heart Disease | +-----+--------------+-----+---------------+ 2 rows in set (0.00 sec)
SELECT pname, age FROM patient WHERE age > 50 ORDER BY age DESC;
Fetches rows from patient that satisfy a condition, in sorted order.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE age > 50 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, age โ picks the columns / calculates the values to show.
- ORDER BY age DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition age > 50 is checked row by row: 4 row(s) pass โ, 8 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------------+-----+ | pname | age | +--------------+-----+ | Suresh Yadav | 70 | | Meena Kapoor | 62 | | Anita Das | 58 | | Ramesh Gupta | 54 | +--------------+-----+ 4 rows in set (0.00 sec)
SELECT pname, disease FROM patient WHERE pname LIKE 'S%';
Fetches rows from patient that satisfy a condition.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE pname LIKE 'S%' (starts with "S") โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, disease โ picks the columns / calculates the values to show.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition pname LIKE 'S%' is checked row by row: 2 row(s) pass โ, 10 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------------+---------------+ | pname | disease | +--------------+---------------+ | Sunita Devi | Fever | | Suresh Yadav | Heart Disease | +--------------+---------------+ 2 rows in set (0.00 sec)
SELECT pname, disease FROM patient WHERE disease IN ('Diabetes','Typhoid');Fetches rows from patient that satisfy a condition.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE disease IN ('Diabetes','Typhoid') โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, disease โ picks the columns / calculates the values to show.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition disease IN ('Diabetes','Typhoid') is checked row by row: 4 row(s) pass โ, 8 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+---------------+----------+ | pname | disease | +---------------+----------+ | Ramesh Gupta | Diabetes | | Imran Khan | Typhoid | | Harpreet Kaur | Diabetes | | Anita Das | Typhoid | +---------------+----------+ 4 rows in set (0.00 sec)
SELECT pname, age, ward FROM patient WHERE gender = 'F' AND age BETWEEN 30 AND 60;
Fetches rows from patient that satisfy a condition.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE gender = 'F' AND age BETWEEN 30 AND 60 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, age, ward โ picks the columns / calculates the values to show.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition gender = 'F' AND age BETWEEN 30 AND 60 is checked row by row: 3 row(s) pass โ, 9 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+---------------+-----+---------+ | pname | age | ward | +---------------+-----+---------+ | Sunita Devi | 36 | General | | Harpreet Kaur | 47 | Private | | Anita Das | 58 | General | +---------------+-----+---------+ 3 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE bill BETWEEN 10000 AND 30000 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, bill โ picks the columns / calculates the values to show.
- ORDER BY bill โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition bill BETWEEN 10000 AND 30000 is checked row by row: 4 row(s) pass โ, 8 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+---------------+----------+ | pname | bill | +---------------+----------+ | Ramesh Gupta | 12500.00 | | Harpreet Kaur | 15200.00 | | Aarav Singh | 18000.00 | | Kavita Rao | 21500.00 | +---------------+----------+ 4 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- 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.
- 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.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+----------+-----------+----------+-----------+----------+ | Patients | Total | Avg_Bill | Max_Bill | Min_Bill | +----------+-----------+----------+-----------+----------+ | 12 | 384100.00 | 32008.33 | 120000.00 | 3600.00 | +----------+-----------+----------+-----------+----------+ 1 row in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- GROUP BY ward โ makes groups: rows with the same ward go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; SUM() adds the values.
- ORDER BY Total_Bill DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same ward are put in one group โ 4 group(s).
| ward | rows_in_group |
|---|---|
| Children | 2 |
| General | 4 |
| ICU | 2 |
| Private | 4 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+----------+----------+------------+ | ward | Patients | Total_Bill | +----------+----------+------------+ | ICU | 2 | 216000.00 | | Private | 4 | 113700.00 | | General | 4 | 32800.00 | | Children | 2 | 21600.00 | +----------+----------+------------+ 4 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- GROUP BY ward โ makes groups: rows with the same ward go into one group (one output row per group).
- HAVING AVG(bill) > 20000 โ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
- 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.
- Functions used: ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same ward are put in one group โ 4 group(s).
| ward | rows_in_group |
|---|---|
| Children | 2 |
| General | 4 |
| ICU | 2 |
| Private | 4 |
HAVING: Group condition AVG(bill) > 20000 โ 2 group(s) kept โ.
| ward | rows_in_group | |
|---|---|---|
| Children | 2 | โ |
| General | 4 | โ |
| ICU | 2 | โ |
| Private | 4 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+---------+-----------+ | ward | Avg_Bill | +---------+-----------+ | ICU | 108000.00 | | Private | 28425.00 | +---------+-----------+ 2 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- 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).
- 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.
- Functions used: MONTHNAME() gives the month name; COUNT(*) counts all rows.
- ORDER BY MONTH(admit_date) โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same MONTHNAME(admit_date), MONTH(admit_date) are put in one group โ 3 group(s).
| MONTHNAME(admit_date) | MONTH(admit_date) | rows_in_group |
|---|---|---|
| August | 8 | 4 |
| July | 7 | 4 |
| September | 9 | 4 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-----------+------------+ | Month | Admissions | +-----------+------------+ | July | 4 | | August | 4 | | September | 4 | +-----------+------------+ 3 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- 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.
- Functions used: DATEDIFF(d1, d2) gives days between two dates.
- ORDER BY Days_Admitted DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
- LIMIT 5 โ shows only the first 5 row(s) of the result.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts, LIMIT cuts โ final result:
+--------------+------------+---------------+ | pname | admit_date | Days_Admitted | +--------------+------------+---------------+ | Ramesh Gupta | 2026-07-04 | 88 | | Sunita Devi | 2026-07-09 | 83 | | Aarav Singh | 2026-07-12 | 80 | | Meena Kapoor | 2026-07-15 | 77 | | Imran Khan | 2026-08-02 | 59 | +--------------+------------+---------------+ 5 rows in set (0.00 sec)
SELECT pname, DAYNAME(admit_date) AS Admitted_On FROM patient WHERE ward = 'Private';
Fetches rows from patient that satisfy a condition.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE ward = 'Private' โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, DAYNAME(admit_date) AS Admitted_On โ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
- Functions used: DAYNAME() gives the weekday name.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition ward = 'Private' is checked row by row: 4 row(s) pass โ, 8 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+---------------+-------------+ | pname | Admitted_On | +---------------+-------------+ | Kavita Rao | Wednesday | | Harpreet Kaur | Tuesday | | Vikas Jain | Wednesday | | Rohit Mehra | Monday | +---------------+-------------+ 4 rows in set (0.00 sec)
UPDATE patient SET bill = bill * 0.90 WHERE age < 18;
Changes existing data in table patient.
- UPDATE patient โ picks the table.
- WHERE age < 18 โ finds only the rows that match.
- SET bill = bill * 0.90 โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE age < 18 โ 2 row(s) matched.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 |
AFTER: The matched rows now have the new values (highlighted).
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | 3240.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 |
SELECT pname, age, bill FROM patient WHERE age < 18;
Fetches rows from patient that satisfy a condition.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE age < 18 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, age, bill โ picks the columns / calculates the values to show.
FROM: MySQL opens table patient - all 12 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | 3240.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 |
WHERE: Condition age < 18 is checked row by row: 2 row(s) pass โ, 10 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | 3240.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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+-----+----------+ | pname | age | bill | +-------------+-----+----------+ | Aarav Singh | 8 | 16200.00 | | Neha Bansal | 5 | 3240.00 | +-------------+-----+----------+ 2 rows in set (0.00 sec)
UPDATE patient SET ward = 'General' WHERE pid = 106;
Changes existing data in table patient.
- UPDATE patient โ picks the table.
- WHERE pid = 106 โ finds only the rows that match.
- SET ward = 'General' โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE pid = 106 โ 1 row(s) matched.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | 3240.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 |
AFTER: The matched rows now have the new values (highlighted).
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | General | 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 | 3240.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 |
DELETE FROM patient WHERE pid = 105;
Removes rows from table patient.
- FROM patient โ picks the table.
- WHERE pid = 105 โ finds the matching rows.
- Those rows are removed permanently โ "Query OK, n rows affected".
FIND: WHERE pid = 105 โ 1 row(s) matched.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.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 | General | 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 | 3240.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 |
AFTER: The matched rows are gone โ 11 row(s) left.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
SELECT COUNT(*) AS Remaining_Patients FROM patient;
Fetches the summary values from patient.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- 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.
- Functions used: COUNT(*) counts all rows.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+--------------------+ | Remaining_Patients | +--------------------+ | 11 | +--------------------+ 1 row in set (0.00 sec)
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.
- FROM appointment a, patient p, doctor d โ takes the tables together (every row of one with every row of the other - Cartesian product).
- 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.
- SELECT a.app_id, p.pname, d.dname, d.department, a.app_date โ picks the columns / calculates the values to show.
- ORDER BY a.app_date โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: The tables are joined: appointment a, patient p, doctor d โ 550 combined rows.
| app_id | pid | did | app_date | pid | pname | age | gender | disease | ward | admit_date | bill | did | dname | department | fee |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 104 | 1 | 2026-07-15 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 1 | Dr. A. Sharma | Cardiology | 1200 |
| 1 | 104 | 1 | 2026-07-15 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 2 | Dr. P. Nair | Orthopaedics | 900 |
| 1 | 104 | 1 | 2026-07-15 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 3 | Dr. S. Khan | General Medicine | 600 |
| 1 | 104 | 1 | 2026-07-15 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 4 | Dr. R. Iyer | Paediatrics | 700 |
| 1 | 104 | 1 | 2026-07-15 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 5 | Dr. M. Gill | Surgery | 1500 |
| 1 | 104 | 1 | 2026-07-15 | 102 | Sunita Devi | 36 | F | Fever | General | 2026-07-09 | 4200 | 1 | Dr. A. Sharma | Cardiology | 1200 |
| 1 | 104 | 1 | 2026-07-15 | 102 | Sunita Devi | 36 | F | Fever | General | 2026-07-09 | 4200 | 2 | Dr. P. Nair | Orthopaedics | 900 |
| 1 | 104 | 1 | 2026-07-15 | 102 | Sunita Devi | 36 | F | Fever | General | 2026-07-09 | 4200 | 3 | Dr. S. Khan | General Medicine | 600 |
| 1 | 104 | 1 | 2026-07-15 | 102 | Sunita Devi | 36 | F | Fever | General | 2026-07-09 | 4200 | 4 | Dr. R. Iyer | Paediatrics | 700 |
| 1 | 104 | 1 | 2026-07-15 | 102 | Sunita Devi | 36 | F | Fever | General | 2026-07-09 | 4200 | 5 | Dr. M. Gill | Surgery | 1500 |
| 1 | 104 | 1 | 2026-07-15 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 1 | Dr. A. Sharma | Cardiology | 1200 |
| 1 | 104 | 1 | 2026-07-15 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 2 | Dr. P. Nair | Orthopaedics | 900 |
| 1 | 104 | 1 | 2026-07-15 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 3 | Dr. S. Khan | General Medicine | 600 |
| 1 | 104 | 1 | 2026-07-15 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 4 | Dr. R. Iyer | Paediatrics | 700 |
WHERE: Only the combined rows where a.pid = p.pid AND a.did = d.did is TRUE are kept โ 9 row(s).
| app_id | pid | did | app_date | pid | pname | age | gender | disease | ward | admit_date | bill | did | dname | department | fee |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 104 | 1 | 2026-07-15 | 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000 | 1 | Dr. A. Sharma | Cardiology | 1200 |
| 2 | 110 | 1 | 2026-09-06 | 110 | Suresh Yadav | 70 | M | Heart Disease | ICU | 2026-09-06 | 120000 | 1 | Dr. A. Sharma | Cardiology | 1200 |
| 3 | 103 | 2 | 2026-07-12 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 2 | Dr. P. Nair | Orthopaedics | 900 |
| 4 | 112 | 2 | 2026-09-21 | 112 | Rohit Mehra | 25 | M | Fracture | Private | 2026-09-21 | 32000 | 2 | Dr. P. Nair | Orthopaedics | 900 |
| 5 | 101 | 3 | 2026-07-04 | 101 | Ramesh Gupta | 54 | M | Diabetes | General | 2026-07-04 | 12500 | 3 | Dr. S. Khan | General Medicine | 600 |
| 7 | 111 | 3 | 2026-09-14 | 111 | Anita Das | 58 | F | Typhoid | General | 2026-09-14 | 8300 | 3 | Dr. S. Khan | General Medicine | 600 |
| 8 | 109 | 4 | 2026-09-01 | 109 | Neha Bansal | 5 | F | Fever | Children | 2026-09-01 | 3240 | 4 | Dr. R. Iyer | Paediatrics | 700 |
| 9 | 103 | 4 | 2026-07-13 | 103 | Aarav Singh | 8 | M | Fracture | Children | 2026-07-12 | 16200 | 4 | Dr. R. Iyer | Paediatrics | 700 |
| 10 | 108 | 5 | 2026-08-19 | 108 | Vikas Jain | 33 | M | Appendicitis | Private | 2026-08-19 | 45000 | 5 | Dr. M. Gill | Surgery | 1500 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------+--------------+---------------+------------------+------------+ | app_id | pname | dname | department | app_date | +--------+--------------+---------------+------------------+------------+ | 5 | Ramesh Gupta | Dr. S. Khan | General Medicine | 2026-07-04 | | 3 | Aarav Singh | Dr. P. Nair | Orthopaedics | 2026-07-12 | | 9 | Aarav Singh | Dr. R. Iyer | Paediatrics | 2026-07-13 | | 1 | Meena Kapoor | Dr. A. Sharma | Cardiology | 2026-07-15 | | 10 | Vikas Jain | Dr. M. Gill | Surgery | 2026-08-19 | | 8 | Neha Bansal | Dr. R. Iyer | Paediatrics | 2026-09-01 | | 2 | Suresh Yadav | Dr. A. Sharma | Cardiology | 2026-09-06 | | 7 | Anita Das | Dr. S. Khan | General Medicine | 2026-09-14 | | 4 | Rohit Mehra | Dr. P. Nair | Orthopaedics | 2026-09-21 | +--------+--------------+---------------+------------------+------------+ 9 rows in set (0.00 sec)
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.
- FROM doctor d, appointment a โ takes the tables together (every row of one with every row of the other - Cartesian product).
- WHERE d.did = a.did โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY Income DESC, d.dname โ sorts the result rows in descending (big โ small / Z โ A) order - the 2nd column breaks ties.
FROM: The tables are joined: doctor d, appointment a โ 50 combined rows.
| did | dname | department | fee | app_id | pid | did | app_date |
|---|---|---|---|---|---|---|---|
| 1 | Dr. A. Sharma | Cardiology | 1200 | 1 | 104 | 1 | 2026-07-15 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 2 | 110 | 1 | 2026-09-06 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 3 | 103 | 2 | 2026-07-12 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 4 | 112 | 2 | 2026-09-21 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 5 | 101 | 3 | 2026-07-04 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 6 | 105 | 3 | 2026-08-02 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 7 | 111 | 3 | 2026-09-14 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 8 | 109 | 4 | 2026-09-01 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 9 | 103 | 4 | 2026-07-13 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 10 | 108 | 5 | 2026-08-19 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 1 | 104 | 1 | 2026-07-15 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 2 | 110 | 1 | 2026-09-06 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 3 | 103 | 2 | 2026-07-12 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 4 | 112 | 2 | 2026-09-21 |
WHERE: Only the combined rows where d.did = a.did is TRUE are kept โ 10 row(s).
| did | dname | department | fee | app_id | pid | did | app_date |
|---|---|---|---|---|---|---|---|
| 1 | Dr. A. Sharma | Cardiology | 1200 | 1 | 104 | 1 | 2026-07-15 |
| 1 | Dr. A. Sharma | Cardiology | 1200 | 2 | 110 | 1 | 2026-09-06 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 3 | 103 | 2 | 2026-07-12 |
| 2 | Dr. P. Nair | Orthopaedics | 900 | 4 | 112 | 2 | 2026-09-21 |
| 3 | Dr. S. Khan | General Medicine | 600 | 5 | 101 | 3 | 2026-07-04 |
| 3 | Dr. S. Khan | General Medicine | 600 | 6 | 105 | 3 | 2026-08-02 |
| 3 | Dr. S. Khan | General Medicine | 600 | 7 | 111 | 3 | 2026-09-14 |
| 4 | Dr. R. Iyer | Paediatrics | 700 | 8 | 109 | 4 | 2026-09-01 |
| 4 | Dr. R. Iyer | Paediatrics | 700 | 9 | 103 | 4 | 2026-07-13 |
| 5 | Dr. M. Gill | Surgery | 1500 | 10 | 108 | 5 | 2026-08-19 |
GROUP BY: Rows with the same d.dname, d.fee are put in one group โ 5 group(s).
| dname | fee | rows_in_group |
|---|---|---|
| Dr. A. Sharma | 1200 | 2 |
| Dr. M. Gill | 1500 | 1 |
| Dr. P. Nair | 900 | 2 |
| Dr. R. Iyer | 700 | 2 |
| Dr. S. Khan | 600 | 3 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+---------------+--------------+--------+ | dname | Appointments | Income | +---------------+--------------+--------+ | Dr. A. Sharma | 2 | 2400 | | Dr. P. Nair | 2 | 1800 | | Dr. S. Khan | 3 | 1800 | | Dr. M. Gill | 1 | 1500 | | Dr. R. Iyer | 2 | 1400 | +---------------+--------------+--------+ 5 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- GROUP BY disease โ makes groups: rows with the same disease go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY Cases DESC, disease โ sorts the result rows in descending (big โ small / Z โ A) order - the 2nd column breaks ties.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
GROUP BY: Rows with the same disease are put in one group โ 7 group(s).
| disease | rows_in_group |
|---|---|
| Appendicitis | 1 |
| Dengue | 1 |
| Diabetes | 2 |
| Fever | 2 |
| Fracture | 2 |
| Heart Disease | 2 |
| Typhoid | 1 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+---------------+-------+ | disease | Cases | +---------------+-------+ | Diabetes | 2 | | Fever | 2 | | Fracture | 2 | | Heart Disease | 2 | | Appendicitis | 1 | | Dengue | 1 | | Typhoid | 1 | +---------------+-------+ 7 rows in set (0.00 sec)
SELECT gender, COUNT(*) AS Patients, ROUND(AVG(age),1) AS Avg_Age FROM patient GROUP BY gender;
Fetches rows from patient, grouped by gender.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- GROUP BY gender โ makes groups: rows with the same gender go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
GROUP BY: Rows with the same gender are put in one group โ 2 group(s).
| gender | rows_in_group |
|---|---|
| F | 6 |
| M | 5 |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+----------+---------+ | gender | Patients | Avg_Age | +--------+----------+---------+ | F | 6 | 39.5 | | M | 5 | 38.0 | +--------+----------+---------+ 2 rows in set (0.00 sec)
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.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
WHERE: Condition ward = 'ICU' is checked row by row: 2 row(s) pass โ, 9 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | โ |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | โ |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 | โ |
SELECT * FROM icu_patients;
Fetches rows from icu_patients.
- FROM icu_patients โ MySQL first opens table icu_patients and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE bill > (SELECT AVG(bill) FROM patient) โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT pname, bill โ picks the columns / calculates the values to show.
- Functions used: AVG() finds the average.
- ORDER BY bill DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
WHERE: Condition bill > (SELECT AVG(bill) FROM patient) is checked row by row: 3 row(s) pass โ, 8 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | โ |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | โ |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row; ORDER BY sorts โ final result:
+--------------+-----------+ | pname | bill | +--------------+-----------+ | Suresh Yadav | 120000.00 | | Meena Kapoor | 96000.00 | | Vikas Jain | 45000.00 | +--------------+-----------+ 3 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- 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.
- SELECT pname, age โ picks the columns / calculates the values to show.
- Functions used: MIN() finds the smallest value; MAX() finds the largest value.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
WHERE: Condition age = (SELECT MIN(age) FROM patient) OR age = (SELECT MAX(age) FROM patient) is checked row by row: 2 row(s) pass โ, 9 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | โ |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | โ |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+--------------+-----+ | pname | age | +--------------+-----+ | Neha Bansal | 5 | | Suresh Yadav | 70 | +--------------+-----+ 2 rows in set (0.00 sec)
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.
- FROM doctor โ MySQL first opens table doctor and looks at all its rows.
- 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.
- SELECT dname, department โ picks the columns / calculates the values to show.
FROM: MySQL opens table doctor - all 5 rows are taken.
| did | dname | department | fee |
|---|---|---|---|
| 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 |
WHERE: Condition did NOT IN (SELECT did FROM appointment WHERE app_date >= '2026-09-01') is checked row by row: 1 row(s) pass โ, 4 fail โ.
| did | dname | department | fee | |
|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+------------+ | dname | department | +-------------+------------+ | Dr. M. Gill | Surgery | +-------------+------------+ 1 row in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE ward IN ('ICU', 'Private') โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: UPPER() changes text to capitals; CONCAT() joins texts together; ROUND(x, d) rounds x to d decimal places.
- ORDER BY bill DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
WHERE: Condition ward IN ('ICU', 'Private') is checked row by row: 5 row(s) pass โ, 6 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | โ |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | โ |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+---------------+------------+------------------+ | Patient | Age_Gender | Bill_in_Thousand | +---------------+------------+------------------+ | SURESH YADAV | 70 yrs / M | 120.0 | | MEENA KAPOOR | 62 yrs / F | 96.0 | | VIKAS JAIN | 33 yrs / M | 45.0 | | ROHIT MEHRA | 25 yrs / M | 32.0 | | HARPREET KAUR | 47 yrs / F | 15.2 | +---------------+------------+------------------+ 5 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- GROUP BY ward โ makes groups: rows with the same ward go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; SUM() adds the values.
- ORDER BY Revenue_Percent DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
GROUP BY: Rows with the same ward are put in one group โ 4 group(s).
| ward | rows_in_group |
|---|---|
| Children | 2 |
| General | 4 |
| ICU | 2 |
| Private | 3 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+----------+----------+-----------------+ | ward | Patients | Revenue_Percent | +----------+----------+-----------------+ | ICU | 2 | 57.7 | | Private | 3 | 24.6 | | General | 4 | 12.4 | | Children | 2 | 5.2 | +----------+----------+-----------------+ 4 rows in set (0.00 sec)
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.
- FROM patient โ MySQL first opens table patient and looks at all its rows.
- WHERE LENGTH(pname) > 11 โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: LEFT(text, n) takes n characters from the left; LENGTH() counts characters.
FROM: MySQL opens table patient - all 11 rows are taken.
| pid | pname | age | gender | disease | ward | admit_date | bill |
|---|---|---|---|---|---|---|---|
| 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 | 16200.00 |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 |
WHERE: Condition LENGTH(pname) > 11 is checked row by row: 4 row(s) pass โ, 7 fail โ.
| pid | pname | age | gender | disease | ward | admit_date | bill | |
|---|---|---|---|---|---|---|---|---|
| 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 | 16200.00 | โ |
| 104 | Meena Kapoor | 62 | F | Heart Disease | ICU | 2026-07-15 | 96000.00 | โ |
| 106 | Kavita Rao | 29 | F | Dengue | General | 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 | 3240.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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+------------+-------------+ | First_Name | Name_Length | +------------+-------------+ | Ramesh | 12 | | Meena | 12 | | Harpreet | 13 | | Suresh | 12 | +------------+-------------+ 4 rows in set (0.00 sec)
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.
Employee Payroll Database (SQL)
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
๐ฏ Objectives
- Use arithmetic expressions in SELECT
- Apply GROUP BY with HAVING
- Alter a table and update rows conditionally
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
dept | TABLE | deptno INT PK, dname VARCHAR(15), location VARCHAR(15) |
employee | TABLE | empno INT PK, ename VARCHAR(30), deptno INT, designation VARCHAR(20), basic INT, doj DATE, mobile CHAR(10), bonus INT DEFAULT 0 |
-- =====================================================================
-- 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;
mysql> DROP DATABASE IF EXISTS payroll_db;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE DATABASE payroll_db;
Query OK, 1 row affected (0.00 sec)
mysql> USE payroll_db;
Database changed
mysql> CREATE TABLE dept (deptno INT PRIMARY KEY, dname VARCHAR(15), location VARCHAR(15));
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE employee (
-> empno INT PRIMARY KEY, ename VARCHAR(30) NOT NULL, deptno INT, designation VARCHAR(20),
-> basic INT, doj DATE, mobile CHAR(10));
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO dept VALUES (10,'Accounts','Delhi'), (20,'Sales','Mumbai'), (30,'IT','Bengaluru'), (40,'HR','Delhi'), (50,'Admin','Noida');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> 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');
Query OK, 12 rows affected (0.00 sec)
Records: 12 Duplicates: 0 Warnings: 0
mysql> 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;
+-------------+-------+----------+----------+---------+------------+
| ename | basic | DA | HRA | PF | Net_Salary |
+-------------+-------+----------+----------+---------+------------+
| Ritu Saxena | 82000 | 32800.00 | 16400.00 | 9840.00 | 121360.00 |
| Tarun Malik | 70000 | 28000.00 | 14000.00 | 8400.00 | 103600.00 |
| Rina Das | 60000 | 24000.00 | 12000.00 | 7200.00 | 88800.00 |
| Anil Sharma | 55000 | 22000.00 | 11000.00 | 6600.00 | 81400.00 |
| Lata Mishra | 52000 | 20800.00 | 10400.00 | 6240.00 | 76960.00 |
+-------------+-------+----------+----------+---------+------------+
5 rows in set (0.00 sec)
mysql> SELECT ename, ROUND((basic*1.48)*12) AS Annual_Net FROM employee WHERE designation = 'Developer';
+-------------+------------+
| ename | Annual_Net |
+-------------+------------+
| Manoj Kumar | 852480 |
| Sakshi Jain | 799200 |
+-------------+------------+
2 rows in set (0.00 sec)
mysql> SELECT deptno, COUNT(*) AS Employees, ROUND(AVG(basic)) AS Avg_Basic, SUM(basic) AS Total_Basic FROM employee GROUP BY deptno;
+--------+-----------+-----------+-------------+
| deptno | Employees | Avg_Basic | Total_Basic |
+--------+-----------+-----------+-------------+
| 10 | 2 | 41500 | 83000 |
| 20 | 3 | 40667 | 122000 |
| 30 | 4 | 61250 | 245000 |
| 40 | 2 | 44000 | 88000 |
| 50 | 1 | 26000 | 26000 |
+--------+-----------+-----------+-------------+
5 rows in set (0.00 sec)
mysql> SELECT deptno, AVG(basic) AS Avg_Basic FROM employee GROUP BY deptno HAVING AVG(basic) > 45000;
+--------+------------+
| deptno | Avg_Basic |
+--------+------------+
| 30 | 61250.0000 |
+--------+------------+
1 row in set (0.00 sec)
mysql> SELECT designation, COUNT(*) AS Total FROM employee GROUP BY designation ORDER BY Total DESC, designation;
+-------------+-------+
| designation | Total |
+-------------+-------+
| Manager | 4 |
| Clerk | 2 |
| Developer | 2 |
| Executive | 2 |
| Officer | 1 |
| Team Lead | 1 |
+-------------+-------+
6 rows in set (0.00 sec)
mysql> SELECT MAX(basic) AS Highest, MIN(basic) AS Lowest, MAX(basic) - MIN(basic) AS Difference FROM employee;
+---------+--------+------------+
| Highest | Lowest | Difference |
+---------+--------+------------+
| 82000 | 26000 | 56000 |
+---------+--------+------------+
1 row in set (0.00 sec)
mysql> SELECT ename, doj, YEAR('2026-04-01') - YEAR(doj) AS Experience FROM employee ORDER BY doj LIMIT 6;
+-------------+------------+------------+
| ename | doj | Experience |
+-------------+------------+------------+
| Ritu Saxena | 2011-01-17 | 15 |
| Rina Das | 2012-11-05 | 14 |
| Lata Mishra | 2013-12-02 | 13 |
| Tarun Malik | 2014-08-18 | 12 |
| Anil Sharma | 2015-04-01 | 11 |
| Geeta Nair | 2017-09-09 | 9 |
+-------------+------------+------------+
6 rows in set (0.00 sec)
mysql> SELECT ename, doj FROM employee WHERE YEAR(doj) < 2016 ORDER BY doj;
+-------------+------------+
| ename | doj |
+-------------+------------+
| Ritu Saxena | 2011-01-17 |
| Rina Das | 2012-11-05 |
| Lata Mishra | 2013-12-02 |
| Tarun Malik | 2014-08-18 |
| Anil Sharma | 2015-04-01 |
+-------------+------------+
5 rows in set (0.00 sec)
mysql> SELECT YEAR(doj) AS Join_Year, COUNT(*) AS Joined FROM employee GROUP BY YEAR(doj) ORDER BY Join_Year;
+-----------+--------+
| Join_Year | Joined |
+-----------+--------+
| 2011 | 1 |
| 2012 | 1 |
| 2013 | 1 |
| 2014 | 1 |
| 2015 | 1 |
| 2017 | 1 |
| 2018 | 1 |
| 2019 | 1 |
| 2020 | 1 |
| 2021 | 1 |
| 2022 | 1 |
| 2023 | 1 |
+-----------+--------+
12 rows in set (0.00 sec)
mysql> ALTER TABLE employee ADD bonus INT DEFAULT 0;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> UPDATE employee SET bonus = basic * 0.10 WHERE designation = 'Manager';
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> SELECT ename, designation, bonus FROM employee WHERE bonus > 0;
+-------------+-------------+-------+
| ename | designation | bonus |
+-------------+-------------+-------+
| Anil Sharma | Manager | 5500 |
| Rina Das | Manager | 6000 |
| Lata Mishra | Manager | 5200 |
| Ritu Saxena | Manager | 8200 |
+-------------+-------------+-------+
4 rows in set (0.00 sec)
mysql> UPDATE employee SET basic = basic * 1.05 WHERE deptno = 30;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> SELECT ename, basic FROM employee WHERE deptno = 30;
+-------------+-------+
| ename | basic |
+-------------+-------+
| Manoj Kumar | 50400 |
| Sakshi Jain | 47250 |
| Tarun Malik | 73500 |
| Ritu Saxena | 86100 |
+-------------+-------+
4 rows in set (0.00 sec)
mysql> 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;
+--------------+----------+-----------+-------+
| ename | dname | location | basic |
+--------------+----------+-----------+-------+
| Manoj Kumar | IT | Bengaluru | 50400 |
| Ritu Saxena | IT | Bengaluru | 86100 |
| Sakshi Jain | IT | Bengaluru | 47250 |
| Tarun Malik | IT | Bengaluru | 73500 |
| Anil Sharma | Accounts | Delhi | 55000 |
| Geeta Nair | HR | Delhi | 36000 |
| Lata Mishra | HR | Delhi | 52000 |
| Poonam Arora | Accounts | Delhi | 28000 |
| Deepak Verma | Sales | Mumbai | 32000 |
| Faisal Ali | Sales | Mumbai | 30000 |
| Rina Das | Sales | Mumbai | 60000 |
| Kunal Bose | Admin | Noida | 26000 |
+--------------+----------+-----------+-------+
12 rows in set (0.00 sec)
mysql> 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;
+-----------+-------+-------------+
| location | Staff | Salary_Bill |
+-----------+-------+-------------+
| Bengaluru | 4 | 257250 |
| Delhi | 4 | 171000 |
| Mumbai | 3 | 122000 |
| Noida | 1 | 26000 |
+-----------+-------+-------------+
4 rows in set (0.00 sec)
mysql> SELECT d.dname, e.ename AS Manager FROM employee e, dept d WHERE e.deptno = d.deptno AND e.designation = 'Manager';
+----------+-------------+
| dname | Manager |
+----------+-------------+
| Accounts | Anil Sharma |
| Sales | Rina Das |
| HR | Lata Mishra |
| IT | Ritu Saxena |
+----------+-------------+
4 rows in set (0.00 sec)
mysql> SELECT ename FROM employee WHERE ename LIKE '%a';
+--------------+
| ename |
+--------------+
| Anil Sharma |
| Poonam Arora |
| Deepak Verma |
| Lata Mishra |
| Ritu Saxena |
+--------------+
5 rows in set (0.00 sec)
mysql> SELECT ename, designation FROM employee WHERE designation IN ('Clerk','Officer');
+--------------+-------------+
| ename | designation |
+--------------+-------------+
| Poonam Arora | Clerk |
| Geeta Nair | Officer |
| Kunal Bose | Clerk |
+--------------+-------------+
3 rows in set (0.00 sec)
mysql> SELECT ename FROM employee WHERE mobile IS NULL;
+--------------+
| ename |
+--------------+
| Poonam Arora |
| Sakshi Jain |
| Kunal Bose |
+--------------+
3 rows in set (0.00 sec)
mysql> SELECT DISTINCT designation FROM employee ORDER BY designation;
+-------------+
| designation |
+-------------+
| Clerk |
| Developer |
| Executive |
| Manager |
| Officer |
| Team Lead |
+-------------+
6 rows in set (0.00 sec)
mysql> SELECT ename, basic FROM employee WHERE basic = (SELECT MAX(basic) FROM employee);
+-------------+-------+
| ename | basic |
+-------------+-------+
| Ritu Saxena | 86100 |
+-------------+-------+
1 row in set (0.00 sec)
mysql> 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;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM salary_register ORDER BY Gross_Pay DESC;
+-------+--------------+----------+-------+----------+----------+----------+-----------+
| empno | ename | dname | basic | DA | HRA | PF | Gross_Pay |
+-------+--------------+----------+-------+----------+----------+----------+-----------+
| 12 | Ritu Saxena | IT | 86100 | 34440.00 | 17220.00 | 10332.00 | 135628.00 |
| 7 | Tarun Malik | IT | 73500 | 29400.00 | 14700.00 | 8820.00 | 108780.00 |
| 4 | Rina Das | Sales | 60000 | 24000.00 | 12000.00 | 7200.00 | 94800.00 |
| 1 | Anil Sharma | Accounts | 55000 | 22000.00 | 11000.00 | 6600.00 | 86900.00 |
| 10 | Lata Mishra | HR | 52000 | 20800.00 | 10400.00 | 6240.00 | 82160.00 |
| 5 | Manoj Kumar | IT | 50400 | 20160.00 | 10080.00 | 6048.00 | 74592.00 |
| 6 | Sakshi Jain | IT | 47250 | 18900.00 | 9450.00 | 5670.00 | 69930.00 |
| 8 | Geeta Nair | HR | 36000 | 14400.00 | 7200.00 | 4320.00 | 53280.00 |
| 3 | Deepak Verma | Sales | 32000 | 12800.00 | 6400.00 | 3840.00 | 47360.00 |
| 9 | Faisal Ali | Sales | 30000 | 12000.00 | 6000.00 | 3600.00 | 44400.00 |
| 2 | Poonam Arora | Accounts | 28000 | 11200.00 | 5600.00 | 3360.00 | 41440.00 |
| 11 | Kunal Bose | Admin | 26000 | 10400.00 | 5200.00 | 3120.00 | 38480.00 |
+-------+--------------+----------+-------+----------+----------+----------+-----------+
12 rows in set (0.00 sec)
mysql> SELECT ename, basic
-> FROM employee
-> WHERE basic > (SELECT AVG(basic) FROM employee)
-> ORDER BY basic DESC;
+-------------+-------+
| ename | basic |
+-------------+-------+
| Ritu Saxena | 86100 |
| Tarun Malik | 73500 |
| Rina Das | 60000 |
| Anil Sharma | 55000 |
| Lata Mishra | 52000 |
| Manoj Kumar | 50400 |
+-------------+-------+
6 rows in set (0.00 sec)
mysql> SELECT dname
-> FROM dept
-> WHERE deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager');
+-------+
| dname |
+-------+
| Admin |
+-------+
1 row in set (0.00 sec)
mysql> 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;
+--------------+------------+-----------+-----------+
| Employee | Basic_Pay | Joined_In | Day |
+--------------+------------+-----------+-----------+
| ANIL SHARMA | Rs. 55,000 | April | Wednesday |
| GEETA NAIR | Rs. 36,000 | September | Saturday |
| LATA MISHRA | Rs. 52,000 | December | Monday |
| POONAM ARORA | Rs. 28,000 | July | Monday |
+--------------+------------+-----------+-----------+
4 rows in set (0.00 sec)
mysql> 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;
+-------------+-------+---------------+
| designation | Staff | Share_Percent |
+-------------+-------+---------------+
| Manager | 4 | 43.9 |
| Developer | 2 | 16.9 |
| Team Lead | 1 | 12.8 |
| Executive | 2 | 10.8 |
| Clerk | 2 | 9.4 |
| Officer | 1 | 6.2 |
+-------------+-------+---------------+
6 rows in set (0.00 sec)
mysql> 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;
+------------+--------------+
| First_Name | Mobile_Last4 |
+------------+--------------+
| Anil | 1111 |
| Deepak | 2222 |
| Rina | 3333 |
| Manoj | 4444 |
| Tarun | 6666 |
| Geeta | 7777 |
+------------+--------------+
6 rows in set (0.00 sec)
- Start
- Create payroll_db, dept and employee tables
- Insert department and employee rows
- Salary slip query with computed columns
- Department-wise aggregate reports
- ALTER TABLE and UPDATE bonus / increment
- Join and search queries
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Top 5 net salaries | Computed DA/HRA/PF columns | PASS |
| 2 | Dept head count | Counts per department | PASS |
| 3 | HAVING AVG(basic) > 45000 | Qualifying departments | PASS |
| 4 | Bonus 10 % to managers | Only managers get bonus | PASS |
| 5 | Experience > 10 years | Senior employees listed | PASS |
| 6 | 5 % increment for IT | IT basic pay increased | PASS |
| 7 | Join with dept | Employee with location | PASS |
| 8 | mobile IS NULL | Employees without mobile | PASS |
โ 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:
DROP DATABASE IF EXISTS payroll_db;
Deletes the database payroll_db completely (structure + data). It cannot be undone.
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".
USE payroll_db;
Selects the database payroll_db - all following commands work inside it.
- MySQL replies "Database changed".
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.
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.
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.
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.
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- 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.
- ORDER BY Net_Salary DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
- LIMIT 5 โ shows only the first 5 row(s) of the result.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts, LIMIT cuts โ final result:
+-------------+-------+----------+----------+---------+------------+ | ename | basic | DA | HRA | PF | Net_Salary | +-------------+-------+----------+----------+---------+------------+ | Ritu Saxena | 82000 | 32800.00 | 16400.00 | 9840.00 | 121360.00 | | Tarun Malik | 70000 | 28000.00 | 14000.00 | 8400.00 | 103600.00 | | Rina Das | 60000 | 24000.00 | 12000.00 | 7200.00 | 88800.00 | | Anil Sharma | 55000 | 22000.00 | 11000.00 | 6600.00 | 81400.00 | | Lata Mishra | 52000 | 20800.00 | 10400.00 | 6240.00 | 76960.00 | +-------------+-------+----------+----------+---------+------------+ 5 rows in set (0.00 sec)
SELECT ename, ROUND((basic*1.48)*12) AS Annual_Net FROM employee WHERE designation = 'Developer';
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE designation = 'Developer' โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- Functions used: ROUND(x, d) rounds x to d decimal places.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition designation = 'Developer' is checked row by row: 2 row(s) pass โ, 10 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | |
|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+------------+ | ename | Annual_Net | +-------------+------------+ | Manoj Kumar | 852480 | | Sakshi Jain | 799200 | +-------------+------------+ 2 rows in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- GROUP BY deptno โ makes groups: rows with the same deptno go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; AVG() finds the average; SUM() adds the values.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same deptno are put in one group โ 5 group(s).
| deptno | rows_in_group |
|---|---|
| 10 | 2 |
| 20 | 3 |
| 30 | 4 |
| 40 | 2 |
| 50 | 1 |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+-----------+-----------+-------------+ | deptno | Employees | Avg_Basic | Total_Basic | +--------+-----------+-----------+-------------+ | 10 | 2 | 41500 | 83000 | | 20 | 3 | 40667 | 122000 | | 30 | 4 | 61250 | 245000 | | 40 | 2 | 44000 | 88000 | | 50 | 1 | 26000 | 26000 | +--------+-----------+-----------+-------------+ 5 rows in set (0.00 sec)
SELECT deptno, AVG(basic) AS Avg_Basic FROM employee GROUP BY deptno HAVING AVG(basic) > 45000;
Fetches rows from employee, grouped by deptno.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- GROUP BY deptno โ makes groups: rows with the same deptno go into one group (one output row per group).
- HAVING AVG(basic) > 45000 โ keeps only the GROUPS that satisfy this condition (WHERE filters rows, HAVING filters groups).
- 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.
- Functions used: AVG() finds the average.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same deptno are put in one group โ 5 group(s).
| deptno | rows_in_group |
|---|---|
| 10 | 2 |
| 20 | 3 |
| 30 | 4 |
| 40 | 2 |
| 50 | 1 |
HAVING: Group condition AVG(basic) > 45000 โ 1 group(s) kept โ.
| deptno | rows_in_group | |
|---|---|---|
| 10 | 2 | โ |
| 20 | 3 | โ |
| 30 | 4 | โ |
| 40 | 2 | โ |
| 50 | 1 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------+------------+ | deptno | Avg_Basic | +--------+------------+ | 30 | 61250.0000 | +--------+------------+ 1 row in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- GROUP BY designation โ makes groups: rows with the same designation go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows.
- ORDER BY Total DESC, designation โ sorts the result rows in descending (big โ small / Z โ A) order - the 2nd column breaks ties.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same designation are put in one group โ 6 group(s).
| designation | rows_in_group |
|---|---|
| Clerk | 2 |
| Developer | 2 |
| Executive | 2 |
| Manager | 4 |
| Officer | 1 |
| Team Lead | 1 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-------------+-------+ | designation | Total | +-------------+-------+ | Manager | 4 | | Clerk | 2 | | Developer | 2 | | Executive | 2 | | Officer | 1 | | Team Lead | 1 | +-------------+-------+ 6 rows in set (0.00 sec)
SELECT MAX(basic) AS Highest, MIN(basic) AS Lowest, MAX(basic) - MIN(basic) AS Difference FROM employee;
Fetches the summary values from employee.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- 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.
- Functions used: MAX() finds the largest value; MIN() finds the smallest value.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+---------+--------+------------+ | Highest | Lowest | Difference | +---------+--------+------------+ | 82000 | 26000 | 56000 | +---------+--------+------------+ 1 row in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- 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.
- Functions used: YEAR() takes the year from a date.
- ORDER BY doj โ sorts the result rows in ascending (small โ big / A โ Z) order.
- LIMIT 6 โ shows only the first 6 row(s) of the result.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts, LIMIT cuts โ final result:
+-------------+------------+------------+ | ename | doj | Experience | +-------------+------------+------------+ | Ritu Saxena | 2011-01-17 | 15 | | Rina Das | 2012-11-05 | 14 | | Lata Mishra | 2013-12-02 | 13 | | Tarun Malik | 2014-08-18 | 12 | | Anil Sharma | 2015-04-01 | 11 | | Geeta Nair | 2017-09-09 | 9 | +-------------+------------+------------+ 6 rows in set (0.00 sec)
SELECT ename, doj FROM employee WHERE YEAR(doj) < 2016 ORDER BY doj;
Fetches rows from employee that satisfy a condition, in sorted order.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE YEAR(doj) < 2016 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, doj โ picks the columns / calculates the values to show.
- Functions used: YEAR() takes the year from a date.
- ORDER BY doj โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
WHERE: Condition YEAR(doj) < 2016 is checked row by row: 5 row(s) pass โ, 7 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | |
|---|---|---|---|---|---|---|---|
| 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 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-------------+------------+ | ename | doj | +-------------+------------+ | Ritu Saxena | 2011-01-17 | | Rina Das | 2012-11-05 | | Lata Mishra | 2013-12-02 | | Tarun Malik | 2014-08-18 | | Anil Sharma | 2015-04-01 | +-------------+------------+ 5 rows in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- GROUP BY YEAR(doj) โ makes groups: rows with the same YEAR(doj) go into one group (one output row per group).
- 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.
- Functions used: YEAR() takes the year from a date; COUNT(*) counts all rows.
- ORDER BY Join_Year โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile |
|---|---|---|---|---|---|---|
| 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 |
GROUP BY: Rows with the same YEAR(doj) are put in one group โ 12 group(s).
| YEAR(doj) | rows_in_group |
|---|---|
| 2011 | 1 |
| 2012 | 1 |
| 2013 | 1 |
| 2014 | 1 |
| 2015 | 1 |
| 2017 | 1 |
| 2018 | 1 |
| 2019 | 1 |
| 2020 | 1 |
| 2021 | 1 |
| 2022 | 1 |
| 2023 | 1 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-----------+--------+ | Join_Year | Joined | +-----------+--------+ | 2011 | 1 | | 2012 | 1 | | 2013 | 1 | | 2014 | 1 | | 2015 | 1 | | 2017 | 1 | | 2018 | 1 | | 2019 | 1 | | 2020 | 1 | | 2021 | 1 | | 2022 | 1 | | 2023 | 1 | +-----------+--------+ 12 rows in set (0.00 sec)
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.
UPDATE employee SET bonus = basic * 0.10 WHERE designation = 'Manager';
Changes existing data in table employee.
- UPDATE employee โ picks the table.
- WHERE designation = 'Manager' โ finds only the rows that match.
- SET bonus = basic * 0.10 โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE designation = 'Manager' โ 4 row(s) matched.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 0 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 0 | โ |
| 5 | Manoj Kumar | 30 | Developer | 48000 | 2020-06-22 | 9813344444 | 0 | |
| 6 | Sakshi Jain | 30 | Developer | 45000 | 2021-02-01 | NULL | 0 | |
| 7 | Tarun Malik | 30 | Team Lead | 70000 | 2014-08-18 | 9815566666 | 0 | |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 0 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | |
| 12 | Ritu Saxena | 30 | Manager | 82000 | 2011-01-17 | 9819900000 | 0 | โ |
AFTER: The matched rows now have the new values (highlighted).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 48000 | 2020-06-22 | 9813344444 | 0 | |
| 6 | Sakshi Jain | 30 | Developer | 45000 | 2021-02-01 | NULL | 0 | |
| 7 | Tarun Malik | 30 | Team Lead | 70000 | 2014-08-18 | 9815566666 | 0 | |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | |
| 12 | Ritu Saxena | 30 | Manager | 82000 | 2011-01-17 | 9819900000 | 8200 | โ |
SELECT ename, designation, bonus FROM employee WHERE bonus > 0;
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE bonus > 0 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, designation, bonus โ picks the columns / calculates the values to show.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 48000 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 45000 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 70000 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 82000 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition bonus > 0 is checked row by row: 4 row(s) pass โ, 8 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 48000 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 45000 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 70000 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 82000 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+-------------+-------+ | ename | designation | bonus | +-------------+-------------+-------+ | Anil Sharma | Manager | 5500 | | Rina Das | Manager | 6000 | | Lata Mishra | Manager | 5200 | | Ritu Saxena | Manager | 8200 | +-------------+-------------+-------+ 4 rows in set (0.00 sec)
UPDATE employee SET basic = basic * 1.05 WHERE deptno = 30;
Changes existing data in table employee.
- UPDATE employee โ picks the table.
- WHERE deptno = 30 โ finds only the rows that match.
- SET basic = basic * 1.05 โ writes the new value(s) in those rows.
- MySQL reports "Rows matched / Changed".
FIND: WHERE deptno = 30 โ 4 row(s) matched.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | |
| 5 | Manoj Kumar | 30 | Developer | 48000 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 45000 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 70000 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | |
| 12 | Ritu Saxena | 30 | Manager | 82000 | 2011-01-17 | 9819900000 | 8200 | โ |
AFTER: The matched rows now have the new values (highlighted).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
SELECT ename, basic FROM employee WHERE deptno = 30;
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE deptno = 30 โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, basic โ picks the columns / calculates the values to show.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition deptno = 30 is checked row by row: 4 row(s) pass โ, 8 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+-------------+-------+ | ename | basic | +-------------+-------+ | Manoj Kumar | 50400 | | Sakshi Jain | 47250 | | Tarun Malik | 73500 | | Ritu Saxena | 86100 | +-------------+-------+ 4 rows in set (0.00 sec)
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.
- 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.ename, d.dname, d.location, e.basic โ picks the columns / calculates the values to show.
- ORDER BY d.location, e.ename โ sorts the result rows in ascending (small โ big / A โ Z) order - the 2nd column breaks ties.
FROM: The tables are joined: employee e, dept d โ 60 combined rows.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 20 | Sales | Mumbai |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 30 | IT | Bengaluru |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 40 | HR | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 50 | Admin | Noida |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 20 | Sales | Mumbai |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 30 | IT | Bengaluru |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 40 | HR | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 50 | Admin | Noida |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 30 | IT | Bengaluru |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 40 | HR | Delhi |
WHERE: Only the combined rows where e.deptno = d.deptno is TRUE are kept โ 12 row(s).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | 20 | Sales | Mumbai |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | 30 | IT | Bengaluru |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | 30 | IT | Bengaluru |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | 30 | IT | Bengaluru |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | 40 | HR | Delhi |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | 20 | Sales | Mumbai |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | 40 | HR | Delhi |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | 50 | Admin | Noida |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | 30 | IT | Bengaluru |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------------+----------+-----------+-------+ | ename | dname | location | basic | +--------------+----------+-----------+-------+ | Manoj Kumar | IT | Bengaluru | 50400 | | Ritu Saxena | IT | Bengaluru | 86100 | | Sakshi Jain | IT | Bengaluru | 47250 | | Tarun Malik | IT | Bengaluru | 73500 | | Anil Sharma | Accounts | Delhi | 55000 | | Geeta Nair | HR | Delhi | 36000 | | Lata Mishra | HR | Delhi | 52000 | | Poonam Arora | Accounts | Delhi | 28000 | | Deepak Verma | Sales | Mumbai | 32000 | | Faisal Ali | Sales | Mumbai | 30000 | | Rina Das | Sales | Mumbai | 60000 | | Kunal Bose | Admin | Noida | 26000 | +--------------+----------+-----------+-------+ 12 rows in set (0.00 sec)
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.
- 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.
- GROUP BY d.location โ makes groups: rows with the same d.location go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; SUM() adds the values.
FROM: The tables are joined: employee e, dept d โ 60 combined rows.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 20 | Sales | Mumbai |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 30 | IT | Bengaluru |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 40 | HR | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 50 | Admin | Noida |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 20 | Sales | Mumbai |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 30 | IT | Bengaluru |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 40 | HR | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 50 | Admin | Noida |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 30 | IT | Bengaluru |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 40 | HR | Delhi |
WHERE: Only the combined rows where e.deptno = d.deptno is TRUE are kept โ 12 row(s).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | 20 | Sales | Mumbai |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | 30 | IT | Bengaluru |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | 30 | IT | Bengaluru |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | 30 | IT | Bengaluru |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | 40 | HR | Delhi |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | 20 | Sales | Mumbai |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | 40 | HR | Delhi |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | 50 | Admin | Noida |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | 30 | IT | Bengaluru |
GROUP BY: Rows with the same d.location are put in one group โ 4 group(s).
| location | rows_in_group |
|---|---|
| Bengaluru | 4 |
| Delhi | 4 |
| Mumbai | 3 |
| Noida | 1 |
RESULT: SELECT picks / calculates the columns โ final result:
+-----------+-------+-------------+ | location | Staff | Salary_Bill | +-----------+-------+-------------+ | Bengaluru | 4 | 257250 | | Delhi | 4 | 171000 | | Mumbai | 3 | 122000 | | Noida | 1 | 26000 | +-----------+-------+-------------+ 4 rows in set (0.00 sec)
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.
- 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 AND e.designation = 'Manager' โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT d.dname, e.ename AS Manager โ picks the columns / calculates the values to show; AS gives a heading (alias) to a column.
FROM: The tables are joined: employee e, dept d โ 60 combined rows.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 20 | Sales | Mumbai |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 30 | IT | Bengaluru |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 40 | HR | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 50 | Admin | Noida |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 20 | Sales | Mumbai |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 30 | IT | Bengaluru |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 40 | HR | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 50 | Admin | Noida |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 30 | IT | Bengaluru |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 40 | HR | Delhi |
WHERE: Only the combined rows where e.deptno = d.deptno AND e.designation = 'Manager' is TRUE are kept โ 4 row(s).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | 20 | Sales | Mumbai |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | 40 | HR | Delhi |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | 30 | IT | Bengaluru |
RESULT: SELECT picks / calculates the columns โ final result:
+----------+-------------+ | dname | Manager | +----------+-------------+ | Accounts | Anil Sharma | | Sales | Rina Das | | HR | Lata Mishra | | IT | Ritu Saxena | +----------+-------------+ 4 rows in set (0.00 sec)
SELECT ename FROM employee WHERE ename LIKE '%a';
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE ename LIKE '%a' (ends with "a") โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename โ picks the columns / calculates the values to show.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition ename LIKE '%a' is checked row by row: 5 row(s) pass โ, 7 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------------+ | ename | +--------------+ | Anil Sharma | | Poonam Arora | | Deepak Verma | | Lata Mishra | | Ritu Saxena | +--------------+ 5 rows in set (0.00 sec)
SELECT ename, designation FROM employee WHERE designation IN ('Clerk','Officer');Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE designation IN ('Clerk','Officer') โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, designation โ picks the columns / calculates the values to show.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition designation IN ('Clerk','Officer') is checked row by row: 3 row(s) pass โ, 9 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------------+-------------+ | ename | designation | +--------------+-------------+ | Poonam Arora | Clerk | | Geeta Nair | Officer | | Kunal Bose | Clerk | +--------------+-------------+ 3 rows in set (0.00 sec)
SELECT ename FROM employee WHERE mobile IS NULL;
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE mobile IS NULL โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename โ picks the columns / calculates the values to show.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition mobile IS NULL is checked row by row: 3 row(s) pass โ, 9 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns โ final result:
+--------------+ | ename | +--------------+ | Poonam Arora | | Sakshi Jain | | Kunal Bose | +--------------+ 3 rows in set (0.00 sec)
SELECT DISTINCT designation FROM employee ORDER BY designation;
Fetches rows from employee, in sorted order.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- SELECT designation โ picks the columns / calculates the values to show.
- DISTINCT โ removes repeated rows, so each value appears only once.
- ORDER BY designation โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
RESULT: SELECT picks / calculates the columns; DISTINCT removes repeats, ORDER BY sorts โ final result:
+-------------+ | designation | +-------------+ | Clerk | | Developer | | Executive | | Manager | | Officer | | Team Lead | +-------------+ 6 rows in set (0.00 sec)
SELECT ename, basic FROM employee WHERE basic = (SELECT MAX(basic) FROM employee);
Fetches rows from employee that satisfy a condition.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE basic = (SELECT MAX(basic) FROM employee) โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, basic โ picks the columns / calculates the values to show.
- Functions used: MAX() finds the largest value.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition basic = (SELECT MAX(basic) FROM employee) is checked row by row: 1 row(s) pass โ, 11 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row โ final result:
+-------------+-------+ | ename | basic | +-------------+-------+ | Ritu Saxena | 86100 | +-------------+-------+ 1 row in set (0.00 sec)
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.
FROM: The tables are joined: employee e, dept d โ 60 combined rows.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 20 | Sales | Mumbai |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 30 | IT | Bengaluru |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 40 | HR | Delhi |
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 50 | Admin | Noida |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 20 | Sales | Mumbai |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 30 | IT | Bengaluru |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 40 | HR | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 50 | Admin | Noida |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 30 | IT | Bengaluru |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 40 | HR | Delhi |
WHERE: Only the combined rows where e.deptno = d.deptno is TRUE are kept โ 12 row(s).
| empno | ename | deptno | designation | basic | doj | mobile | bonus | deptno | dname | location |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | 10 | Accounts | Delhi |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | 10 | Accounts | Delhi |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | 20 | Sales | Mumbai |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | 20 | Sales | Mumbai |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | 30 | IT | Bengaluru |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | 30 | IT | Bengaluru |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | 30 | IT | Bengaluru |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | 40 | HR | Delhi |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | 20 | Sales | Mumbai |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | 40 | HR | Delhi |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | 50 | Admin | Noida |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | 30 | IT | Bengaluru |
SELECT * FROM salary_register ORDER BY Gross_Pay DESC;
Fetches rows from salary_register, in sorted order.
- FROM salary_register โ MySQL first opens table salary_register and looks at all its rows.
- SELECT all the columns (*) โ picks the columns / calculates the values to show.
- ORDER BY Gross_Pay DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE basic > (SELECT AVG(basic) FROM employee) โ checks this condition for every row; only the rows where it is TRUE are kept.
- SELECT ename, basic โ picks the columns / calculates the values to show.
- Functions used: AVG() finds the average.
- ORDER BY basic DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition basic > (SELECT AVG(basic) FROM employee) is checked row by row: 6 row(s) pass โ, 6 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns; the aggregate function squeezes all kept rows into ONE row; ORDER BY sorts โ final result:
+-------------+-------+ | ename | basic | +-------------+-------+ | Ritu Saxena | 86100 | | Tarun Malik | 73500 | | Rina Das | 60000 | | Anil Sharma | 55000 | | Lata Mishra | 52000 | | Manoj Kumar | 50400 | +-------------+-------+ 6 rows in set (0.00 sec)
SELECT dname FROM dept WHERE deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager');
Fetches rows from dept that satisfy a condition.
- FROM dept โ MySQL first opens table dept and looks at all its rows.
- 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.
- SELECT dname โ picks the columns / calculates the values to show.
FROM: MySQL opens table dept - all 5 rows are taken.
| deptno | dname | location |
|---|---|---|
| 10 | Accounts | Delhi |
| 20 | Sales | Mumbai |
| 30 | IT | Bengaluru |
| 40 | HR | Delhi |
| 50 | Admin | Noida |
WHERE: Condition deptno NOT IN (SELECT DISTINCT deptno FROM employee WHERE designation = 'Manager') is checked row by row: 1 row(s) pass โ, 4 fail โ.
| deptno | dname | location | |
|---|---|---|---|
| 10 | Accounts | Delhi | โ |
| 20 | Sales | Mumbai | โ |
| 30 | IT | Bengaluru | โ |
| 40 | HR | Delhi | โ |
| 50 | Admin | Noida | โ |
RESULT: SELECT picks / calculates the columns; DISTINCT removes repeats โ final result:
+-------+ | dname | +-------+ | Admin | +-------+ 1 row in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE deptno IN (10, 40) โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- 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.
- ORDER BY ename โ sorts the result rows in ascending (small โ big / A โ Z) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition deptno IN (10, 40) is checked row by row: 4 row(s) pass โ, 8 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+--------------+------------+-----------+-----------+ | Employee | Basic_Pay | Joined_In | Day | +--------------+------------+-----------+-----------+ | ANIL SHARMA | Rs. 55,000 | April | Wednesday | | GEETA NAIR | Rs. 36,000 | September | Saturday | | LATA MISHRA | Rs. 52,000 | December | Monday | | POONAM ARORA | Rs. 28,000 | July | Monday | +--------------+------------+-----------+-----------+ 4 rows in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- GROUP BY designation โ makes groups: rows with the same designation go into one group (one output row per group).
- 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.
- Functions used: COUNT(*) counts all rows; ROUND(x, d) rounds x to d decimal places; SUM() adds the values.
- ORDER BY Share_Percent DESC โ sorts the result rows in descending (big โ small / Z โ A) order.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
GROUP BY: Rows with the same designation are put in one group โ 6 group(s).
| designation | rows_in_group |
|---|---|
| Clerk | 2 |
| Developer | 2 |
| Executive | 2 |
| Manager | 4 |
| Officer | 1 |
| Team Lead | 1 |
RESULT: SELECT picks / calculates the columns; ORDER BY sorts โ final result:
+-------------+-------+---------------+ | designation | Staff | Share_Percent | +-------------+-------+---------------+ | Manager | 4 | 43.9 | | Developer | 2 | 16.9 | | Team Lead | 1 | 12.8 | | Executive | 2 | 10.8 | | Clerk | 2 | 9.4 | | Officer | 1 | 6.2 | +-------------+-------+---------------+ 6 rows in set (0.00 sec)
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.
- FROM employee โ MySQL first opens table employee and looks at all its rows.
- WHERE mobile IS NOT NULL โ checks this condition for every row; only the rows where it is TRUE are kept.
- 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.
- 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.
- LIMIT 6 โ shows only the first 6 row(s) of the result.
FROM: MySQL opens table employee - all 12 rows are taken.
| empno | ename | deptno | designation | basic | doj | mobile | bonus |
|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 |
WHERE: Condition mobile IS NOT NULL is checked row by row: 9 row(s) pass โ, 3 fail โ.
| empno | ename | deptno | designation | basic | doj | mobile | bonus | |
|---|---|---|---|---|---|---|---|---|
| 1 | Anil Sharma | 10 | Manager | 55000 | 2015-04-01 | 9810011111 | 5500 | โ |
| 2 | Poonam Arora | 10 | Clerk | 28000 | 2019-07-15 | NULL | 0 | โ |
| 3 | Deepak Verma | 20 | Executive | 32000 | 2018-01-10 | 9811122222 | 0 | โ |
| 4 | Rina Das | 20 | Manager | 60000 | 2012-11-05 | 9812233333 | 6000 | โ |
| 5 | Manoj Kumar | 30 | Developer | 50400 | 2020-06-22 | 9813344444 | 0 | โ |
| 6 | Sakshi Jain | 30 | Developer | 47250 | 2021-02-01 | NULL | 0 | โ |
| 7 | Tarun Malik | 30 | Team Lead | 73500 | 2014-08-18 | 9815566666 | 0 | โ |
| 8 | Geeta Nair | 40 | Officer | 36000 | 2017-09-09 | 9816677777 | 0 | โ |
| 9 | Faisal Ali | 20 | Executive | 30000 | 2022-03-14 | 9817788888 | 0 | โ |
| 10 | Lata Mishra | 40 | Manager | 52000 | 2013-12-02 | 9818899999 | 5200 | โ |
| 11 | Kunal Bose | 50 | Clerk | 26000 | 2023-05-08 | NULL | 0 | โ |
| 12 | Ritu Saxena | 30 | Manager | 86100 | 2011-01-17 | 9819900000 | 8200 | โ |
RESULT: SELECT picks / calculates the columns; LIMIT cuts โ final result:
+------------+--------------+ | First_Name | Mobile_Last4 | +------------+--------------+ | Anil | 1111 | | Deepak | 2222 | | Rina | 3333 | | Manoj | 4444 | | Tarun | 6666 | | Geeta | 7777 | +------------+--------------+ 6 rows in set (0.00 sec)
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).
ATM Simulator
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
๐ฏ Objectives
- Control program flow with attempt counters
- Validate cash withdrawals
- Maintain a transaction log in a list
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
accounts | dict | Account no -> {name, pin, balance, today, statement, blocked} |
DAILY_LIMIT | int | Rs. 25,000 per day |
MIN_BALANCE | int | Rs. 1,000 must remain |
statement | list | Last transactions of an account (max 6) |
# =====================================================================
# 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!")
==============================================
KV BANK ATM
==============================================
Insert card - enter account number (0 = shut down): 1001
Enter 4-digit PIN: 1111
Wrong PIN! 2 attempt(s) left
Enter 4-digit PIN: 2222
Wrong PIN! 1 attempt(s) left
Enter 4-digit PIN: 3333
Wrong PIN!
Card blocked after 3 wrong attempts.
Insert card - enter account number (0 = shut down): 1001
This card is blocked. Contact your branch.
Insert card - enter account number (0 = shut down): 1002
Enter 4-digit PIN: 1234
Welcome, Sunita Sharma
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 1
Available balance: Rs. 30000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 2550
Amount must be in multiples of 100.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 29500
Daily limit Rs. 25000 exceeded. You can withdraw Rs. 25000 more today.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 5000
Please collect cash Rs. 5000. Balance Rs. 25000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 2
Deposit amount: 7000
Deposited. Balance Rs. 32000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 20000
Please collect cash Rs. 20000. Balance Rs. 12000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 1000
Daily limit Rs. 25000 exceeded. You can withdraw Rs. 0 more today.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 4
Fast cash 1) 500 2) 1000 3) 2000 : 3
Daily limit Rs. 25000 exceeded. You can withdraw Rs. 0 more today.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 5
Transfer to account: 1003
Amount: 3000
Rs. 3000 sent to Rohit Verma. Balance Rs. 9000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 5
Transfer to account: 1002
Amount: 3000
Invalid beneficiary account.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 6
Type Amount Balance
WITHDRAW 5000.00 25000.00
DEPOSIT 7000.00 32000.00
WITHDRAW 20000.00 12000.00
TRANSFER 3000.00 9000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 7
Old PIN: 1234
New PIN: 1234
New PIN must be 4 digits and different from the old PIN.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 7
Old PIN: 1234
New PIN: 5678
PIN changed successfully.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 1
Available balance: Rs. 9000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 8
Logged out. Please take your card.
Insert card - enter account number (0 = shut down): 1003
Enter 4-digit PIN: 8642
Welcome, Rohit Verma
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 1
Available balance: Rs. 8000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 3
Withdraw amount: 7500
Insufficient balance. Minimum balance Rs. 1000 must remain.
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 6
Type Amount Balance
RECEIVED 3000.00 8000.00
1.Balance 2.Deposit 3.Withdraw 4.Fast Cash 5.Transfer 6.Statement 7.Change PIN 8.Logout 0.Shut Down
Enter choice: 8
Logged out. Please take your card.
Insert card - enter account number (0 = shut down): 0
ATM shut down. Thank you for banking with us!
- Start
- Insert card - read account number
- PIN correct within 3 tries? → No: block card
- Display ATM menu and read choice
- Withdraw allowed (multiple of 100, limit, balance)? → No: show reason
- Update balance and statement
- Show receipt / balance / statement
- Logout? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Wrong PIN 3 times | Card blocked | PASS |
| 2 | Correct PIN | Welcome message | PASS |
| 3 | Withdraw 2550 | 'Multiples of 100' | PASS |
| 4 | Withdraw leaving < Rs. 1000 | 'Minimum balance' message | PASS |
| 5 | Withdraw above daily limit | 'Daily limit' message | PASS |
| 6 | Fast cash 2000 | Balance reduced by 2000 | PASS |
| 7 | Transfer 3000 to account 1002 | Both balances updated | PASS |
| 8 | Change PIN to same PIN | Rejected | PASS |
| 9 | Mini statement | Last 6 transactions | PASS |
โ 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
- Global variables / constants are created:
DAILY_LIMIT,MIN_BALANCE,accounts. - 5 functions are defined (lines 16โ126) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
log(acc, kind, amt) | 16โ20 | Adds a statement entry (keeps last 6). | withdraw(), session() |
read_amount(msg) | 23โ28 | Read amount | session() |
withdraw(acc, amt) | 31โ43 | Withdraws after all checks. | session() |
login() | 46โ68 | Returns the account number after PIN check, or None. | main program |
session(no) | 71โ126 | ATM menu for a logged-in user. Returns False on shut down. | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
login()shows: KV BANK ATM - You type 1001 at Insert card - enter account number (0 = shut down):
- You type 1111 at Enter 4-digit PIN:shows: Wrong PIN! 2 attempt(s) left
- You type 2222 at Enter 4-digit PIN:shows: Wrong PIN! 1 attempt(s) left
- You type 3333 at Enter 4-digit PIN:runs:
login()shows: Wrong PIN! (+1 more lines) - You type 1001 at Insert card - enter account number (0 = shut down):runs:
login()shows: This card is blocked. Contact your branch. - You type 1002 at Insert card - enter account number (0 = shut down):
- You type 1234 at Enter 4-digit PIN:runs:
session()shows: Welcome, Sunita Sharma (+1 more lines) - You type 1 at Enter choice:shows: Available balance: Rs. 30000.00 (+1 more lines)
- You type 3 at Enter choice:runs:
read_amount() - You type 2550 at Withdraw amount:runs:
withdraw()shows: Amount must be in multiples of 100. (+1 more lines) - You type 3 at Enter choice:runs:
read_amount() - You type 29500 at Withdraw amount:runs:
withdraw()shows: Daily limit Rs. 25000 exceeded. You can withdraw Rs. 25000 more today. (+1 more lines) - You type 3 at Enter choice:runs:
read_amount() - You type 5000 at Withdraw amount:runs:
withdraw()โlog()shows: Please collect cash Rs. 5000. Balance Rs. 25000.00 (+1 more lines) - You type 2 at Enter choice:runs:
read_amount() - You type 7000 at Deposit amount:runs:
log()shows: Deposited. Balance Rs. 32000.00 (+1 more lines) - You type 3 at Enter choice:runs:
read_amount() - You type 20000 at Withdraw amount:runs:
withdraw()โlog()shows: Please collect cash Rs. 20000. Balance Rs. 12000.00 (+1 more lines) - You type 3 at Enter choice:runs:
read_amount() - You type 1000 at Withdraw amount:runs:
withdraw()shows: Daily limit Rs. 25000 exceeded. You can withdraw Rs. 0 more today. (+1 more lines) - You type 4 at Enter choice:
- 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) - You type 5 at Enter choice:
- You type 1003 at Transfer to account:runs:
read_amount() - You type 3000 at Amount:runs:
log()ร2shows: Rs. 3000 sent to Rohit Verma. Balance Rs. 9000.00 (+1 more lines) - You type 5 at Enter choice:
- You type 1002 at Transfer to account:runs:
read_amount() - You type 3000 at Amount:shows: Invalid beneficiary account. (+1 more lines)
- You type 6 at Enter choice:shows: Type Amount Balance (+5 more lines)
- You type 7 at Enter choice:
- You type 1234 at Old PIN:
- You type 1234 at New PIN:shows: New PIN must be 4 digits and different from the old PIN. (+1 more lines)
- You type 7 at Enter choice:
- You type 1234 at Old PIN:
- You type 5678 at New PIN:shows: PIN changed successfully. (+1 more lines)
- You type 1 at Enter choice:shows: Available balance: Rs. 9000.00 (+1 more lines)
- You type 8 at Enter choice:runs:
login()shows: Logged out. Please take your card. - You type 1003 at Insert card - enter account number (0 = shut down):
- 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Library Management System
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
library.dat | binary file | One pickled dictionary per book: id, title, author, category, issued_to, issue_date |
members.csv | CSV file | member_id, name, class |
temp.dat | binary file | Temporary file used while updating / deleting |
FINE | int | Rs. 2 per day after 14 days |
TODAY | date | Date used for issue / return (fixed for the demo) |
# =====================================================================
# 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)
======================================================================
LIBRARY MANAGEMENT SYSTEM
======================================================================
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 1
Book ID : 1
Title : Wings of Fire
Author : A.P.J. Abdul Kalam
Category : Biography
Book added successfully!
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 1
Book ID : 2
Title : Python Programming
Author : Sumita Arora
Category : Computer
Book added successfully!
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 1
Book ID : 3
Title : Ignited Minds
Author : A.P.J. Abdul Kalam
Category : Biography
Book added successfully!
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 1
Book ID : 4
Title : Godan
Author : Premchand
Category : Hindi
Book added successfully!
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 1
Book ID : 2
Book ID already exists.
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 2
ID Title Author Category Status
----------------------------------------------------------------------
1 Wings of Fire A.P.J. Abdul Kalam Biography Available
2 Python Programming Sumita Arora Computer Available
3 Ignited Minds A.P.J. Abdul Kalam Biography Available
4 Godan Premchand Hindi Available
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 3
Enter Book ID, title or author: kalam
ID Title Author Category Status
----------------------------------------------------------------------
1 Wings of Fire A.P.J. Abdul Kalam Biography Available
3 Ignited Minds A.P.J. Abdul Kalam Biography Available
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 4
Member ID : M1
Name : Riya Sharma
Class : XII-A
Member saved: Riya Sharma
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 4
Member ID : M2
Name : Kabir Singh
Class : XII-B
Member saved: Kabir Singh
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 5
Book ID to issue: 1
Member ID : M1
Issue date (yyyy-mm-dd): 2026-07-01
'Wings of Fire' issued to Riya Sharma. Due date: 2026-07-15
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 5
Book ID to issue: 1
Member ID : M2
Issue date (yyyy-mm-dd): 2026-07-03
Book is already issued to M1
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 5
Book ID to issue: 3
Member ID : M2
Issue date (yyyy-mm-dd): 2026-07-05
'Ignited Minds' issued to Kabir Singh. Due date: 2026-07-19
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 5
Book ID to issue: 2
Member ID : M1
Issue date (yyyy-mm-dd): 2026-07-20
'Python Programming' issued to Riya Sharma. Due date: 2026-08-03
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 6
Book ID to return: 1
Return date (yyyy-mm-dd): 2026-07-21
Returned by M1 after 20 days. Fine: Rs. 12
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 9
Total books: 4 | Issued: 2 | Available: 2
Python Programming -> Riya Sharma 5 days
Ignited Minds -> Kabir Singh OVERDUE by 6 days (fine so far Rs. 12)
Category-wise: Biography 2, Computer 1, Hindi 1
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 7
Book ID to update: 4
New title [Godan]: Godaan
New author [Premchand]:
New category [Hindi]:
Record updated.
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 8
Book ID to delete: 3
Cannot delete - book is issued.
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 8
Book ID to delete: 4
Deleted: Godaan
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 2
ID Title Author Category Status
----------------------------------------------------------------------
1 Wings of Fire A.P.J. Abdul Kalam Biography Available
2 Python Programming Sumita Arora Computer Issued to M1
3 Ignited Minds A.P.J. Abdul Kalam Biography Issued to M2
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 5
Book ID to issue: x
Please enter a number.
1.Add Book 2.Display 3.Search 4.Add Member 5.Issue 6.Return 7.Update 8.Delete 9.Reports 0.Exit
Enter choice: 0
Library closed.
- Start
- Display menu and read choice
- Choice is Add / Issue / Return? → No: run the selected report
- Open library.dat in append / read mode
- Load records one by one with pickle.load() until EOFError
- Record found and status valid? → No: show message
- Update record and rewrite file through temp.dat
- Display result / fine
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add book 1 'Wings of Fire' | Record saved in library.dat | PASS |
| 2 | Duplicate Book ID | 'Book ID already exists' | PASS |
| 3 | Search author 'kalam' | Matching books listed | PASS |
| 4 | Issue to member M1 | Issued with due date | PASS |
| 5 | Issue an issued book | 'Book is already issued' | PASS |
| 6 | Return after 20 days | Fine Rs. 12 | PASS |
| 7 | Update title | Record rewritten through temp file | PASS |
| 8 | Delete issued book | Not allowed | PASS |
| 9 | Overdue report | Books issued more than 14 days | PASS |
| 10 | Book ID 'x' | ValueError handled | PASS |
โ 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
- Imports (line 5):
pickle- writing / reading Python objects in binary files,csv- reading / writing CSV files,os- file and folder operations,date,timedeltaare loaded. - Global variables / constants are created:
TODAY. - 14 functions are defined (lines 12โ173) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_books() | 12โ22 | Returns a list of all book dictionaries. | add_book(), display_books(), search_book(), issue_book() |
write_books(books) | 25โ30 | Rewrites the file through a temporary file. | issue_book(), return_book(), update_book(), delete_book() |
read_int(msg) | 33โ38 | Read int | add_book(), issue_book(), return_book(), update_book() |
add_book() | 41โ53 | Appends a new book. | main program (menu) |
show(books) | 56โ61 | Show | display_books(), search_book() |
display_books() | 64โ66 | Display books | main program (menu) |
search_book() | 69โ73 | Search by ID / title / author. | main program (menu) |
add_member() | 76โ81 | Writes a member to the CSV file. | main program (menu) |
members() | 84โ88 | Members | issue_book(), reports() |
issue_book() | 91โ112 | Issues a book to a member. | main program (menu) |
return_book() | 115โ128 | Returns a book and calculates the fine. | main program (menu) |
update_book() | 131โ144 | Updates title / author / category (blank keeps old value). | main program (menu) |
delete_book() | 147โ158 | Deletes a book that is not issued. | main program (menu) |
reports() | 161โ173 | Issued, overdue and category-wise stock. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: LIBRARY MANAGEMENT SYSTEM (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 1 at Book ID :runs:
read_books() - You type Wings of Fire at Title :
- You type A.P.J. Abdul Kalam at Author :
- You type Biography at Category :shows: Book added successfully! (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 2 at Book ID :runs:
read_books() - You type Python Programming at Title :
- You type Sumita Arora at Author :
- You type Computer at Category :shows: Book added successfully! (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 3 at Book ID :runs:
read_books() - You type Ignited Minds at Title :
- You type A.P.J. Abdul Kalam at Author :
- You type Biography at Category :shows: Book added successfully! (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 4 at Book ID :runs:
read_books() - You type Godan at Title :
- You type Premchand at Author :
- You type Hindi at Category :shows: Book added successfully! (+1 more lines)
- You type 1 at Enter choice:runs:
add_book()โread_int() - You type 2 at Book ID :runs:
read_books()shows: Book ID already exists. (+1 more lines) - You type 2 at Enter choice:runs:
display_books()โread_books()โshow()shows: ID Title Author Category Status (+5 more lines) - You type 3 at Enter choice:runs:
search_book() - You type kalam at Enter Book ID, title or author:runs:
read_books()โshow()shows: ID Title Author Category Status (+3 more lines) - You type 4 at Enter choice:runs:
add_member() - You type M1 at Member ID :
- You type Riya Sharma at Name :
- You type XII-A at Class :shows: Member saved: Riya Sharma (+1 more lines)
- You type 4 at Enter choice:runs:
add_member() - You type M2 at Member ID :
- You type Kabir Singh at Name :
- You type XII-B at Class :shows: Member saved: Kabir Singh (+1 more lines)
- You type 5 at Enter choice:runs:
issue_book()โread_int() - You type 1 at Book ID to issue:
- You type M1 at Member ID :
- 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) - You type 5 at Enter choice:runs:
issue_book()โread_int() - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Bank Management System (with MySQL)
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
๐ฏ Objectives
- Connect Python to MySQL using mysql.connector
- Use parameterised INSERT, UPDATE and SELECT queries
- Protect data with balance checks and commit()
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
accounts | MySQL table | accno INT PK AUTO_INCREMENT (from 1001), name, mobile, acc_type, balance DECIMAL(12,2) |
transactions | MySQL table | tid INT PK, accno INT, ttype VARCHAR(10), amount DECIMAL(12,2), balance DECIMAL(12,2) |
conn / cur | objects | MySQL connection and cursor |
MIN_BAL | int | Rs. 1000 minimum balance |
# =====================================================================
# 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"))()
============================================================
KV BANK - BANK MANAGEMENT SYSTEM (Python + MySQL)
============================================================
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 1
Account holder name : Narender Kumar
Mobile number : 9810012345
Type S/C (Savings/Current): S
Opening deposit : 5000
Account opened! Account No: 1001
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 1
Account holder name : Sunita Rao
Mobile number : 9811198765
Type S/C (Savings/Current): C
Opening deposit : 500
Minimum opening deposit is Rs. 1000.
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 1
Account holder name : Sunita Rao
Mobile number : 9811198765
Type S/C (Savings/Current): C
Opening deposit : 20000
Account opened! Account No: 1002
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 1
Account holder name : Amit Jain
Mobile number : 9899911122
Type S/C (Savings/Current): S
Opening deposit : 8000
Account opened! Account No: 1003
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 2
Account No: 1001
Amount : 2000
Deposited. New balance Rs. 7000.00
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 3
Account No: 1003
Amount : 7500
Insufficient balance. Rs. 1000 must remain (available Rs. 7000.00).
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 3
Account No: 1003
Amount : 2500
Please collect Rs. 2500. Balance Rs. 5500.00
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 4
From account: 1001
To account : 1002
Amount : 1500
Rs. 1500 transferred from 1001 to 1002.
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 4
From account: 1001
To account : 9999
Amount : 100
Transfer failed: Account not found - no money moved.
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 5
Account No: 1001
TID Type Amount Balance
1 OPEN 5000.00 5000.00
4 DEPOSIT 2000.00 7000.00
6 TRF-OUT 1500.00 5500.00
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 6
Account No: 1002
Account 1002 | Sunita Rao | Mobile 9811198765 | Current | Balance Rs. 21500.00
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 7
Account 1001: interest Rs. 18.33
Account 1003: interest Rs. 18.33
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 8
AccNo Name Type Balance
1002 Sunita Rao C 21500.00
1001 Narender Kumar S 5518.33
1003 Amit Jain S 5518.33
Accounts 3 | Total deposits Rs. 32536.66 | Highest Rs. 21500.00 | Average Rs. 10845.55
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 9
Account No to close: 1003
Account 1003 closed. Rs. 5518.33 paid to the customer. Rows deleted: 1
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 8
AccNo Name Type Balance
1002 Sunita Rao C 21500.00
1001 Narender Kumar S 5518.33
Accounts 2 | Total deposits Rs. 27018.33 | Highest Rs. 21500.00 | Average Rs. 13509.17
1.Open 2.Deposit 3.Withdraw 4.Transfer 5.Statement 6.Details 7.Interest 8.Report 9.Close 0.Exit
Enter choice: 0
Connection closed. Thank you!
- Start
- Connect to MySQL, create bankdb and tables
- Display menu and read choice
- Choice is Transfer? → No: run the selected operation
- Read from-account, to-account and amount
- Both accounts exist and balance enough? → No: show error
- Two UPDATEs, log transactions, COMMIT (ROLLBACK on error)
- Show statement / report
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Open account with Rs. 5000 | Account 1001 created | PASS |
| 2 | Opening deposit Rs. 500 | 'Minimum Rs. 1000' | PASS |
| 3 | Deposit 2000 | Balance increased; transaction logged | PASS |
| 4 | Withdraw leaving < 1000 | Refused | PASS |
| 5 | Transfer 1500 from 1001 to 1002 | Both balances updated in one COMMIT | PASS |
| 6 | Transfer to 9999 | 'Account not found', nothing changed | PASS |
| 7 | Mini statement | Last 5 transactions | PASS |
| 8 | Credit interest | Savings accounts get 4 % / 12 | PASS |
| 9 | Bank report | Count, total and highest balance | PASS |
| 10 | Close account | Row deleted | PASS |
โ 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
- Imports (line 6):
mysql.connector- connecting Python with MySQL are loaded. - Global variables / constants are created:
MIN_BAL,conn,cur. - 12 functions are defined (lines 21โ151) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
num(msg, kind) | 21โ26 | Num | open_account(), deposit(), withdraw(), transfer() |
get_balance(accno) | 29โ32 | Get balance | log(), deposit(), withdraw(), transfer() |
log(accno, ttype, amount) | 35โ37 | Log | open_account(), deposit(), withdraw(), transfer() |
open_account() | 40โ53 | Opens a new account. | main program (menu) |
deposit() | 56โ64 | Deposit | main program (menu) |
withdraw() | 67โ78 | Withdraw | main program (menu) |
transfer() | 81โ97 | Fund transfer as one database transaction. | main program (menu) |
statement() | 100โ108 | Statement | main program (menu) |
details() | 111โ118 | Details | main program (menu) |
credit_interest() | 121โ129 | Monthly interest 4 % p.a. for savings accounts. | main program (menu) |
report() | 132โ140 | Report | main program (menu) |
close_account() | 143โ151 | Close account | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Hospital Patient Management System
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
patients.csv | CSV file | pid, name, age, gender, symptom, doctor, fee |
DOCTORS | dict | symptom keyword -> (department doctor, consultation fee) |
emergency | list (stack) | push = append(), pop = pop() |
opd | list (queue) | append() to add, pop(0) to serve |
FIELDS | list | Header row of the CSV |
# =====================================================================
# 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"))()
====================================================================
CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM
====================================================================
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P101
Name : Ravi Kumar
Age : 45
Gender M/F : M
Symptom : fever
Registered. Doctor: Dr. Mehta (General) Fee: Rs. 300
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P102
Name : Anita Sharma
Age : 32
Gender M/F : F
Symptom : skin rash
Registered. Doctor: Dr. Kaur (Dermatology) Fee: Rs. 500
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P103
Name : Mohan Lal
Age : 67
Gender M/F : M
Symptom : chest pain
Registered. Doctor: Dr. Rao (Cardiology) Fee: Rs. 800
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P104
Name : Neha Sharma
Age : abc
Age must be a number.
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P104
Name : Neha Sharma
Age : 9
Gender M/F : F
Symptom : cough
Registered. Doctor: Dr. Das (Paediatrics) Fee: Rs. 400
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 1
Patient ID : P101
Patient ID already exists.
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 2
PID Name Age G Symptom Doctor Fee
--------------------------------------------------------------------
P101 Ravi Kumar 45 M fever Dr. Mehta (General) 300
P102 Anita Sharma 32 F skin rash Dr. Kaur (Dermatology) 500
P103 Mohan Lal 67 M chest pain Dr. Rao (Cardiology) 800
P104 Neha Sharma 9 F cough Dr. Das (Paediatrics) 400
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 3
Enter Patient ID or name: sharma
PID Name Age G Symptom Doctor Fee
--------------------------------------------------------------------
P102 Anita Sharma 32 F skin rash Dr. Kaur (Dermatology) 500
P104 Neha Sharma 9 F cough Dr. Das (Paediatrics) 400
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 4
Patient ID for OPD: P101
Token 1 given to Ravi Kumar
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 4
Patient ID for OPD: P104
Token 2 given to Neha Sharma
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 5
Emergency Patient ID: P103
Pushed on emergency stack. Stack size: 1
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 5
Emergency Patient ID: P102
Pushed on emergency stack. Stack size: 2
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 7
Top of emergency stack: Anita Sharma
Emergency stack (top -> bottom): ['P102', 'P103']
OPD queue (front -> rear): ['P101', 'P104']
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 6
[EMERGENCY] Now calling Anita Sharma (P102) to Dr. Kaur (Dermatology)
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 6
[EMERGENCY] Now calling Mohan Lal (P103) to Dr. Rao (Cardiology)
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 6
[OPD] Now calling Ravi Kumar (P101) to Dr. Mehta (General)
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 7
Top of emergency stack: Empty
Emergency stack (top -> bottom): []
OPD queue (front -> rear): ['P104']
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 6
[OPD] Now calling Neha Sharma (P104) to Dr. Das (Paediatrics)
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 6
Underflow! No patient waiting.
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 8
Patient ID to update: P104
New age [9]: 10
New symptom [cough]: cold
Updated. Doctor now: Dr. Das (Paediatrics)
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 9
Patient ID to discharge: P102
----------------------------------
Bill for Anita Sharma (P102)
Consultation : Rs. 500
Medicines : Rs. 250
Total : Rs. 750
----------------------------------
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 10
Total patients: 3
Cardiology : * 1
General : * 1
Paediatrics : * 1
Age groups: {'Child (<12)': 1, 'Adult (12-59)': 1, 'Senior (60+)': 1}
Fee collected (registered): Rs. 1500
1.Register 2.Show 3.Search 4.OPD 5.Emergency 6.Call Next 7.Peek 8.Update 9.Discharge 10.Reports 0.Exit
Enter choice: 0
Goodbye!
- Start
- Display menu and read choice
- Choice is Call Next? → No: run selected file / stack operation
- Emergency stack empty? → No: pop the top patient
- OPD queue empty? → No: serve the first patient
- Display 'No patient waiting' or patient details
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Register P101 with 'fever' | Doctor: Dr. Mehta (General) | PASS |
| 2 | Register with age 'abc' | 'Age must be a number' | PASS |
| 3 | Duplicate P101 | Refused | PASS |
| 4 | Search 'sharma' | Matching rows | PASS |
| 5 | Push P103 emergency | Stack size increases | PASS |
| 6 | Call next (stack not empty) | Emergency patient first (LIFO) | PASS |
| 7 | Call next with empty stack | First OPD patient (FIFO) | PASS |
| 8 | Call next - nothing waiting | 'Underflow' | PASS |
| 9 | Discharge P102 | Row deleted, bill printed | PASS |
| 10 | Reports | Department counts and fee total | PASS |
โ 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
- Imports (line 6):
csv- reading / writing CSV files,os- file and folder operations are loaded. - Global variables / constants are created:
FILE,FIELDS,DOCTORS,emergency,opd. - 15 functions are defined (lines 18โ164) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_all() | 18โ22 | Read all | find(), register(), show_all(), search() |
write_all(rows) | 25โ29 | Write all | register(), update(), discharge() |
find(pid) | 32โ36 | Find | register(), add_opd(), push_emergency(), call_next() |
allot(symptom, age) | 39โ46 | Returns (doctor, fee) from the symptom keyword. | register(), update() |
register() | 49โ65 | Register | main program (menu) |
show(rows) | 68โ72 | Show | show_all(), search() |
show_all() | 75โ77 | Show all | main program (menu) |
search() | 80โ83 | Search | main program (menu) |
add_opd() | 86โ92 | Add opd | main program (menu) |
push_emergency() | 95โ101 | Push emergency | main program (menu) |
call_next() | 104โ114 | Emergency stack first (pop), otherwise OPD queue. | main program (menu) |
peek() | 117โ120 | Peek | main program (menu) |
update() | 123โ135 | Update | main program (menu) |
discharge() | 138โ149 | Discharge | main program (menu) |
reports() | 152โ164 | Reports | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CITY HOSPITAL - PATIENT MANAGEMENT SYSTEM (+1 more lines)
- You type 1 at Enter choice:runs:
register() - You type P101 at Patient ID :runs:
find()โread_all() - You type Ravi Kumar at Name :
- You type 45 at Age :
- You type M at Gender M/F :
- You type fever at Symptom :runs:
allot()โread_all()โwrite_all()shows: Registered. Doctor: Dr. Mehta (General) Fee: Rs. 300 (+1 more lines) - You type 1 at Enter choice:runs:
register() - You type P102 at Patient ID :runs:
find()โread_all() - You type Anita Sharma at Name :
- You type 32 at Age :
- You type F at Gender M/F :
- You type skin rash at Symptom :runs:
allot()โread_all()โwrite_all()shows: Registered. Doctor: Dr. Kaur (Dermatology) Fee: Rs. 500 (+1 more lines) - You type 1 at Enter choice:runs:
register() - You type P103 at Patient ID :runs:
find()โread_all() - You type Mohan Lal at Name :
- You type 67 at Age :
- You type M at Gender M/F :
- You type chest pain at Symptom :runs:
allot()โread_all()โwrite_all()shows: Registered. Doctor: Dr. Rao (Cardiology) Fee: Rs. 800 (+1 more lines) - You type 1 at Enter choice:runs:
register() - You type P104 at Patient ID :runs:
find()โread_all() - You type Neha Sharma at Name :
- You type abc at Age :shows: Age must be a number. (+1 more lines)
- You type 1 at Enter choice:runs:
register() - You type P104 at Patient ID :runs:
find()โread_all() - You type Neha Sharma at Name :
- You type 9 at Age :
- You type F at Gender M/F :
- You type cough at Symptom :runs:
allot()โread_all()โwrite_all()shows: Registered. Doctor: Dr. Das (Paediatrics) Fee: Rs. 400 (+1 more lines) - You type 1 at Enter choice:runs:
register() - You type P101 at Patient ID :runs:
find()โread_all()shows: Patient ID already exists. (+1 more lines) - You type 2 at Enter choice:runs:
show_all()โread_all()โshow()shows: PID Name Age G Symptom Doctor Fee (+5 more lines) - You type 3 at Enter choice:runs:
search() - You type sharma at Enter Patient ID or name:runs:
read_all()โshow()shows: PID Name Age G Symptom Doctor Fee (+3 more lines) - You type 4 at Enter choice:runs:
add_opd() - 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) - You type 4 at Enter choice:runs:
add_opd() - 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) - You type 5 at Enter choice:runs:
push_emergency() - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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()).
Quiz / Online Exam System
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
BANK | dict of lists | subject -> list of (question, options, answer) |
scores.csv | CSV file | name, subject, score, max, percent |
CORRECT / WRONG | int | +4 / -1 marking scheme |
ADMIN_PWD | str | Password for adding questions |
# =====================================================================
# 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"))()
========================================================
KV ONLINE QUIZ SYSTEM (+4 correct / -1 wrong)
========================================================
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 1
Student name: Riya
Subject (python / networking / sql): python
Q1. Which is immutable?
(a) list
(b) dict
(c) tuple
(d) set
Your answer (a-d, s=skip): c
Correct! +4
Q2. Keyword to define a function?
(a) def
(b) fun
(c) define
(d) func
Your answer (a-d, s=skip): a
Correct! +4
Q3. Result of 7 // 2?
(a) 3.5
(b) 3
(c) 4
(d) 1
Your answer (a-d, s=skip): s
Skipped. Answer: 3
Q4. Output of 2**3?
(a) 6
(b) 8
(c) 9
(d) 5
Your answer (a-d, s=skip): b
Correct! +4
Q5. Which module gives random numbers?
(a) math
(b) os
(c) random
(d) sys
Your answer (a-d, s=skip): z
Invalid option, try again.
Your answer (a-d, s=skip): c
Correct! +4
Riya: Right 4, Wrong 0, Score 16/20 (80.0%) - Excellent
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 1
Student name: Kabir
Subject (python / networking / sql): sql
Q1. Wildcard for any characters in LIKE?
(a) %
(b) _
(c) *
(d) #
Your answer (a-d, s=skip): a
Correct! +4
Q2. Command to remove a table?
(a) DROP
(b) DELETE
(c) REMOVE
(d) CUT
Your answer (a-d, s=skip): a
Correct! +4
Q3. Clause to filter groups?
(a) WHERE
(b) HAVING
(c) ORDER BY
(d) LIKE
Your answer (a-d, s=skip): b
Correct! +4
Q4. Aggregate that counts rows?
(a) SUM()
(b) COUNT()
(c) MAX()
(d) AVG()
Your answer (a-d, s=skip): b
Correct! +4
Q5. Which is a DDL command?
(a) SELECT
(b) UPDATE
(c) CREATE
(d) INSERT
Your answer (a-d, s=skip): a
Wrong! -1. Correct answer: CREATE
Kabir: Right 4, Wrong 1, Score 15/20 (75.0%) - Good
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 1
Student name: Aman
Subject (python / networking / sql): maths
Invalid subject.
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 1
Student name: Aman
Subject (python / networking / sql): networking
Q1. Full form of LAN?
(a) Large Area Net
(b) Local Area Network
(c) Long Access Node
(d) Line Area Net
Your answer (a-d, s=skip): b
Correct! +4
Q2. IPv4 address length in bits?
(a) 16
(b) 64
(c) 32
(d) 128
Your answer (a-d, s=skip): c
Correct! +4
Q3. Device that connects different networks?
(a) Hub
(b) Repeater
(c) Router
(d) Switch
Your answer (a-d, s=skip): c
Correct! +4
Q4. Protocol used to send e-mail?
(a) SMTP
(b) FTP
(c) HTTP
(d) PPP
Your answer (a-d, s=skip): a
Correct! +4
Q5. Topology with a central device?
(a) Bus
(b) Star
(c) Ring
(d) Mesh
Your answer (a-d, s=skip): b
Correct! +4
Aman: Right 5, Wrong 0, Score 20/20 (100.0%) - Excellent
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 1
Student name: Riya
Subject (python / networking / sql): sql
Q1. Clause to filter groups?
(a) WHERE
(b) HAVING
(c) ORDER BY
(d) LIKE
Your answer (a-d, s=skip): b
Correct! +4
Q2. Command to remove a table?
(a) DROP
(b) DELETE
(c) REMOVE
(d) CUT
Your answer (a-d, s=skip): a
Correct! +4
Q3. Which is a DDL command?
(a) SELECT
(b) UPDATE
(c) CREATE
(d) INSERT
Your answer (a-d, s=skip): c
Correct! +4
Q4. Wildcard for any characters in LIKE?
(a) %
(b) _
(c) *
(d) #
Your answer (a-d, s=skip): c
Wrong! -1. Correct answer: %
Q5. Aggregate that counts rows?
(a) SUM()
(b) COUNT()
(c) MAX()
(d) AVG()
Your answer (a-d, s=skip): b
Correct! +4
Riya: Right 4, Wrong 1, Score 15/20 (75.0%) - Good
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 2
Rank Name Subject Score %
1 Aman networking 20/20 100.0
2 Riya python 16/20 80.0
3 Kabir sql 15/20 75.0
4 Riya sql 15/20 75.0
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 3
Enter your name: riya
python 16/20 (80.0%)
sql 15/20 (75.0%)
Attempts: 2 | Best: 80.0 %
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 4
python attempts 1 average 80.0% topper Riya (80.0%)
networking attempts 1 average 100.0% topper Aman (100.0%)
sql attempts 2 average 75.0% topper Kabir (75.0%)
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 5
Admin password: abc
Access denied.
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 5
Admin password: kv@123
Subject: python
Question: Which function gives the length of a list?
Option a: size()
Option b: len()
Option c: count()
Option d: length()
Correct option (a-d): b
Question added to python
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 6
python : 6 questions
networking : 5 questions
sql : 5 questions
1.Take Quiz 2.Leaderboard 3.My Results 4.Statistics 5.Add Question 6.Count 0.Exit
Enter choice: 0
All the best for your exams!
- Start
- Display menu and read choice
- Choice is Take Quiz? → No: run report option
- Read name and subject
- Pick 5 random questions
- Ask each question and read option a-d / s
- Add +4, -1 or 0
- Save score in scores.csv
- Show score and remark
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Correct answer 'b' | +4 marks | PASS |
| 2 | Wrong answer | -1 marks, correct answer shown | PASS |
| 3 | Answer 's' | Skipped, 0 marks | PASS |
| 4 | Invalid option 'z' | Asked again | PASS |
| 5 | Unknown subject | 'Invalid subject' | PASS |
| 6 | Leaderboard | Top 5 sorted by percentage | PASS |
| 7 | My results for 'Riya' | All her attempts | PASS |
| 8 | Wrong admin password | Access denied | PASS |
| 9 | Add question | Question count increases | PASS |
โ 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
- Imports (line 6):
random- random number functions,csv- reading / writing CSV files,os- file and folder operations are loaded. - Global variables / constants are created:
BANK. - 7 functions are defined (lines 27โ108) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
take_quiz() | 27โ58 | Conducts a 5-question quiz with negative marking. | main program (menu) |
rows() | 61โ65 | Rows | leaderboard(), my_results(), stats() |
leaderboard() | 68โ72 | Leaderboard | main program (menu) |
my_results() | 75โ80 | My results | main program (menu) |
stats() | 83โ91 | Stats | main program (menu) |
add_question() | 94โ103 | Add question | main program (menu) |
count() | 106โ108 | Count | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: KV ONLINE QUIZ SYSTEM (+4 correct / -1 wrong) (+1 more lines)
- You type 1 at Enter choice:runs:
take_quiz() - You type Riya at Student name:
- You type python at Subject (python / networking / sql):shows: Q1. Which is immutable? (+4 more lines)
- You type c at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type a at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type s at Your answer (a-d, s=skip):shows: Skipped. Answer: 3 (+5 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type z at Your answer (a-d, s=skip):shows: Invalid option, try again.
- You type c at Your answer (a-d, s=skip):shows: Correct! +4 (+2 more lines)
- You type 1 at Enter choice:runs:
take_quiz() - You type Kabir at Student name:
- You type sql at Subject (python / networking / sql):shows: Q1. Wildcard for any characters in LIKE? (+4 more lines)
- You type a at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type a at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type a at Your answer (a-d, s=skip):shows: Wrong! -1. Correct answer: CREATE (+2 more lines)
- You type 1 at Enter choice:runs:
take_quiz() - You type Aman at Student name:
- You type maths at Subject (python / networking / sql):shows: Invalid subject. (+1 more lines)
- You type 1 at Enter choice:runs:
take_quiz() - You type Aman at Student name:
- You type networking at Subject (python / networking / sql):shows: Q1. Full form of LAN? (+4 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type c at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type c at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type a at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+2 more lines)
- You type 1 at Enter choice:runs:
take_quiz() - You type Riya at Student name:
- You type sql at Subject (python / networking / sql):shows: Q1. Clause to filter groups? (+4 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type a at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type c at Your answer (a-d, s=skip):shows: Correct! +4 (+5 more lines)
- You type c at Your answer (a-d, s=skip):shows: Wrong! -1. Correct answer: % (+5 more lines)
- You type b at Your answer (a-d, s=skip):shows: Correct! +4 (+2 more lines)
- You type 2 at Enter choice:runs:
leaderboard()โrows()shows: Rank Name Subject Score % (+5 more lines) - You type 3 at Enter choice:runs:
my_results() - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
GST Invoice / Book-Shop Billing System
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
items | MySQL table | code PK, name, category, price, gst, stock |
invoice | MySQL table | inv_no PK AUTO_INCREMENT, customer, subtotal, discount, gst_amt, total |
inv_items | MySQL table | inv_no, code, qty, rate, gst |
invoices.csv | CSV file | Exported invoice summary |
GST | dict | Category -> GST rate |
# =====================================================================
# 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)
==========================================================
GST BILLING SYSTEM (Python + MySQL)
==========================================================
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 1
Item code : B01
Item name : NCERT Physics XII
Category (Books/Stationery/Electronics): Books
Price : 285
Stock : 20
NCERT Physics XII added with GST 5%.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 1
Item code : B02
Item name : Sumita Arora CS
Category (Books/Stationery/Electronics): Books
Price : 560
Stock : 10
Sumita Arora CS added with GST 5%.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 1
Item code : S01
Item name : Geometry Box
Category (Books/Stationery/Electronics): Stationery
Price : 120
Stock : 6
Geometry Box added with GST 12%.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 1
Item code : S02
Item name : Gel Pen Pack
Category (Books/Stationery/Electronics): Stationery
Price : 90
Stock : 4
Gel Pen Pack added with GST 12%.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 1
Item code : E01
Item name : Scientific Calculator
Category (Books/Stationery/Electronics): Electronics
Price : 950
Stock : 5
Scientific Calculator added with GST 18%.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 2
Code Name Category Price GST Stock
B01 NCERT Physics XII Books 285.00 5% 20
B02 Sumita Arora CS Books 560.00 5% 10
E01 Scientific Calculator Electronics 950.00 18% 5
S01 Geometry Box Stationery 120.00 12% 6
S02 Gel Pen Pack Stationery 90.00 12% 4
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 3
Customer name: Ritu Verma
Item code (blank to finish): B01
Quantity : 2
Added 2 x NCERT Physics XII
Item code (blank to finish): S01
Quantity : 1
Added 1 x Geometry Box
Item code (blank to finish): S02
Quantity : 9
Only 4 in stock.
Item code (blank to finish): X99
Quantity : 1
Item not found.
Item code (blank to finish):
==========================================================
KV BOOK & STATIONERY HOUSE - TAX INVOICE
Invoice No: 1 Customer: Ritu Verma
----------------------------------------------------------
Item Qty Rate GST Amount
NCERT Physics XII 2 285.00 5% 570.00
Geometry Box 1 120.00 12% 120.00
----------------------------------------------------------
Sub total 690.00
Discount (5% above Rs. 2000) -0.00
CGST 21.45
SGST 21.45
GRAND TOTAL 732.90
==========================================================
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 3
Customer name: Arjun Mehta
Item code (blank to finish): B02
Quantity : 2
Added 2 x Sumita Arora CS
Item code (blank to finish): E01
Quantity : 1
Added 1 x Scientific Calculator
Item code (blank to finish): B01
Quantity : 1
Added 1 x NCERT Physics XII
Item code (blank to finish):
==========================================================
KV BOOK & STATIONERY HOUSE - TAX INVOICE
Invoice No: 2 Customer: Arjun Mehta
----------------------------------------------------------
Item Qty Rate GST Amount
Sumita Arora CS 2 560.00 5% 1120.00
Scientific Calculator 1 950.00 18% 950.00
NCERT Physics XII 1 285.00 5% 285.00
----------------------------------------------------------
Sub total 2355.00
Discount (5% above Rs. 2000) -117.75
CGST 114.59
SGST 114.59
GRAND TOTAL 2466.44
==========================================================
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 4
Invoice number: 1
==========================================================
KV BOOK & STATIONERY HOUSE - TAX INVOICE
Invoice No: 1 Customer: Ritu Verma
----------------------------------------------------------
Item Qty Rate GST Amount
NCERT Physics XII 2 285.00 5% 570.00
Geometry Box 1 120.00 12% 120.00
----------------------------------------------------------
Sub total 690.00
Discount (5% above Rs. 2000) -0.00
CGST 21.45
SGST 21.45
GRAND TOTAL 732.90
==========================================================
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 5
Category Qty Sales GST
Books 5 1975.00 98.75
Electronics 1 950.00 171.00
Stationery 1 120.00 14.40
Invoices: 2 | Net collection Rs. 3199.34
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 6
Item code: S02
Quantity purchased: 10
Stock updated.
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 7
LOW: E01 Scientific Calculator - only 4 left
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 8
2 invoices exported to invoices.csv
inv_no,customer,subtotal,discount,gst,total
1,Ritu Verma,690.00,0.00,42.90,732.90
2,Arjun Mehta,2355.00,117.75,229.19,2466.44
1.Add Item 2.Items 3.New Invoice 4.Find Invoice 5.Sales Report 6.Purchase 7.Low Stock 8.Export 0.Exit
Enter choice: 0
Thank you, visit again!
- Start
- Connect to MySQL and create tables
- Display menu and read choice
- Choice is New Invoice? → No: run selected option
- Read item code and quantity (blank to finish)
- Item exists and stock enough? → No: show message
- Add to cart, compute GST
- Apply discount, save invoice, reduce stock, COMMIT
- Print invoice
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add item B01 Book | GST 5 % auto | PASS |
| 2 | Bill 2 books + 1 bag | CGST + SGST correct | PASS |
| 3 | Quantity more than stock | 'Only n in stock' | PASS |
| 4 | Wrong item code | 'Item not found' | PASS |
| 5 | Bill above Rs. 2000 | 5 % discount | PASS |
| 6 | Find invoice 1 | Old bill reprinted | PASS |
| 7 | Sales report | Category totals with GROUP BY | PASS |
| 8 | Purchase 10 pens | Stock updated | PASS |
| 9 | Low stock | Items < 5 listed | PASS |
| 10 | Export CSV | File written | PASS |
โ 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
- Imports (line 6):
mysql.connector- connecting Python with MySQL,csv- reading / writing CSV files are loaded. - Global variables / constants are created:
GST,conn,cur. - 9 functions are defined (lines 22โ141) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
add_item() | 22โ32 | Add item | main program (menu) |
show_items() | 35โ39 | Show items | main program (menu) |
print_invoice(no) | 42โ63 | Print invoice | new_invoice(), find_invoice() |
new_invoice() | 66โ98 | New invoice | main program (menu) |
find_invoice() | 101โ102 | Find invoice | main program (menu) |
sales_report() | 105โ113 | Sales report | main program (menu) |
purchase() | 116โ120 | Purchase | main program (menu) |
low_stock() | 123โ129 | Low stock | main program (menu) |
export_csv() | 132โ141 | Export csv | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Student Management System (Python + MySQL)
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
๐ฏ Objectives
- Perform CRUD operations through mysql.connector
- Use fetchone(), fetchall() and rowcount
- Rank records using ORDER BY and LIMIT
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
student | MySQL table | roll INT PK, name, section, stream, eng, maths, phy, chem, cs (INT) |
SUBJ | list | Subject column names |
grade() | function | Returns A1..E from percentage |
cur.rowcount | int | Rows affected by UPDATE / DELETE |
# =====================================================================
# 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.")
==================================================================
STUDENT MANAGEMENT SYSTEM (Python + MySQL)
==================================================================
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 1
Name : Aanya Gupta
Section : A
Stream : Science
ENG marks: 88
MATHS marks: 95
PHY marks: 82
CHEM marks: 79
CS marks: 97
Student added.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 2
Name : Rohan Das
Section : A
Stream : Science
ENG marks: 65
MATHS marks: 58
PHY marks: 61
CHEM marks: 55
CS marks: 70
Student added.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 3
Name : Manpreet Kaur
Section : B
Stream : Science
ENG marks: 91
MATHS marks: 89
PHY marks: 93
CHEM marks: 90
CS marks: 86
Student added.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 4
Name : Ishaan Nair
Section : B
Stream : Science
ENG marks: 42
MATHS marks: 30
PHY marks: 35
CHEM marks: 38
CS marks: 45
Student added.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 5
Name : Fatima Khan
Section : A
Stream : Science
ENG marks: 78
MATHS marks: 84
PHY marks: 72
CHEM marks: 80
CS marks: 92
Student added.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 3
Name : Test
Section : A
Stream : Science
ENG marks: 50
MATHS marks: 50
PHY marks: 50
CHEM marks: 50
CS marks: 50
Roll number 3 already exists.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 1
Roll no : 6
Name : Dev
Section : A
Stream : Science
ENG marks: 105
Marks must be 0-100. Record not saved.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 2
Roll Name Sec ENG MAT PHY CHE CS Total % Grade
------------------------------------------------------------------
1 Aanya Gupta A 88 95 82 79 97 441 88.2 A2
2 Rohan Das A 65 58 61 55 70 309 61.8 B2
3 Manpreet Kaur B 91 89 93 90 86 449 89.8 A2
4 Ishaan Nair B 42 30 35 38 45 190 38.0 D
5 Fatima Khan A 78 84 72 80 92 406 81.2 A2
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 3
Roll no or part of name: aan
Roll Name Sec ENG MAT PHY CHE CS Total % Grade
------------------------------------------------------------------
1 Aanya Gupta A 88 95 82 79 97 441 88.2 A2
4 Ishaan Nair B 42 30 35 38 45 190 38.0 D
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 3
Roll no or part of name: 4
Roll Name Sec ENG MAT PHY CHE CS Total % Grade
------------------------------------------------------------------
4 Ishaan Nair B 42 30 35 38 45 190 38.0 D
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 4
Roll no : 3
Subject (eng/maths/phy/chem/cs): cs
New marks: 95
1 row updated.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 5
Roll no to delete: 99
No such student.
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 6
Rank 1: Manpreet Kaur (Roll 3) Total 458/500 91.6%
Rank 2: Aanya Gupta (Roll 1) Total 441/500 88.2%
Rank 3: Fatima Khan (Roll 5) Total 406/500 81.2%
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 7
Students: 5 | Class average: 72.16% | Highest: 458 | Lowest: 190
Passed in all subjects: 4/5 -> Pass percentage 80.0%
ENG average 72.80 highest 91
MATHS average 71.20 highest 95
PHY average 68.60 highest 93
CHEM average 68.40 highest 90
CS average 79.80 highest 97
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 8
Sections with average above 65 %:
Section A: 3 students, average 77.07%
1.Add 2.Display 3.Search 4.Update 5.Delete 6.Merit 7.Result 8.Sections 0.Exit
Enter choice: 0
Bye!
- Start
- Connect and create sms_db.student
- Display menu and read choice
- Valid choice? → No: show 'Invalid choice'
- Build parameterised SQL query
- cursor.execute(), fetchall() / commit()
- Display rows / result
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add roll 1 with marks | Row inserted | PASS |
| 2 | Duplicate roll | IntegrityError handled | PASS |
| 3 | Marks 105 | 'Marks must be 0-100' | PASS |
| 4 | Search 'aan' | Aanya and Ishaan listed | PASS |
| 5 | Update CS of roll 3 to 95 | 1 row updated | PASS |
| 6 | Delete roll 99 | 'No such student' | PASS |
| 7 | Merit list | Top 3 by total | PASS |
| 8 | Class result | Average and pass % | PASS |
| 9 | Section analysis | Only 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
- Imports (line 6):
mysql.connector- connecting Python with MySQL,IntegrityErrorare loaded. - Global variables / constants are created:
SUBJ,conn,cur,TOTAL. - 10 functions are defined (lines 19โ112) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
grade(p) | 19โ23 | Grade | show() |
add() | 26โ43 | Add | main program (menu) |
show(rows) | 46โ51 | Show | display(), search() |
display() | 54โ56 | Display | main program (menu) |
search() | 59โ66 | Search | main program (menu) |
update() | 69โ78 | Update | main program (menu) |
delete() | 81โ85 | Delete | main program (menu) |
merit() | 88โ91 | Merit | main program (menu) |
result() | 94โ104 | Result | main program (menu) |
section_analysis() | 107โ112 | Section analysis | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Employee Payroll System (Binary File)
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
๐ฏ Objectives
- Use pickle for binary file handling
- Update records with a temporary file and os.replace()
- Compute salary components in a program
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
employee.dat | binary file | Pickled dict: code, name, dept, desig, basic, city |
HRA | dict | City class -> HRA percent |
DA, PF | float | 0.46 and 0.12 of basic |
pos | int | File position from tell() before reading a record |
temp.dat | binary file | Used while deleting |
# =====================================================================
# 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"))()
=====================================================================
EMPLOYEE PAYROLL SYSTEM (Binary File)
=====================================================================
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 1
Emp code : E01
Name : Sanjay Verma
Department : IT
Designation: Manager
Basic pay : 65000
City class X/Y/Z: X
Employee saved.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 1
Emp code : E02
Name : Pooja Rani
Department : Accounts
Designation: Accountant
Basic pay : 42000
City class X/Y/Z: Y
Employee saved.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 1
Emp code : E03
Name : Imran Ali
Department : IT
Designation: Developer
Basic pay : 52000
City class X/Y/Z: X
Employee saved.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 1
Emp code : E04
Name : Kiran Bala
Department : HR
Designation: Executive
Basic pay : 35000
City class X/Y/Z: Z
Employee saved.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 1
Emp code : E01
Employee code already exists.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 2
Code Name Dept Designation Basic Gross Net
---------------------------------------------------------------------
E01 Sanjay Verma IT Manager 65000 110500 102500
E02 Pooja Rani ACCOUNTS Accountant 42000 68040 62800
E03 Imran Ali IT Developer 52000 88400 81960
E04 Kiran Bala HR Executive 35000 53900 49500
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 3
Emp code: E01
======================================
SALARY SLIP - JULY 2026
Sanjay Verma (E01) - Manager, IT
--------------------------------------
Basic Rs. 65,000.00
DA (46%) Rs. 29,900.00
HRA (24%) Rs. 15,600.00
Gross Rs. 110,500.00
PF (12%) Rs. 7,800.00
Prof. Tax Rs. 200.00
Net Pay Rs. 102,500.00
======================================
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 4
Department: it
E01 Sanjay Verma Manager Net Rs. 102,500
E03 Imran Ali Developer Net Rs. 81,960
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 5
Emp code: E02
Increment %: 10
Basic of Pooja Rani raised from 42000 to 46200 (record at byte 109)
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 3
Emp code: E02
======================================
SALARY SLIP - JULY 2026
Pooja Rani (E02) - Accountant, ACCOUNTS
--------------------------------------
Basic Rs. 46,200.00
DA (46%) Rs. 21,252.00
HRA (16%) Rs. 7,392.00
Gross Rs. 74,844.00
PF (12%) Rs. 5,544.00
Prof. Tax Rs. 200.00
Net Pay Rs. 69,100.00
======================================
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 6
Emp code to delete: E04
Deleted.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 6
Emp code to delete: E99
Not found.
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 7
Department Staff Total Net Average
ACCOUNTS 1 69,100 69,100
IT 2 184,460 92,230
Monthly payroll: Rs. 253,560 | Highest paid: Sanjay Verma
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 8
Emp code: E01
Taxable income Rs. 1,251,000 -> Tax Rs. 67,650 + 4% cess = Rs. 70,356 per year
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 2
Code Name Dept Designation Basic Gross Net
---------------------------------------------------------------------
E01 Sanjay Verma IT Manager 65000 110500 102500
E02 Pooja Rani ACCOUNTS Accountant 46200 74844 69100
E03 Imran Ali IT Developer 52000 88400 81960
1.Add 2.Display 3.Salary Slip 4.Search Dept 5.Increment 6.Delete 7.Report 8.Tax 0.Exit
Enter choice: 0
Payroll closed.
- Start
- Display menu and read choice
- Choice is Increment? → No: run selected option
- Open employee.dat in rb+ mode
- pos = f.tell(); rec = pickle.load(f)
- rec code matches? → No: read next record
- f.seek(pos); pickle.dump(updated rec)
- Show new salary
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add E01 basic 45000 city X | Saved | PASS |
| 2 | Duplicate E01 | Refused | PASS |
| 3 | Salary slip E01 | DA, HRA, PF and net shown | PASS |
| 4 | Search dept 'IT' | IT employees listed | PASS |
| 5 | Increment 10 % to E02 | Basic updated in place | PASS |
| 6 | Delete E04 | Record removed | PASS |
| 7 | Delete E99 | 'Not found' | PASS |
| 8 | Payroll report | Dept totals | PASS |
| 9 | Tax estimate E01 | Tax as per slabs | PASS |
โ 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
- Imports (line 6):
pickle- writing / reading Python objects in binary files,os- file and folder operations are loaded. - Global variables / constants are created:
FILE,HRA. - 10 functions are defined (lines 13โ142) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
records() | 13โ22 | Records | add(), display(), slip(), search_dept() |
pay(e) | 25โ32 | Returns dict of salary components. | display(), slip(), search_dept(), report() |
add() | 35โ45 | Add | main program (menu) |
display() | 48โ53 | Display | main program (menu) |
slip() | 56โ68 | Slip | main program (menu) |
search_dept() | 71โ75 | Search dept | main program (menu) |
increment() | 78โ98 | In-place update using seek() and tell(). | main program (menu) |
delete() | 101โ115 | Delete | main program (menu) |
report() | 118โ126 | Report | main program (menu) |
tax() | 129โ142 | Simplified new-regime annual tax with standard deduction. | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: EMPLOYEE PAYROLL SYSTEM (Binary File) (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type E01 at Emp code :runs:
records() - You type Sanjay Verma at Name :
- You type IT at Department :
- You type Manager at Designation:
- You type 65000 at Basic pay :
- You type X at City class X/Y/Z:shows: Employee saved. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type E02 at Emp code :runs:
records() - You type Pooja Rani at Name :
- You type Accounts at Department :
- You type Accountant at Designation:
- You type 42000 at Basic pay :
- You type Y at City class X/Y/Z:shows: Employee saved. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type E03 at Emp code :runs:
records() - You type Imran Ali at Name :
- You type IT at Department :
- You type Developer at Designation:
- You type 52000 at Basic pay :
- You type X at City class X/Y/Z:shows: Employee saved. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type E04 at Emp code :runs:
records() - You type Kiran Bala at Name :
- You type HR at Department :
- You type Executive at Designation:
- You type 35000 at Basic pay :
- You type Z at City class X/Y/Z:shows: Employee saved. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type E01 at Emp code :runs:
records()shows: Employee code already exists. (+1 more lines) - You type 2 at Enter choice:runs:
display()โrecords()โpay()ร4shows: Code Name Dept Designation Basic Gross Net (+5 more lines) - You type 3 at Enter choice:runs:
slip() - You type E01 at Emp code:runs:
records()โpay()shows: SALARY SLIP - JULY 2026 (+9 more lines) - You type 4 at Enter choice:runs:
search_dept() - You type it at Department:runs:
records()โpay()ร2shows: E01 Sanjay Verma Manager Net Rs. 102,500 (+2 more lines) - You type 5 at Enter choice:runs:
increment() - You type E02 at Emp code:
- You type 10 at Increment %:shows: Basic of Pooja Rani raised from 42000 to 46200 (record at byte 109) (+1 more lines)
- 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Railway Reservation System (Python + MySQL)
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
๐ฏ Objectives
- Design two related tables and join them
- Update seat availability atomically with commit()
- Use lastrowid to obtain the generated PNR
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
train | MySQL table | tno PK, name, source, dest, sl, ac3, ac2 (available seats) |
booking | MySQL table | pnr PK AUTO_INCREMENT (from 4501), tno FK, name, age, cls, fare, status |
FARE | dict | Class -> base fare per train |
lastrowid | int | Generated PNR |
# =====================================================================
# 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.")
==============================================================
INDIAN RAILWAYS - RESERVATION SYSTEM (Python + MySQL)
==============================================================
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 1
No Train From To SL 3A 2A
12301 Howrah Rajdhani Howrah New Delhi 4 3 1
12425 Rajdhani Express New Delhi Jammu Tawi 3 2 2
12951 Mumbai Rajdhani Mumbai New Delhi 5 4 2
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 12425
Passenger name: Amit Sharma
Age : 35
Class SL/3A/2A: SL
--------------------------------------------
PNR 4501 | Rajdhani Express (12425)
Amit Sharma, 35 yrs | Class SL | Fare Rs. 545.00 | CNF
--------------------------------------------
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 12425
Passenger name: Kamla Devi
Age : 66
Class SL/3A/2A: SL
--------------------------------------------
PNR 4502 | Rajdhani Express (12425)
Kamla Devi, 66 yrs | Class SL | Fare Rs. 327.00 | CNF
--------------------------------------------
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 12425
Passenger name: Rahul Sharma
Age : 8
Class SL/3A/2A: SL
--------------------------------------------
PNR 4503 | Rajdhani Express (12425)
Rahul Sharma, 8 yrs | Class SL | Fare Rs. 272.50 | CNF
--------------------------------------------
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 12425
Passenger name: Sneha Joshi
Age : 24
Class SL/3A/2A: SL
--------------------------------------------
PNR 4504 | Rajdhani Express (12425)
Sneha Joshi, 24 yrs | Class SL | Fare Rs. 545.00 | WL1
--------------------------------------------
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 12425
Passenger name: Vikas Rana
Age : 30
Class SL/3A/2A: 3A
--------------------------------------------
PNR 4505 | Rajdhani Express (12425)
Vikas Rana, 30 yrs | Class 3A | Fare Rs. 1430.00 | CNF
--------------------------------------------
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 2
Train no : 11111
Passenger name: Test
Age : 20
Class SL/3A/2A: SL
Train not found / invalid class.
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 3
PNR: 4504
PNR 4504: Sneha Joshi (24) | Rajdhani Express New Delhi -> Jammu Tawi | SL | Rs. 545.00 | Status: WL1
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 4
PNR to cancel: 4501
Ticket of Amit Sharma cancelled. Refund Rs. 485.00 (deduction Rs. 60)
Waiting passenger Sneha Joshi (PNR 4504) is now CONFIRMED.
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 3
PNR: 4504
PNR 4504: Sneha Joshi (24) | Rajdhani Express New Delhi -> Jammu Tawi | SL | Rs. 545.00 | Status: CNF
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 4
PNR to cancel: 9999
Invalid PNR.
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 5
Train no: 12425
PNR Name Age Cls Status
4505 Vikas Rana 30 3A CNF
4502 Kamla Devi 66 SL CNF
4503 Rahul Sharma 8 SL CNF
4504 Sneha Joshi 24 SL CNF
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 6
Rajdhani Express tickets 4 revenue Rs. 2574.50
Mumbai Rajdhani tickets 0 revenue Rs. 0.00
Howrah Rajdhani tickets 0 revenue Rs. 0.00
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 1
No Train From To SL 3A 2A
12301 Howrah Rajdhani Howrah New Delhi 4 3 1
12425 Rajdhani Express New Delhi Jammu Tawi 0 1 2
12951 Mumbai Rajdhani Mumbai New Delhi 5 4 2
1.Trains 2.Book 3.PNR Status 4.Cancel 5.Chart 6.Revenue 0.Exit
Enter choice: 0
Happy journey!
- Start
- Create railway_db, train and booking tables
- Display menu and read choice
- Choice is Book? → No: run selected option
- Read train, name, age, class
- Seats available? → No: status = WL n
- Reduce seat, status = CNF
- Compute fare with concession, INSERT, COMMIT
- Print ticket with PNR
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Book SL on 12425 | CNF, seat reduced | PASS |
| 2 | Senior citizen age 65 | 40 % concession | PASS |
| 3 | Child age 8 | 50 % fare | PASS |
| 4 | Seats over | Status WL1 | PASS |
| 5 | Invalid train 11111 | 'Train not found' | PASS |
| 6 | PNR status | Joined details | PASS |
| 7 | Cancel CNF ticket | Refund and WL1 confirmed | PASS |
| 8 | Cancel unknown PNR | 'Invalid PNR' | PASS |
| 9 | Chart | Sorted passengers | PASS |
| 10 | Revenue | Train-wise totals | PASS |
โ 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
- Imports (line 6):
mysql.connector- connecting Python with MySQL are loaded. - Global variables / constants are created:
FARE,COL,CANCEL,conn,cur. - 7 functions are defined (lines 29โ113) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
trains() | 29โ33 | Trains | main program (menu) |
concession(age) | 36โ37 | Concession | book() |
book() | 40โ63 | Book | main program (menu) |
pnr_status(pnr) | 66โ74 | Pnr status | main program (menu) |
cancel() | 77โ98 | Cancel | main program (menu) |
chart() | 101โ106 | Chart | main program (menu) |
revenue() | 109โ113 | Revenue | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Browser History Manager (Stack)
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
๐ฏ Objectives
- Implement the Stack data structure with a list
- Apply push, pop, peek and isEmpty operations
- Model a real-life LIFO problem
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
back_stack | list (stack) | Pages before the current page |
forward_stack | list (stack) | Pages after the current page (after Back) |
current | str | Page on screen |
MAX | int | Stack size limit (overflow) |
bookmarks.txt | text file | One URL per line |
history.csv | CSV file | visit_no, url |
# =====================================================================
# 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"))()
========================================================
BROWSER HISTORY MANAGER (Stack)
========================================================
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.google.com
Now on: www.google.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.cbse.gov.in
Now on: www.cbse.gov.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: kvsangathan.nic.in
Now on: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: abc
Invalid URL.
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.python.org
Now on: www.python.org
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 5
BACK STACK FORWARD STACK
| kvsangathan.nic.in | <-top | |
| www.cbse.gov.in | | |
| www.google.com | | |
| home | | |
+--------------------+ +--------------------+
Current page: www.python.org
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: www.cbse.gov.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 4
Current page : www.cbse.gov.in
Back top : www.google.com
Forward top : kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 3
-> Forward to: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 5
BACK STACK FORWARD STACK
| www.cbse.gov.in | <-top | |
| www.google.com | | |
| home | | www.python.org |
+--------------------+ +--------------------+
Current page: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 6
Bookmarked: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.w3schools.com
Now on: www.w3schools.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 5
BACK STACK FORWARD STACK
| kvsangathan.nic.in | <-top | |
| www.cbse.gov.in | | |
| www.google.com | | |
| home | | |
+--------------------+ +--------------------+
Current page: www.w3schools.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: www.cbse.gov.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: www.google.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
<- Back to: home
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 3
-> Forward to: www.google.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 3
-> Forward to: www.cbse.gov.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 3
-> Forward to: kvsangathan.nic.in
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 3
-> Forward to: www.w3schools.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.google.com
Now on: www.google.com
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 1
Enter URL: www.python.org
Now on: www.python.org
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 6
Bookmarked: www.python.org
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 7
1. kvsangathan.nic.in
2. www.python.org
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 8
Visit log: 1:www.google.com | 2:www.cbse.gov.in | 3:kvsangathan.nic.in | 4:www.python.org | 5:www.w3schools.com | 6:www.google.com | 7:www.python.org
Most visited:
www.google.com ## 2
www.python.org ## 2
www.cbse.gov.in # 1
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 9
History cleared. Back and Forward stacks are empty.
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 2
Underflow! No previous page.
1.Visit 2.Back 3.Forward 4.Current 5.Stacks 6.Bookmark 7.Bookmarks 8.History 9.Clear 0.Exit
Enter choice: 0
Browser closed.
- Start
- Display menu and read choice
- Choice is Back? → No: Visit / Forward / other option
- back_stack empty? → No: forward.push(current); current = back.pop()
- 'Underflow - no previous page'
- Show current page
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Visit google.com | Current = google.com | PASS |
| 2 | Visit 3 more pages | Back stack holds 3 | PASS |
| 3 | Back twice | Forward stack holds 2 | PASS |
| 4 | Forward once | Moves one page ahead | PASS |
| 5 | Visit after Back | Forward stack cleared | PASS |
| 6 | Back with empty stack | Underflow message | PASS |
| 7 | Forward with empty stack | Underflow message | PASS |
| 8 | Visit invalid 'abc' | 'Invalid URL' | PASS |
| 9 | Bookmark | Saved in file | PASS |
| 10 | Most visited | Counts from history.csv | PASS |
โ 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
- Imports (line 6):
csv- reading / writing CSV files,os- file and folder operations are loaded. - Global variables / constants are created:
MAX,current,visits. - 13 functions are defined (lines 14โ115) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
is_empty(stk) | 14โ15 | Is empty | pop(), peek(), back(), forward() |
push(stk, item) | 18โ22 | Push | visit(), back(), forward() |
pop(stk) | 25โ26 | Pop | back(), forward() |
peek(stk) | 29โ30 | Peek | show_current() |
visit() | 33โ44 | Visit | main program (menu) |
back() | 47โ54 | Back | main program (menu) |
forward() | 57โ64 | Forward | main program (menu) |
show_current() | 67โ70 | Show current | main program (menu) |
show_stacks() | 73โ82 | Show stacks | main program (menu) |
add_bookmark() | 85โ88 | Add bookmark | main program (menu) |
show_bookmarks() | 91โ97 | Show bookmarks | main program (menu) |
history() | 100โ109 | History | main program (menu) |
clear() | 112โ115 | Clear | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: BROWSER HISTORY MANAGER (Stack) (+1 more lines)
- You type 1 at Enter choice:runs:
visit() - You type www.google.com at Enter URL:runs:
push()shows: Now on: www.google.com (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type www.cbse.gov.in at Enter URL:runs:
push()shows: Now on: www.cbse.gov.in (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type kvsangathan.nic.in at Enter URL:runs:
push()shows: Now on: kvsangathan.nic.in (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type abc at Enter URL:shows: Invalid URL. (+1 more lines)
- You type 1 at Enter choice:runs:
visit() - You type www.python.org at Enter URL:runs:
push()shows: Now on: www.python.org (+1 more lines) - You type 5 at Enter choice:runs:
show_stacks()shows: BACK STACK FORWARD STACK (+7 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: kvsangathan.nic.in (+1 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: www.cbse.gov.in (+1 more lines) - 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) - You type 3 at Enter choice:runs:
forward()โis_empty()โpush()โpop()โis_empty()shows: -> Forward to: kvsangathan.nic.in (+1 more lines) - You type 5 at Enter choice:runs:
show_stacks()shows: BACK STACK FORWARD STACK (+6 more lines) - You type 6 at Enter choice:runs:
add_bookmark()shows: Bookmarked: kvsangathan.nic.in (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type www.w3schools.com at Enter URL:runs:
push()shows: Now on: www.w3schools.com (+1 more lines) - You type 5 at Enter choice:runs:
show_stacks()shows: BACK STACK FORWARD STACK (+7 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: kvsangathan.nic.in (+1 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: www.cbse.gov.in (+1 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: www.google.com (+1 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()โpush()โpop()โis_empty()shows: <- Back to: home (+1 more lines) - You type 3 at Enter choice:runs:
forward()โis_empty()โpush()โpop()โis_empty()shows: -> Forward to: www.google.com (+1 more lines) - You type 3 at Enter choice:runs:
forward()โis_empty()โpush()โpop()โis_empty()shows: -> Forward to: www.cbse.gov.in (+1 more lines) - You type 3 at Enter choice:runs:
forward()โis_empty()โpush()โpop()โis_empty()shows: -> Forward to: kvsangathan.nic.in (+1 more lines) - You type 3 at Enter choice:runs:
forward()โis_empty()โpush()โpop()โis_empty()shows: -> Forward to: www.w3schools.com (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type www.google.com at Enter URL:runs:
push()shows: Now on: www.google.com (+1 more lines) - You type 1 at Enter choice:runs:
visit() - You type www.python.org at Enter URL:runs:
push()shows: Now on: www.python.org (+1 more lines) - You type 6 at Enter choice:runs:
add_bookmark()shows: Bookmarked: www.python.org (+1 more lines) - You type 7 at Enter choice:runs:
show_bookmarks()shows: 1. kvsangathan.nic.in (+2 more lines) - 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) - You type 9 at Enter choice:runs:
clear()shows: History cleared. Back and Forward stacks are empty. (+1 more lines) - You type 2 at Enter choice:runs:
back()โis_empty()shows: Underflow! No previous page. (+1 more lines) - You type 0 at Enter choice:shows: Browser closed.
โค Inside each function - line by line
is_empty() - lines 14โ15
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Hotel Management System (Python + MySQL)
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
๐ฏ Objectives
- Maintain room status with UPDATE queries
- Calculate bills with GST in Python
- Generate reports with JOIN and GROUP BY
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
room | MySQL table | rno PK, rtype, tariff, status |
guest | MySQL table | gid PK, name, idproof, rno, checkin DATE, checkout DATE, service, total |
service | MySQL table | gid, item, amount |
GST | function | 12 % if tariff <= 7500 else 18 % |
# =====================================================================
# 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.")
==================================================
HOTEL MANAGEMENT SYSTEM (Python + MySQL)
==================================================
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 1
Room Type Tariff Status
101 Standard 3500 Available
102 Standard 3500 Available
103 Standard 3500 Available
201 Deluxe 6000 Available
202 Deluxe 6000 Available
301 Suite 12000 Available
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 2
Room type (Standard/Deluxe/Suite): Deluxe
Available Deluxe rooms: 201 (Rs. 6000), 202 (Rs. 6000)
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 3
Room no : 101
Guest name: Rajesh Gupta
ID proof : Aadhaar
Check-in date (yyyy-mm-dd): 2026-07-10
Welcome Rajesh Gupta! Room 101 allotted. Guest ID 1
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 3
Room no : 201
Guest name: Meena Iyer
ID proof : PAN
Check-in date (yyyy-mm-dd): 2026-07-11
Welcome Meena Iyer! Room 201 allotted. Guest ID 2
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 3
Room no : 301
Guest name: Thomas George
ID proof : Passport
Check-in date (yyyy-mm-dd): 2026-07-11
Welcome Thomas George! Room 301 allotted. Guest ID 3
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 3
Room no : 101
Guest name: Anil
ID proof : PAN
Check-in date (yyyy-mm-dd): 2026-07-12
Room not available.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 3
Room no : 999
No such room.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 4
Room no : 201
Item : Dinner
Amount : 1250
Rs. 1250 for Dinner added to Meena Iyer's bill.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 4
Room no : 201
Item : Laundry
Amount : 300
Rs. 300 for Laundry added to Meena Iyer's bill.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 4
Room no : 101
Item : Breakfast
Amount : 450
Rs. 450 for Breakfast added to Rajesh Gupta's bill.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 6
Guest 1: Rajesh Gupta Room 101 (Standard) since 2026-07-10
Guest 2: Meena Iyer Room 201 (Deluxe) since 2026-07-11
Guest 3: Thomas George Room 301 (Suite) since 2026-07-11
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 8
Occupied 3/6 rooms -> occupancy 50.0%
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 5
Room no : 201
Check-out date (yyyy-mm-dd): 2026-07-10
Invalid date - check-out must be after check-in.
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 5
Room no : 201
Check-out date (yyyy-mm-dd): 2026-07-14
============================================
HOTEL KV RESIDENCY - BILL
Guest: Meena Iyer Room 201 (Deluxe)
Stay : 2026-07-11 to 2026-07-14 (3 nights)
--------------------------------------------
Room charges 3 x 6000 18,000.00
Dinner 1,250.00
Laundry 300.00
GST on room @ 12% 2,160.00
TOTAL 21,710.00
============================================
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 5
Room no : 101
Check-out date (yyyy-mm-dd): 2026-07-12
============================================
HOTEL KV RESIDENCY - BILL
Guest: Rajesh Gupta Room 101 (Standard)
Stay : 2026-07-10 to 2026-07-12 (2 nights)
--------------------------------------------
Room charges 2 x 3500 7,000.00
Breakfast 450.00
GST on room @ 12% 840.00
TOTAL 8,290.00
============================================
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 7
Type Stays Revenue
Deluxe 1 21,710.00
Standard 1 8,290.00
Suite 0 0.00
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 2
Room type (Standard/Deluxe/Suite): Deluxe
Available Deluxe rooms: 201 (Rs. 6000), 202 (Rs. 6000)
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 8
Occupied 1/6 rooms -> occupancy 16.7%
1.Rooms 2.Available 3.Check-in 4.Service 5.Check-out 6.Guests 7.Revenue 8.Occupancy 0.Exit
Enter choice: 0
Thank you!
- Start
- Create hotel_db tables and rooms
- Display menu and read choice
- Choice is Check-out? → No: run selected option
- Read room number and checkout date
- nights = (checkout - checkin).days
- Bill = nights x tariff + service + GST
- UPDATE guest and room status, COMMIT
- Print bill
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Check-in room 101 | Room Occupied | PASS |
| 2 | Check-in occupied room | 'Room not available' | PASS |
| 3 | Room 999 | 'No such room' | PASS |
| 4 | Room service Rs. 450 | Added to guest | PASS |
| 5 | Check-out after 3 nights | 3 x tariff + GST | PASS |
| 6 | Checkout before checkin | 'Invalid date' | PASS |
| 7 | Available Deluxe | Only free Deluxe rooms | PASS |
| 8 | Revenue report | Type-wise totals | PASS |
| 9 | Occupancy | Percentage | PASS |
โ 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
- Imports (line 6):
mysql.connector- connecting Python with MySQL,dateare loaded. - Global variables / constants are created:
conn,cur. - 10 functions are defined (lines 25โ134) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
gst_rate(tariff) | 25โ26 | Gst rate | check_out() |
show_rooms() | 29โ33 | Show rooms | main program (menu) |
available() | 36โ40 | Available | main program (menu) |
guest_in(rno) | 43โ45 | Guest in | room_service(), check_out() |
check_in() | 48โ65 | Check in | main program (menu) |
room_service() | 68โ77 | Room service | main program (menu) |
check_out() | 80โ113 | Check out | main program (menu) |
current_guests() | 116โ120 | Current guests | main program (menu) |
revenue() | 123โ128 | Revenue | main program (menu) |
occupancy() | 131โ134 | Occupancy | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
School Result Analytics Dashboard
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
๐ฏ Objectives
- Create and display a DataFrame
- Use groupby() and boolean filtering
- Plot and save a bar chart with Matplotlib
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Name, Section, Eng, Maths, Phy, Chem, IP + calculated columns |
SUBJ | list | Subject column names |
grade() | function | CBSE grade from percentage |
sec | DataFrame | Result of groupby('Section') |
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"))()
============================================================
SCHOOL RESULT ANALYTICS DASHBOARD
============================================================
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 1
Name Section Eng Maths Phy Chem IP Total Percent Grade Result
1 Amit A 88 95 84 80 97 444 88.8 A2 PASS
2 Sara A 92 89 90 93 96 460 92.0 A1 PASS
3 Rahul B 65 58 62 60 71 316 63.2 B2 PASS
4 Priya B 78 82 75 79 88 402 80.4 B1 PASS
5 Karan A 55 30 38 44 61 228 45.6 C2 COMPT
6 Neha C 81 77 70 73 90 391 78.2 B1 PASS
7 Arjun C 47 41 35 39 52 214 42.8 C2 PASS
8 Ishita B 90 94 88 91 98 461 92.2 A1 PASS
9 Vikram A 72 68 66 64 80 350 70.0 B2 PASS
10 Zoya C 85 79 81 76 93 414 82.8 A2 PASS
11 Manav B 60 52 57 49 67 285 57.0 C1 PASS
12 Divya C 74 88 69 72 85 388 77.6 B1 PASS
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 2
Eng Maths Phy Chem IP
count 12.00 12.00 12.00 12.00 12.00
mean 73.92 71.08 67.92 68.33 81.50
std 14.56 21.45 17.87 17.53 15.36
min 47.00 30.00 35.00 39.00 52.00
25% 63.75 56.50 60.75 57.25 70.00
50% 76.00 78.00 69.50 72.50 86.50
75% 85.75 88.25 81.75 79.25 93.75
max 92.00 95.00 90.00 93.00 98.00
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 3
Students Avg_Percent Highest Pass_%
Section
A 4 74.10 460 75.0
B 4 73.20 461 100.0
C 4 70.35 414 100.0
Best section: A
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 4
Eng : Sara (92)
Maths : Amit (95)
Phy : Sara (90)
Chem : Sara (93)
IP : Ishita (98)
Overall topper: Ishita
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 5
Name Section Total Percent Grade
8 Ishita B 461 92.2 A1
2 Sara A 460 92.0 A1
1 Amit A 444 88.8 A2
10 Zoya C 414 82.8 A2
4 Priya B 402 80.4 B1
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 6
Enter name: priya
4
Name Priya
Section B
Eng 78
Maths 82
Phy 75
Chem 79
IP 88
Total 402
Percent 80.4
Grade B1
Result PASS
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 6
Enter name: xyz
Not found.
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 7
4 charts saved: subject_avg.png, grade_pie.png, section_compare.png, marks_hist.png
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 8
Saved result_analysis.csv -> 12 rows
1.Result Sheet 2.Statistics 3.Sections 4.Toppers 5.Merit 6.Search 7.Charts 8.Export 0.Exit
Enter choice: 0
Analysis complete.
- Start
- Create DataFrame and calculated columns
- Display menu and read choice
- Choice is Charts? → No: run the selected analysis
- Plot bar, pie, bar and histogram
- savefig() and show()
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Option 1 | 12 rows with Total, %, Grade | PASS |
| 2 | Option 2 | count, mean, std, min, max | PASS |
| 3 | Option 3 | Average of A, B, C | PASS |
| 4 | Option 4 | Topper per subject | PASS |
| 5 | Option 5 | Top 5 by total | PASS |
| 6 | Search 'priya' | Her row shown | PASS |
| 7 | Search 'xyz' | 'Not found' | PASS |
| 8 | Option 7 | 4 PNG files | PASS |
| 9 | Option 8 | CSV created | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
SUBJ,data,df. - 9 functions are defined (lines 19โ84) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
grade(p) | 19โ23 | Grade | main program (menu) |
sheet() | 32โ33 | Sheet | main program (menu) |
stats() | 36โ37 | Stats | main program (menu) |
sections() | 40โ44 | Sections | main program (menu) |
toppers() | 47โ51 | Toppers | main program (menu) |
merit() | 54โ55 | Merit | main program (menu) |
search() | 58โ61 | Search | main program (menu) |
charts() | 64โ79 | Charts | main program (menu) |
export() | 82โ84 | Export | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
grade()ร12shows: SCHOOL RESULT ANALYTICS DASHBOARD (+1 more lines) - You type 1 at Enter choice:runs:
sheet()shows: Name Section Eng Maths Phy Chem IP Total Percent Grade Result (+13 more lines) - You type 2 at Enter choice:runs:
stats()shows: Eng Maths Phy Chem IP (+9 more lines) - You type 3 at Enter choice:runs:
sections()shows: Students Avg_Percent Highest Pass_% (+6 more lines) - You type 4 at Enter choice:runs:
toppers()shows: Eng : Sara (92) (+6 more lines) - You type 5 at Enter choice:runs:
merit()shows: Name Section Total Percent Grade (+6 more lines) - You type 6 at Enter choice:runs:
search() - You type priya at Enter name:shows: 4 (+12 more lines)
- You type 6 at Enter choice:runs:
search() - You type xyz at Enter name:shows: Not found. (+1 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+5 more lines) - You type 8 at Enter choice:runs:
export()shows: Saved result_analysis.csv -> 12 rows (+1 more lines) - You type 0 at Enter choice:shows: Analysis complete.
โค Inside each function - line by line
grade() - lines 19โ23
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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().
Household / Shop Expenditure Analyzer
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
๐ฏ Objectives
- Read and write CSV files with Pandas
- Clean data using drop_duplicates()
- Visualise proportions with a pie chart
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
exp | DataFrame | Date, Category, Item, Amount, Mode |
expenses.csv | CSV file | Permanent storage |
BUDGET | dict | Category -> monthly budget |
Month | column | Derived with dt.strftime('%b') |
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.")
============================================================
HOUSEHOLD EXPENDITURE ANALYZER
============================================================
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 1
Date Category Item Amount Mode Month
0 2026-01-03 Grocery Monthly ration 5200 UPI Jan
1 2026-01-05 Bills Electricity 2350 UPI Jan
2 2026-01-08 Education School fee 4500 Netbanking Jan
3 2026-01-12 Transport Petrol 2100 Card Jan
4 2026-01-20 Entertainment Movie 900 UPI Jan
5 2026-01-25 Health Medicines 650 Cash Jan
6 2026-02-02 Grocery Monthly ration 5600 UPI Feb
7 2026-02-06 Bills Mobile + WiFi 1450 UPI Feb
8 2026-02-10 Bills Electricity 2780 UPI Feb
9 2026-02-14 Entertainment Dinner out 2400 Card Feb
10 2026-02-18 Transport Petrol 2600 Card Feb
11 2026-02-22 Education Books 1800 Cash Feb
12 2026-03-01 Grocery Monthly ration 6100 UPI Mar
13 2026-03-04 Health Doctor visit 1500 Cash Mar
14 2026-03-09 Bills Electricity 3120 UPI Mar
15 2026-03-15 Transport Car service 3400 Card Mar
16 2026-03-21 Entertainment Holi party 1800 Cash Mar
17 2026-03-26 Education Coaching 3500 Netbanking Mar
Records: 18 | Total spent: Rs. 51,750
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 2
Date (yyyy-mm-dd): 2026-03-28
Category: Grocery
Item: Fruits & vegetables
Amount: 450
Mode (UPI/Cash/Card/Netbanking): UPI
Expense saved. Total records: 19
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 2
Date (yyyy-mm-dd): 2026-03-29
Category: Food
Item: Pizza
Amount: -5
Mode (UPI/Cash/Card/Netbanking): Cash
Invalid amount or category. Not saved.
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 3
Index to delete: 3
Deleted: Petrol 2100.0
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 4
count sum mean Share_%
Category
Grocery 4 17350.0 4337.5 34.6
Education 3 9800.0 3266.7 19.6
Bills 4 9700.0 2425.0 19.4
Transport 2 6000.0 3000.0 12.0
Entertainment 3 5100.0 1700.0 10.2
Health 2 2150.0 1075.0 4.3
Highest spending: Grocery
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 5
Category Bills Education Entertainment Grocery Health Transport TOTAL
Month
Jan 2350.0 4500.0 900.0 5200.0 650.0 0.0 13600.0
Feb 4230.0 1800.0 2400.0 5600.0 0.0 2600.0 16630.0
Mar 3120.0 3500.0 1800.0 6550.0 1500.0 3400.0 19870.0
Month-on-month change in total (%):
Month
Jan 0.0
Feb 22.3
Mar 19.5
Name: TOTAL, dtype: float64
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 6
Budget Avg_Spent Status
Bills 5000 3233.0 Within
Education 6000 3267.0 Within
Entertainment 2500 1700.0 Within
Grocery 8000 5783.0 Within
Health 2000 717.0 Within
Transport 3000 2000.0 Within
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 7
Filter by (category/mode/amount): mode
Value: UPI
Date Category Item Amount Mode
0 2026-01-03 Grocery Monthly ration 5200.0 UPI
1 2026-01-05 Bills Electricity 2350.0 UPI
3 2026-01-20 Entertainment Movie 900.0 UPI
5 2026-02-02 Grocery Monthly ration 5600.0 UPI
6 2026-02-06 Bills Mobile + WiFi 1450.0 UPI
7 2026-02-10 Bills Electricity 2780.0 UPI
11 2026-03-01 Grocery Monthly ration 6100.0 UPI
13 2026-03-09 Bills Electricity 3120.0 UPI
17 2026-03-28 Grocery Fruits & vegetables 450.0 UPI
Rows: 9 | Sum: Rs. 27950.0
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 7
Filter by (category/mode/amount): amount
Value: 2000
Date Category Item Amount Mode
0 2026-01-03 Grocery Monthly ration 5200.0 UPI
1 2026-01-05 Bills Electricity 2350.0 UPI
2 2026-01-08 Education School fee 4500.0 Netbanking
5 2026-02-02 Grocery Monthly ration 5600.0 UPI
7 2026-02-10 Bills Electricity 2780.0 UPI
8 2026-02-14 Entertainment Dinner out 2400.0 Card
9 2026-02-18 Transport Petrol 2600.0 Card
11 2026-03-01 Grocery Monthly ration 6100.0 UPI
13 2026-03-09 Bills Electricity 3120.0 UPI
14 2026-03-15 Transport Car service 3400.0 Card
16 2026-03-26 Education Coaching 3500.0 Netbanking
Rows: 11 | Sum: Rs. 41550.0
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 8
Charts saved: expense_pie.png, monthly_trend.png, budget_vs_actual.png
1.View 2.Add 3.Delete 4.Summary 5.Monthly Pivot 6.Budget 7.Filter 8.Charts 0.Exit
Enter choice: 0
Data saved in expenses.csv
- Start
- Create / read expenses.csv into DataFrame
- Display menu and read choice
- Choice is Add? → No: run selected analysis
- Read date, category, item, amount, mode
- Amount > 0 and category valid? → No: show error
- Append row with pd.concat and to_csv()
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | View | All rows | PASS |
| 2 | Add Rs. 450 Grocery | Row added, file saved | PASS |
| 3 | Add amount -5 | Rejected | PASS |
| 4 | Delete index 3 | Row removed | PASS |
| 5 | Category summary | Totals and % share | PASS |
| 6 | Monthly pivot | Month x category table | PASS |
| 7 | Budget check | Over-budget categories flagged | PASS |
| 8 | Filter Mode = UPI | Only UPI rows | PASS |
| 9 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,os- file and folder operations are loaded. - Global variables / constants are created:
FILE,CATS,BUDGET,rows. - 9 functions are defined (lines 24โ114) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
load() | 24โ27 | Load | view(), summary(), pivot(), budget() |
view() | 30โ33 | View | main program (menu) |
add() | 36โ48 | Add | main program (menu) |
delete() | 51โ58 | Delete | main program (menu) |
summary() | 61โ66 | Summary | main program (menu) |
pivot() | 69โ76 | Pivot | main program (menu) |
budget() | 79โ84 | Budget | main program (menu) |
filt() | 87โ98 | Filt | main program (menu) |
charts() | 101โ114 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HOUSEHOLD EXPENDITURE ANALYZER (+1 more lines)
- You type 1 at Enter choice:runs:
view()โload()shows: Date Category Item Amount Mode Month (+20 more lines) - You type 2 at Enter choice:runs:
add() - You type 2026-03-28 at Date (yyyy-mm-dd):
- You type Grocery at Category:
- You type Fruits & vegetables at Item:
- You type 450 at Amount:
- You type UPI at Mode (UPI/Cash/Card/Netbanking):shows: Expense saved. Total records: 19 (+1 more lines)
- You type 2 at Enter choice:runs:
add() - You type 2026-03-29 at Date (yyyy-mm-dd):
- You type Food at Category:
- You type Pizza at Item:
- You type -5 at Amount:
- You type Cash at Mode (UPI/Cash/Card/Netbanking):shows: Invalid amount or category. Not saved. (+1 more lines)
- You type 3 at Enter choice:runs:
delete() - You type 3 at Index to delete:shows: Deleted: Petrol 2100.0 (+1 more lines)
- You type 4 at Enter choice:runs:
summary()โload()shows: count sum mean Share_% (+9 more lines) - You type 5 at Enter choice:runs:
pivot()โload()shows: Category Bills Education Entertainment Grocery Health Transport TOTAL (+11 more lines) - You type 6 at Enter choice:runs:
budget()โload()shows: Budget Avg_Spent Status (+7 more lines) - You type 7 at Enter choice:runs:
filt()โload() - You type mode at Filter by (category/mode/amount):
- You type UPI at Value:shows: Date Category Item Amount Mode (+11 more lines)
- You type 7 at Enter choice:runs:
filt()โload() - You type amount at Filter by (category/mode/amount):
- You type 2000 at Value:shows: Date Category Item Amount Mode (+13 more lines)
- You type 8 at Enter choice:runs:
charts()โload()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Data saved in expenses.csv
โค Inside each function - line by line
load() - lines 24โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Open Government Data Explorer
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
๐ฏ Objectives
- Load and explore a dataset with describe()
- Sort a DataFrame using sort_values()
- Create a customised bar chart
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
census | DataFrame | State, Region, Population (lakh), Literacy, Male, Female, SexRatio |
census_data.csv | CSV file | Downloaded / saved open data |
Gap | column | Male - Female literacy |
Rank | column | rank(ascending=False) |
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.")
Dataset loaded: 15 states x 9 columns
============================================================
OPEN GOVERNMENT DATA EXPLORER
============================================================
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 1
State Region Population Literacy Male Female SexRatio Gap Rank
0 Kerala South 334.1 94.0 96.1 92.1 1084 4.0 1
1 Mizoram North-East 10.9 91.3 93.3 89.3 976 4.0 2
2 Goa West 14.6 88.7 92.6 84.7 973 7.9 3
3 Tripura North-East 36.7 87.2 91.5 82.7 960 8.8 4
4 Himachal Pradesh North 68.6 82.8 89.5 75.9 972 13.6 5
5 Maharashtra West 1123.7 82.3 88.4 75.9 929 12.5 6
6 Tamil Nadu South 721.5 80.1 86.8 73.4 996 13.4 7
7 Punjab North 277.4 75.8 80.4 70.7 895 9.7 10
8 Gujarat West 604.4 78.0 85.8 69.7 919 16.1 8
9 West Bengal East 912.8 76.3 81.7 70.5 950 11.2 9
10 Karnataka South 610.9 75.4 82.5 68.1 973 14.4 11
11 Odisha East 419.7 72.9 81.6 64.0 979 17.6 12
12 Uttar Pradesh North 1998.1 67.7 77.3 57.2 912 20.1 13
13 Rajasthan North 685.5 66.1 79.2 52.1 928 27.1 14
14 Bihar East 1041.0 61.8 71.2 51.5 918 19.7 15
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 2
TOP 5 LITERATE STATES
State Literacy Rank
Kerala 94.0 1
Mizoram 91.3 2
Goa 88.7 3
Tripura 87.2 4
Himachal Pradesh 82.8 5
BOTTOM 5 STATES
State Literacy Rank
Bihar 61.8 15
Rajasthan 66.1 14
Uttar Pradesh 67.7 13
Odisha 72.9 12
Karnataka 75.4 11
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 3
State Male Female Gap
Rajasthan 79.2 52.1 27.1
Uttar Pradesh 77.3 57.2 20.1
Bihar 71.2 51.5 19.7
Odisha 81.6 64.0 17.6
Gujarat 85.8 69.7 16.1
Karnataka 82.5 68.1 14.4
Himachal Pradesh 89.5 75.9 13.6
Tamil Nadu 86.8 73.4 13.4
Maharashtra 88.4 75.9 12.5
West Bengal 81.7 70.5 11.2
Punjab 80.4 70.7 9.7
Tripura 91.5 82.7 8.8
Goa 92.6 84.7 7.9
Kerala 96.1 92.1 4.0
Mizoram 93.3 89.3 4.0
Largest gender gap: Rajasthan (27.1 points) | Smallest: Mizoram (4.0)
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 4
States Avg_Literacy Avg_SexRatio Population
Region
North-East 2 89.2 968.0 47.6
South 3 83.2 1017.7 1666.5
West 3 83.0 940.3 1742.7
North 4 73.1 926.8 3029.6
East 3 70.3 949.0 2373.5
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 5
State name: kerala
State Kerala
Region South
Population 334.1
Literacy 94.0
Male 96.1
Female 92.1
SexRatio 1084
Gap 4.0
Rank 1
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 6
Column (Literacy/Female/SexRatio/Population): SexRatio
Value: 950
State SexRatio
Kerala 1084
Mizoram 976
Goa 973
Tripura 960
Himachal Pradesh 972
Tamil Nadu 996
Karnataka 973
Odisha 979
8 states have SexRatio > 950.0
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 7
Literacy Female SexRatio Population
Literacy 1.00 0.99 0.65 -0.64
Female 0.99 1.00 0.64 -0.64
SexRatio 0.65 0.64 1.00 -0.41
Population -0.64 -0.64 -0.41 1.00
Literacy vs Sex ratio correlation: 0.65
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 8
Charts saved: literacy_bar.png, gender_gap.png, literacy_vs_sex_ratio.png
1.View 2.Top/Bottom 3.Gender Gap 4.Regions 5.Search 6.Filter 7.Correlation 8.Charts 0.Exit
Enter choice: 0
Thank you for exploring open data!
- Start
- Save open data as CSV and read with read_csv()
- Add Gap and Rank columns
- Display menu and read choice
- Valid option? → No: 'Invalid choice'
- Run analysis / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | View | 15 states | PASS |
| 2 | Top 5 | Kerala first | PASS |
| 3 | Bottom 5 | Bihar last | PASS |
| 4 | Gender gap | Largest gap state shown | PASS |
| 5 | Region summary | Averages by region | PASS |
| 6 | Search 'kerala' | Kerala row | PASS |
| 7 | Filter SexRatio > 950 | Matching states | PASS |
| 8 | Correlation | Value between -1 and 1 | PASS |
| 9 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
raw,census. - 8 functions are defined (lines 25โ79) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
view() | 25โ26 | View | main program (menu) |
top_bottom() | 29โ31 | Top bottom | main program (menu) |
gap() | 34โ37 | Gap | main program (menu) |
region() | 40โ43 | Region | main program (menu) |
search() | 46โ49 | Search | main program (menu) |
above() | 52โ57 | Above | main program (menu) |
correlation() | 60โ63 | Correlation | main program (menu) |
charts() | 66โ79 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: Dataset loaded: 15 states x 9 columns (+2 more lines)
- You type 1 at Enter choice:runs:
view()shows: State Region Population Literacy Male Female SexRatio Gap Rank (+16 more lines) - You type 2 at Enter choice:runs:
top_bottom()shows: TOP 5 LITERATE STATES (+14 more lines) - You type 3 at Enter choice:runs:
gap()shows: State Male Female Gap (+17 more lines) - You type 4 at Enter choice:runs:
region()shows: States Avg_Literacy Avg_SexRatio Population (+7 more lines) - You type 5 at Enter choice:runs:
search() - You type kerala at State name:shows: State Kerala (+9 more lines)
- You type 6 at Enter choice:runs:
above() - You type SexRatio at Column (Literacy/Female/SexRatio/Population):
- You type 950 at Value:shows: State SexRatio (+10 more lines)
- You type 7 at Enter choice:runs:
correlation()shows: Literacy Female SexRatio Population (+6 more lines) - You type 8 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Thank you for exploring open data!
โค Inside each function - line by line
view() - lines 25โ26
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Student Database + SQL Analytics Combo
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
student | MySQL table | roll PK, name, section, maths, science, english |
df | DataFrame | Data fetched from MySQL |
q() | function | Runs a query and returns a DataFrame |
cur | cursor | Executes SQL |
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)
12 records inserted with executemany()
============================================================
STUDENT DATABASE + SQL ANALYTICS
============================================================
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 1
roll name section maths science english total
1 Aarav A 88 92 79 259
2 Bhavya A 76 81 85 242
3 Chirag B 54 61 70 185
4 Diya B 95 89 91 275
5 Eshan C 45 52 60 157
6 Farah C 82 78 88 248
7 Gaurav A 67 73 64 204
8 Hina B 90 94 86 270
9 Ira C 38 44 55 137
10 Jatin A 79 70 68 217
11 Kavya B 85 91 95 271
12 Laksh C 60 58 72 190
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 2
Roll: 13
Name: Tanvi Rao
Section: B
Maths: 91
Science: 87
English: 93
Inserted Tanvi Rao
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 3
Roll: 5
Subject: maths
New marks: 72
1 row(s) updated
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 4
Roll to delete: 99
0 row(s) deleted
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 5
Section-wise average (SQL GROUP BY):
section students avg_maths avg_sci avg_eng
A 4 77.50 79.00 74.00
B 5 83.00 84.40 87.00
C 4 63.00 58.00 68.75
Sections with maths average > 70 (HAVING):
section avg_maths
A 77.5000
B 83.0000
Students scoring 85+ in any subject:
name maths science english
Aarav 88 92 79
Bhavya 76 81 85
Diya 95 89 91
Farah 82 78 88
Hina 90 94 86
Kavya 85 91 95
Tanvi Rao 91 87 93
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 6
maths science english
count 13.00 13.00 13.00
mean 75.15 74.62 77.38
std 16.64 16.57 13.36
min 38.00 44.00 55.00
25% 67.00 61.00 68.00
50% 79.00 78.00 79.00
75% 88.00 89.00 88.00
max 95.00 94.00 95.00
Section-wise mean (Pandas groupby):
maths science english percent
section
A 77.5 79.0 74.00 76.82
B 83.0 84.4 87.00 84.80
C 63.0 58.0 68.75 63.25
Grade count:
grade
D 1
C 0
B 5
A 4
A+ 3
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 7
name section total
Diya B 275
Kavya B 271
Tanvi Rao B 271
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 8
Charts saved: section_avg_sql.png, subject_box.png, grade_count.png
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 1
roll name section maths science english total
1 Aarav A 88 92 79 259
2 Bhavya A 76 81 85 242
3 Chirag B 54 61 70 185
4 Diya B 95 89 91 275
5 Eshan C 72 52 60 184
6 Farah C 82 78 88 248
7 Gaurav A 67 73 64 204
8 Hina B 90 94 86 270
9 Ira C 38 44 55 137
10 Jatin A 79 70 68 217
11 Kavya B 85 91 95 271
12 Laksh C 60 58 72 190
13 Tanvi Rao B 91 87 93 271
1.View 2.Add 3.Update 4.Delete 5.SQL Reports 6.Pandas Analysis 7.Toppers 8.Charts 0.Exit
Enter choice: 0
Connection closed.
- Start
- Connect to MySQL, create table, executemany()
- Display menu and read choice
- DML option (2/3/4)? → No: run SELECT and build DataFrame
- execute() + commit()
- Analyse DataFrame / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | View | 12 rows in DataFrame | PASS |
| 2 | Add roll 13 | Row inserted | PASS |
| 3 | Update maths roll 5 | 1 row changed | PASS |
| 4 | Delete roll 99 | 0 rows | PASS |
| 5 | SQL reports | Section averages | PASS |
| 6 | Pandas analysis | Same averages as SQL | PASS |
| 7 | Top performers | 3 students | PASS |
| 8 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,mysql.connector- connecting Python with MySQL are loaded. - Global variables / constants are created:
conn,cur,SUBJ. - 9 functions are defined (lines 27โ96) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
q(sql, params) | 27โ30 | Runs a SELECT and returns a DataFrame. | view(), sql_reports(), pandas_analysis(), toppers() |
view() | 33โ36 | View | main program (menu) |
add() | 39โ44 | Add | main program (menu) |
update() | 47โ52 | Update | main program (menu) |
delete() | 55โ58 | Delete | main program (menu) |
sql_reports() | 61โ69 | Sql reports | main program (menu) |
pandas_analysis() | 72โ80 | Pandas analysis | main program (menu) |
toppers() | 83โ85 | Toppers | main program (menu) |
charts() | 88โ96 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Inventory / Stock Price Tracker
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
๐ฏ Objectives
- Handle missing and wrong data with fillna() and apply()
- Select rows using nlargest()
- Draw a line chart with markers
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
inv | DataFrame | Item, Category, Opening, Purchase, Sold, Price, Reorder |
prices | DataFrame | Date-indexed daily prices of 3 items |
Closing | column | Opening + Purchase - Sold |
Value | column | Closing x Price |
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.")
============================================================
INVENTORY & PRICE TRACKER
============================================================
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 1
Raw data:
Item Category Opening Purchase Sold Price Reorder
0 Notebook Paper 120.0 100.0 150 45.0 50
1 Gel Pen Writing 200.0 -10.0 160 10.0 60
2 Pencil Box Writing 40.0 20.0 45 120.0 15
3 Geometry Box Maths 25.0 10.0 28 150.0 10
4 Calculator Maths 10.0 5.0 9 950.0 5
5 Drawing File Paper 60.0 NaN 35 60.0 20
6 Eraser Writing NaN 50.0 30 5.0 20
7 Marker Writing 80.0 40.0 70 NaN 30
8 Stapler Office 15.0 10.0 6 180.0 5
9 Glue Stick Office 50.0 30.0 72 25.0 20
Missing values per column:
Item 0
Category 0
Opening 1
Purchase 1
Sold 0
Price 1
Reorder 0
Closing 0
Value 1
Status 0
After cleaning - missing: 0 | negative purchase fixed: 1
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 2
Item Opening Purchase Sold Closing Price Value Status
Notebook 120.0 100.0 150 70 45.0 3150.0 OK
Gel Pen 200.0 10.0 160 50 10.0 500.0 REORDER
Pencil Box 40.0 20.0 45 15 120.0 1800.0 OK
Geometry Box 25.0 10.0 28 7 150.0 1050.0 REORDER
Calculator 10.0 5.0 9 6 950.0 5700.0 OK
Drawing File 60.0 0.0 35 25 60.0 1500.0 OK
Eraser 0.0 50.0 30 20 5.0 100.0 OK
Marker 80.0 40.0 70 50 60.0 3000.0 OK
Stapler 15.0 10.0 6 19 180.0 3420.0 OK
Glue Stick 50.0 30.0 72 8 25.0 200.0 REORDER
Total stock value: Rs. 20,420
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 3
Item Closing Reorder Order_Qty
Gel Pen 50 60 70
Geometry Box 7 10 13
Glue Stick 8 20 32
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 4
Item name: Gel Pen
IN or OUT: IN
Quantity: 50
Gel Pen: closing stock now 100 (OK)
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 4
Item name: Notebook
IN or OUT: OUT
Quantity: 500
Insufficient stock! Available: 70
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 4
Item name: Notebook
IN or OUT: OUT
Quantity: 20
Notebook: closing stock now 50 (OK)
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 3
Item Closing Reorder Order_Qty
Geometry Box 7 10 13
Glue Stick 8 20 32
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 5
Calculator Geometry Box Stapler
2026-07-01 961 146 183
2026-07-02 980 142 187
2026-07-03 956 138 182
2026-07-04 975 135 180
2026-07-05 975 139 181
2026-07-06 978 136 180
2026-07-07 987 137 181
2026-07-08 977 139 183
2026-07-09 1005 137 184
2026-07-10 982 135 178
2026-07-11 972 134 183
2026-07-12 968 132 183
2026-07-13 974 136 187
2026-07-14 971 133 184
2026-07-15 953 137 182
5-day rolling average (last 3 days):
Calculator Geometry Box Stapler
2026-07-13 980.2 134.8 183.0
2026-07-14 973.4 134.0 183.0
2026-07-15 967.6 134.4 183.8
% change over 15 days:
Calculator -0.83
Geometry Box -6.16
Stapler -0.55
Max single-day rise: {'Calculator': 2.87, 'Geometry Box': 3.03, 'Stapler': 2.81}
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 6
Items Closing Value
Category
Maths 2 13 6750.0
Office 2 27 3620.0
Paper 2 75 3750.0
Writing 4 185 5900.0
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 7
Charts saved: stock_trend.png, stock_value.png, reorder.png
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 8
inventory_clean.csv saved with 10 columns
1.Clean 2.Report 3.Reorder 4.Stock IN/OUT 5.Price Tracker 6.Category 7.Charts 8.Save 0.Exit
Enter choice: 0
Goodbye!
- Start
- Create DataFrame with NaN / negative values
- Clean data
- Display menu and read choice
- Choice is Stock IN/OUT? → No: run report
- Read item, type and quantity
- OUT quantity <= closing? → No: 'Insufficient stock'
- Update and recalculate
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Cleaning | NaN count becomes 0 | PASS |
| 2 | Negative purchase -10 | Converted to 10 | PASS |
| 3 | Inventory report | Closing and value | PASS |
| 4 | Reorder list | Items below level | PASS |
| 5 | Stock IN 50 Pen | Closing increases | PASS |
| 6 | Stock OUT more than stock | Refused | PASS |
| 7 | Price tracker | Rolling mean shown | PASS |
| 8 | Category summary | Totals | PASS |
| 9 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,numpy- fast arrays and maths are loaded. - Global variables / constants are created:
inv,raw. - 9 functions are defined (lines 20โ98) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
clean() | 20โ27 | Clean | main program (menu) |
recalc() | 30โ33 | Recalc | clean(), stock_entry(), main program |
report() | 36โ38 | Report | main program (menu) |
reorder() | 41โ44 | Reorder | main program (menu) |
stock_entry() | 47โ61 | Stock entry | main program (menu) |
tracker() | 71โ76 | Tracker | main program (menu) |
category() | 79โ80 | Category | main program (menu) |
charts() | 83โ93 | Charts | main program (menu) |
save() | 96โ98 | Save | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
recalc()shows: INVENTORY & PRICE TRACKER (+1 more lines) - You type 1 at Enter choice:runs:
clean()โrecalc()shows: Raw data: (+24 more lines) - You type 2 at Enter choice:runs:
report()shows: Item Opening Purchase Sold Closing Price Value Status (+12 more lines) - You type 3 at Enter choice:runs:
reorder()shows: Item Closing Reorder Order_Qty (+4 more lines) - You type 4 at Enter choice:runs:
stock_entry() - You type Gel Pen at Item name:
- You type IN at IN or OUT:
- You type 50 at Quantity:runs:
recalc()shows: Gel Pen: closing stock now 100 (OK) (+1 more lines) - You type 4 at Enter choice:runs:
stock_entry() - You type Notebook at Item name:
- You type OUT at IN or OUT:
- You type 500 at Quantity:shows: Insufficient stock! Available: 70 (+1 more lines)
- You type 4 at Enter choice:runs:
stock_entry() - You type Notebook at Item name:
- You type OUT at IN or OUT:
- You type 20 at Quantity:runs:
recalc()shows: Notebook: closing stock now 50 (OK) (+1 more lines) - You type 3 at Enter choice:runs:
reorder()shows: Item Closing Reorder Order_Qty (+3 more lines) - You type 5 at Enter choice:runs:
tracker()shows: Calculator Geometry Box Stapler (+26 more lines) - You type 6 at Enter choice:runs:
category()shows: Items Closing Value (+6 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 8 at Enter choice:runs:
save()shows: inventory_clean.csv saved with 10 columns (+1 more lines) - You type 0 at Enter choice:shows: Goodbye!
โค Inside each function - line by line
clean() - lines 20โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Weather Data Analysis (Delhi)
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
๐ฏ Objectives
- Use describe(), idxmax() and idxmin()
- Filter rows with boolean conditions
- Create line and bar charts with labels
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
w | DataFrame | Date index; MaxT, MinT, Humidity, Rain_mm |
Range | column | MaxT - MinT |
Type | column | Weather type from rules |
weekly | DataFrame | Weekly mean / sum |
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"))()
============================================================
WEATHER DATA ANALYSIS - DELHI
============================================================
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 1
MaxT MinT Humidity Rain_mm Range Type
Date
2026-07-01 39.1 30.5 83 10.5 8.6 Rainy
2026-07-02 41.0 33.6 83 19.3 7.4 Rainy
2026-07-03 40.6 34.1 74 0.0 6.5 Hot
2026-07-04 37.6 30.3 76 0.0 7.3 Humid
2026-07-05 37.7 30.1 83 31.5 7.6 Rainy
2026-07-06 37.2 27.5 65 0.0 9.7 Pleasant
2026-07-07 38.7 32.2 94 34.9 6.5 Rainy
2026-07-08 37.5 31.2 66 0.0 6.3 Pleasant
2026-07-09 38.6 30.4 83 21.1 8.2 Rainy
2026-07-10 34.2 24.3 69 6.1 9.9 Pleasant
2026-07-11 39.5 29.9 68 4.6 9.6 Hot
2026-07-12 36.6 27.8 83 35.8 8.8 Rainy
2026-07-13 37.7 31.4 62 0.0 6.3 Pleasant
2026-07-14 36.2 27.0 59 0.0 9.2 Pleasant
2026-07-15 35.6 26.9 64 0.0 8.7 Pleasant
2026-07-16 36.7 30.1 68 9.3 6.6 Pleasant
2026-07-17 37.1 29.2 98 41.9 7.9 Rainy
2026-07-18 35.3 29.1 74 7.9 6.2 Pleasant
2026-07-19 35.2 26.0 65 0.0 9.2 Pleasant
2026-07-20 36.3 27.4 65 0.0 8.9 Pleasant
2026-07-21 33.6 24.4 64 0.0 9.2 Pleasant
2026-07-22 32.4 23.4 70 12.6 9.0 Rainy
2026-07-23 35.2 28.1 70 10.0 7.1 Rainy
2026-07-24 33.3 24.1 60 0.0 9.2 Pleasant
2026-07-25 31.1 24.1 65 0.0 7.0 Pleasant
2026-07-26 32.7 26.1 98 55.2 6.6 Rainy
2026-07-27 33.1 25.5 75 10.3 7.6 Rainy
2026-07-28 31.7 23.7 84 36.2 8.0 Rainy
2026-07-29 31.0 23.9 74 7.3 7.1 Pleasant
2026-07-30 33.3 24.9 77 23.0 8.4 Rainy
2026-07-31 34.4 26.0 59 0.0 8.4 Pleasant
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 2
MaxT MinT Humidity Rain_mm Range
count 31.00 31.00 31.00 31.00 31.00
mean 35.81 27.85 73.48 12.18 7.97
std 2.73 3.07 10.91 15.37 1.15
min 31.00 23.40 59.00 0.00 6.20
25% 33.45 25.20 65.00 0.00 7.05
50% 36.20 27.50 70.00 7.30 8.00
75% 37.65 30.20 83.00 20.20 8.95
max 41.00 34.10 98.00 55.20 9.90
Total rainfall: 377.5 mm on 18 days
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 3
Hottest day : 2026-07-02 - 41.0 C
Coolest night: 2026-07-22 - 23.4 C
Wettest day : 2026-07-26 - 55.2 mm
Most humid : 2026-07-17 - 98 %
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 4
MaxT MinT Humidity Rain_mm
Date
Week ending 05-Jul 39.2 31.7 79.8 61.3
Week ending 12-Jul 37.5 29.0 75.4 102.5
Week ending 19-Jul 36.3 28.5 70.0 59.1
Week ending 26-Jul 33.5 25.4 70.3 77.8
Week ending 02-Aug 32.7 24.8 73.8 76.8
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 5
Filter hot / rain: hot
MaxT Humidity Rain_mm Type
Date
2026-07-01 39.1 83 10.5 Rainy
2026-07-02 41.0 83 19.3 Rainy
2026-07-03 40.6 74 0.0 Hot
2026-07-07 38.7 94 34.9 Rainy
2026-07-09 38.6 83 21.1 Rainy
2026-07-11 39.5 68 4.6 Hot
6 days found
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 5
Filter hot / rain: rain
MaxT Humidity Rain_mm Type
Date
2026-07-01 39.1 83 10.5 Rainy
2026-07-02 41.0 83 19.3 Rainy
2026-07-05 37.7 83 31.5 Rainy
2026-07-07 38.7 94 34.9 Rainy
2026-07-09 38.6 83 21.1 Rainy
2026-07-10 34.2 69 6.1 Pleasant
2026-07-11 39.5 68 4.6 Hot
2026-07-12 36.6 83 35.8 Rainy
2026-07-16 36.7 68 9.3 Pleasant
2026-07-17 37.1 98 41.9 Rainy
2026-07-18 35.3 74 7.9 Pleasant
2026-07-22 32.4 70 12.6 Rainy
2026-07-23 35.2 70 10.0 Rainy
2026-07-26 32.7 98 55.2 Rainy
2026-07-27 33.1 75 10.3 Rainy
2026-07-28 31.7 84 36.2 Rainy
2026-07-29 31.0 74 7.3 Pleasant
2026-07-30 33.3 77 23.0 Rainy
18 days found
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 6
Date (yyyy-mm-dd): 2026-07-15
MaxT 35.6
MinT 26.9
Humidity 64
Rain_mm 0.0
Range 8.7
Type Pleasant
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 6
Date (yyyy-mm-dd): 2026-08-01
No data for 2026-08-01
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 7
Type
Pleasant 15
Rainy 13
Hot 2
Humid 1
Average max temp by type:
Type
Hot 40.0
Humid 37.6
Pleasant 35.0
Rainy 35.9
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 8
Charts saved: temperature.png, rainfall.png, humidity_scatter.png, weather_types.png
1.Data 2.Stats 3.Extremes 4.Weekly 5.Filter 6.Search 7.Day Types 8.Charts 0.Exit
Enter choice: 0
Stay safe in the weather!
- Start
- Create date-indexed DataFrame
- Add Range and Type columns
- Display menu and read choice
- Valid option? → No: 'Invalid choice'
- Analyse / filter / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Show data | 31 rows | PASS |
| 2 | Statistics | Mean max temp shown | PASS |
| 3 | Extremes | Dates of max / min | PASS |
| 4 | Weekly | 5 weeks | PASS |
| 5 | Filter hot (>=38) | Hot days listed | PASS |
| 6 | Search 2026-07-15 | That day's weather | PASS |
| 7 | Search 2026-08-01 | 'No data' | PASS |
| 8 | Day types | Counts of each type | PASS |
| 9 | Charts | 4 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,numpy- fast arrays and maths are loaded. - Global variables / constants are created:
rng,dates,maxt,rain,w. - 9 functions are defined (lines 20โ88) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
kind(r) | 20โ27 | Kind | main program (menu) |
show() | 33โ34 | Show | main program (menu) |
stats() | 37โ39 | Stats | main program (menu) |
extremes() | 42โ46 | Extremes | main program (menu) |
weekly() | 49โ52 | Weekly | main program (menu) |
filt() | 55โ59 | Filt | main program (menu) |
search() | 62โ67 | Search | main program (menu) |
types() | 70โ72 | Types | main program (menu) |
charts() | 75โ88 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
kind()ร31shows: WEATHER DATA ANALYSIS - DELHI (+1 more lines) - You type 1 at Enter choice:runs:
show()shows: MaxT MinT Humidity Rain_mm Range Type (+33 more lines) - You type 2 at Enter choice:runs:
stats()shows: MaxT MinT Humidity Rain_mm Range (+10 more lines) - You type 3 at Enter choice:runs:
extremes()shows: Hottest day : 2026-07-02 - 41.0 C (+4 more lines) - You type 4 at Enter choice:runs:
weekly()shows: MaxT MinT Humidity Rain_mm (+7 more lines) - You type 5 at Enter choice:runs:
filt() - You type hot at Filter hot / rain:shows: MaxT Humidity Rain_mm Type (+9 more lines)
- You type 5 at Enter choice:runs:
filt() - You type rain at Filter hot / rain:shows: MaxT Humidity Rain_mm Type (+21 more lines)
- You type 6 at Enter choice:runs:
search() - You type 2026-07-15 at Date (yyyy-mm-dd):shows: MaxT 35.6 (+6 more lines)
- You type 6 at Enter choice:runs:
search() - You type 2026-08-01 at Date (yyyy-mm-dd):shows: No data for 2026-08-01 (+1 more lines)
- You type 7 at Enter choice:runs:
types()shows: Type (+11 more lines) - You type 8 at Enter choice:runs:
charts()shows: [chart is drawn] (+5 more lines) - You type 0 at Enter choice:shows: Stay safe in the weather!
โค Inside each function - line by line
kind() - lines 20โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Retail Sales Analysis (CSV)
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
๐ฏ Objectives
- Import and export CSV files
- Add calculated columns and use groupby() with sort_values()
- Visualise trends and shares with charts
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
sales | DataFrame | OrderID, Date, Region, Category, Product, Qty, Price, Salesperson |
Revenue / Net | column | Qty x Price and after discount |
sales.csv | CSV file | Raw transactions |
sales_summary.csv | CSV file | Exported category summary |
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.")
============================================================
RETAIL SALES ANALYSIS (Jan - Jun 2026)
============================================================
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 1
Shape: (120, 12)
OrderID Date Region Category Product Qty Price Salesperson Revenue Discount Net Month
1001 2026-04-29 South Electronics Smart Watch 4 3499 Ehsaan 13996 0.0 13996.0 04-Apr
1002 2026-02-06 North Electronics Smart Watch 4 3499 Ehsaan 13996 0.0 13996.0 02-Feb
1003 2026-05-10 West Grocery Tea 500g 4 245 Asha 980 0.0 980.0 05-May
1004 2026-04-01 South Stationery Pen Set 2 150 Ehsaan 300 0.0 300.0 04-Apr
1005 2026-03-14 West Stationery Pen Set 4 150 Chetan 600 0.0 600.0 03-Mar
1006 2026-01-17 East Clothing Kurta 7 899 Asha 6293 0.0 6293.0 01-Jan
1007 2026-02-20 East Stationery School Bag 2 899 Deepa 1798 0.0 1798.0 02-Feb
1008 2026-01-13 West Grocery Mustard Oil 1L 4 189 Ehsaan 756 0.0 756.0 01-Jan
Data types:
OrderID int64
Date datetime64[ns]
Region object
Category object
Product object
Qty int64
Price int64
Salesperson object
Revenue int64
Discount float64
Net float64
Month object
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 2
Orders Units Revenue Avg_Order Share_%
Category
Electronics 26 115 845113.0 32504.0 72.0
Clothing 28 129 220171.0 7863.0 19.0
Stationery 37 122 60303.0 1630.0 5.0
Grocery 29 123 41127.0 1418.0 4.0
Total net revenue: Rs. 1,166,714
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 3
Month 01-Jan 02-Feb 03-Mar 04-Apr 05-May 06-Jun Total
Region
West 130109.0 24003.0 110811.0 26488.0 96487.0 16186.0 404084.0
North 34415.0 32590.0 3876.0 159818.0 11540.0 38140.0 280379.0
South 2370.0 139807.0 35042.0 31088.0 41000.0 22963.0 272270.0
East 34236.0 92992.0 20648.0 37511.0 22673.0 1920.0 209980.0
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 4
Revenue Growth_%
Month
01-Jan 201130.0 -
02-Feb 289392.0 43.9
03-Mar 170377.0 -41.1
04-Apr 254905.0 49.6
05-May 171700.0 -32.6
06-Jun 79209.0 -53.9
Best month: 02-Feb | Weakest: 06-Jun
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 5
Category Product
Electronics Smartphone 639960.0
Smart Watch 141185.0
Clothing Jacket 122451.0
Jeans 64457.0
Electronics Earbuds 63968.0
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 6
Orders Revenue Rank
Salesperson
Asha 27 398106.0 1
Deepa 25 335035.0 2
Chetan 30 213978.0 3
Ehsaan 20 143672.0 4
Bharat 18 75923.0 5
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 7
Region: North
Minimum net revenue: 20000
OrderID Date Product Qty Net
1043 2026-04-30 Smartphone 5 75995.25
1059 2026-04-07 Smartphone 3 45597.15
2 orders | total Rs. 121592
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 8
Charts saved: monthly_revenue.png, category_share.png, region_month.png, top_products.png
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 9
Category,Qty,Revenue,Discount,Net
Clothing,129,220171,0.0,220171.0
Electronics,115,879385,34272.35,845112.65
Grocery,123,41127,0.0,41127.0
Stationery,122,60303,0.0,60303.0
1.Preview 2.Category 3.Pivot 4.Growth 5.Top Products 6.Ranking 7.Filter 8.Charts 9.Export 0.Exit
Enter choice: 0
Report complete.
- Start
- Generate data, save sales.csv, read it back
- Add calculated columns
- Display menu and read choice
- Valid option? → No: 'Invalid choice'
- Run groupby / pivot / filter / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Preview | 120 rows x 12 columns | PASS |
| 2 | Category summary | Revenue per category | PASS |
| 3 | Pivot | 4 regions x 6 months | PASS |
| 4 | Growth | % change per month | PASS |
| 5 | Top products | 5 rows | PASS |
| 6 | Ranking | Rank 1 salesperson | PASS |
| 7 | Filter North, 20000 | Matching rows | PASS |
| 8 | Charts | 4 PNG files | PASS |
| 9 | Export | CSV saved | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,numpy- fast arrays and maths are loaded. - Global variables / constants are created:
rng,PRODUCTS,rows,sales. - 9 functions are defined (lines 30โ90) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
preview() | 30โ33 | Preview | main program (menu) |
category() | 36โ40 | Category | main program (menu) |
pivot() | 43โ46 | Pivot | main program (menu) |
growth() | 49โ53 | Growth | main program (menu) |
top_products() | 56โ58 | Top products | main program (menu) |
ranking() | 61โ64 | Ranking | main program (menu) |
filt() | 67โ72 | Filt | main program (menu) |
charts() | 75โ85 | Charts | main program (menu) |
export() | 88โ90 | Export | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: RETAIL SALES ANALYSIS (Jan - Jun 2026) (+1 more lines)
- You type 1 at Enter choice:runs:
preview()shows: Shape: (120, 12) (+23 more lines) - You type 2 at Enter choice:runs:
category()shows: Orders Units Revenue Avg_Order Share_% (+7 more lines) - 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) - You type 4 at Enter choice:runs:
growth()shows: Revenue Growth_% (+9 more lines) - You type 5 at Enter choice:runs:
top_products()shows: Category Product (+6 more lines) - You type 6 at Enter choice:runs:
ranking()shows: Orders Revenue Rank (+7 more lines) - You type 7 at Enter choice:runs:
filt() - You type North at Region:
- You type 20000 at Minimum net revenue:shows: OrderID Date Product Qty Net (+4 more lines)
- You type 8 at Enter choice:runs:
charts()shows: [chart is drawn] (+5 more lines) - You type 9 at Enter choice:runs:
export()shows: Category,Qty,Revenue,Discount,Net (+5 more lines) - You type 0 at Enter choice:shows: Report complete.
โค Inside each function - line by line
preview() - lines 30โ33
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Employee Payroll Analytics (MySQL + Pandas)
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
๐ฏ Objectives
- Combine MySQL storage with Pandas analysis
- Create calculated columns in a DataFrame
- Summarise with groupby() and agg()
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
emp | MySQL table | eid PK, name, dept, desig, basic, doj DATE, city |
df | DataFrame | From fetchall() + cursor.description |
DA / HRA / PF | float | 0.46 / 0.24 / 0.12 of basic |
Exp_Yrs | column | Years since joining |
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)
============================================================
EMPLOYEE PAYROLL ANALYTICS (MySQL + Pandas)
============================================================
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 1
eid name dept desig basic doj city
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
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 2
dept staff total_basic avg_basic max_basic
IT 4 258000 64500 92000
Sales 4 202000 50500 81000
Finance 2 118000 59000 63000
HR 2 112000 56000 74000
Departments with more than 2 employees (HAVING):
dept staff
IT 4
Sales 4
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 3
eid name dept basic DA HRA PF Gross Net
E101 Arvind Rao IT 92000 42320.0 22080.0 11040.0 156400.0 145360.0
E102 Bina Shah IT 61000 28060.0 14640.0 7320.0 103700.0 96380.0
E103 Chandan Roy IT 58000 26680.0 13920.0 6960.0 98600.0 91640.0
E104 Dolly Paul HR 74000 34040.0 17760.0 8880.0 125800.0 116920.0
E105 Ekta Jain HR 38000 17480.0 9120.0 4560.0 64600.0 60040.0
E106 Faisal Khan Sales 81000 37260.0 19440.0 9720.0 137700.0 127980.0
E107 Geeta Nair Sales 42000 19320.0 10080.0 5040.0 71400.0 66360.0
E108 Harsh Vora Sales 40000 18400.0 9600.0 4800.0 68000.0 63200.0
E109 Indu Bala Finance 55000 25300.0 13200.0 6600.0 93500.0 86900.0
E110 Jai Thakur Finance 63000 28980.0 15120.0 7560.0 107100.0 99540.0
E111 Kriti Das IT 47000 21620.0 11280.0 5640.0 79900.0 74260.0
E112 Lalit Mohan Sales 39000 17940.0 9360.0 4680.0 66300.0 61620.0
Monthly payroll (Net): Rs. 1,090,200 | Annual: Rs. 13,082,400
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 4
eid name dept doj basic Exp_Yrs Band
E101 Arvind Rao IT 2012-06-11 92000 14.1 7+ yrs
E106 Faisal Khan Sales 2013-11-30 81000 12.7 7+ yrs
E104 Dolly Paul HR 2014-03-20 74000 12.4 7+ yrs
E109 Indu Bala Finance 2016-09-12 55000 9.9 7+ yrs
E102 Bina Shah IT 2018-08-01 61000 8.0 7+ yrs
E110 Jai Thakur Finance 2019-10-21 63000 6.8 3-7 yrs
E103 Chandan Roy IT 2020-01-15 58000 6.5 3-7 yrs
E107 Geeta Nair Sales 2021-05-17 42000 5.2 3-7 yrs
E111 Kriti Das IT 2021-12-06 47000 4.6 3-7 yrs
E105 Ekta Jain HR 2022-07-04 38000 4.1 3-7 yrs
E108 Harsh Vora Sales 2023-02-01 40000 3.5 3-7 yrs
E112 Lalit Mohan Sales 2024-06-10 39000 2.1 0-3 yrs
Employees per band:
Band
0-3 yrs 1
3-7 yrs 6
7+ yrs 5
Average basic per band:
Band
0-3 yrs 39000.0
3-7 yrs 48000.0
7+ yrs 72600.0
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 5
Emp ID: E113
Name: Ritika Sen
Dept: IT
Designation: Analyst
Basic: 48000
Date of joining (yyyy-mm-dd): 2026-04-01
City: Pune
Hired Ritika Sen - 1 row inserted
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 6
Emp ID: E105
Raise %: 10
1 row(s) updated
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 6
Emp ID: E999
Raise %: 5
0 row(s) updated
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 7
Current After_8% Extra
dept
Finance 186440.0 201355.0 14915.0
HR 182964.0 197601.0 14637.0
IT 483480.0 522158.0 38678.0
Sales 319160.0 344693.0 25533.0
Extra monthly cost of 8% raise: Rs. 93,764
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 8
Charts saved: dept_payroll.png, salary_hist.png, exp_vs_salary.png
1.List 2.Dept Summary 3.Payroll 4.Experience 5.Hire 6.Raise 7.What-if 8.Charts 0.Exit
Enter choice: 0
Connection closed.
- Start
- Connect, create table and insert 12 rows
- Display menu and read choice
- DML option? → No: SELECT into DataFrame
- execute + commit
- Calculate payroll columns / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Employee list | 12 rows | PASS |
| 2 | Dept summary | SQL GROUP BY result | PASS |
| 3 | Payroll sheet | Net pay column | PASS |
| 4 | Experience | Band counts | PASS |
| 5 | Hire E113 | Row inserted | PASS |
| 6 | Raise 10 % to E105 | 1 row updated | PASS |
| 7 | Raise to E999 | 0 rows | PASS |
| 8 | What-if | Extra monthly cost | PASS |
| 9 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,mysql.connector- connecting Python with MySQL are loaded. - Global variables / constants are created:
TODAY,conn,cur. - 10 functions are defined (lines 28โ106) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
frame(sql, p) | 28โ30 | Frame | payroll(), emp_list(), dept_summary(), experience() |
payroll() | 33โ40 | Payroll | sheet(), what_if(), charts() |
emp_list() | 43โ44 | Emp list | main program (menu) |
dept_summary() | 47โ51 | Dept summary | main program (menu) |
sheet() | 54โ57 | Sheet | main program (menu) |
experience() | 60โ67 | Experience | main program (menu) |
hire() | 70โ75 | Hire | main program (menu) |
raise_pay() | 78โ82 | Raise pay | main program (menu) |
what_if() | 85โ91 | What if | main program (menu) |
charts() | 94โ106 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Cricket Player Statistics Analyzer
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
๐ฏ Objectives
- Create calculated columns in a DataFrame
- Use nlargest(), filtering and corr()
- Plot bar and scatter charts with annotations
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
cr | DataFrame | Player, Role, M, Inn, NO, Runs, Balls, Fours, Sixes, Wkts |
Average | column | Runs / (Inn - NO) |
SR | column | Runs / Balls x 100 |
Boundary_% | column | (4s x 4 + 6s x 6) / Runs x 100 |
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.")
============================================================
CRICKET PLAYER STATISTICS ANALYZER
============================================================
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 1
Player Role M Runs Average SR Boundary_% Wkts
1 Virat Kohli Batter 125 4188 48.70 136.64 53.0 4
2 Rohit Sharma Batter 159 4231 31.81 142.31 65.3 1
3 Suryakumar Yadav Batter 83 2598 38.78 167.29 70.1 0
4 Shubman Gill Batter 35 1068 34.45 140.53 61.6 0
5 Yashasvi Jaiswal Batter 23 723 38.05 164.32 75.5 0
6 Rishabh Pant Batter 76 1209 22.81 127.53 58.9 0
7 KL Rahul Batter 72 2265 37.75 139.38 61.4 0
8 Hardik Pandya All-rounder 114 1803 27.32 139.98 59.2 94
9 Ravindra Jadeja All-rounder 74 515 17.76 125.92 47.4 54
10 Axar Patel All-rounder 70 535 17.83 140.79 51.6 71
11 Shivam Dube All-rounder 35 531 26.55 139.74 59.5 11
12 Tilak Varma Batter 25 749 41.61 150.40 66.0 2
13 Jasprit Bumrah Bowler 70 8 4.00 53.33 0.0 89
14 Kuldeep Yadav Bowler 40 35 7.00 92.11 40.0 69
15 Ishan Kishan Batter 32 796 26.53 124.37 70.4 0
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 2
Player Runs Average SR
Rohit Sharma 4231 31.81 142.31
Virat Kohli 4188 48.70 136.64
Suryakumar Yadav 2598 38.78 167.29
KL Rahul 2265 37.75 139.38
Hardik Pandya 1803 27.32 139.98
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 3
Player Balls Runs SR
Suryakumar Yadav 1553 2598 167.29
Rohit Sharma 2973 4231 142.31
Shubman Gill 760 1068 140.53
Hardik Pandya 1288 1803 139.98
KL Rahul 1625 2265 139.38
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 4
Players Runs Avg_SR Wkts
Role
All-rounder 4 3384 136.6 230
Batter 9 17827 143.6 7
Bowler 2 43 72.7 158
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 5
Player name contains: sharma
Player Role Runs Average SR Wkts
Rohit Sharma Batter 4231 31.81 142.31 1
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 6
First player : Virat Kohli
Second player: Shubman Gill
Player Virat Kohli Shubman Gill Better
M 125.00 35.00 Virat Kohli
Runs 4188.00 1068.00 Virat Kohli
Average 48.70 34.45 Virat Kohli
SR 136.64 140.53 Shubman Gill
Fours 369.00 115.00 Virat Kohli
Sixes 124.00 33.00 Virat Kohli
Boundary_% 53.00 61.60 Shubman Gill
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 7
Player Average SR
Virat Kohli 48.70 136.64
Suryakumar Yadav 38.78 167.29
Yashasvi Jaiswal 38.05 164.32
KL Rahul 37.75 139.38
Tilak Varma 41.61 150.40
5 impact batters (Average >= 35 and SR >= 135)
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 8
Runs Average SR Sixes Boundary_%
Runs 1.00 0.65 0.41 0.94 0.35
Average 0.65 1.00 0.79 0.59 0.72
SR 0.41 0.79 1.00 0.48 0.91
Sixes 0.94 0.59 0.48 1.00 0.42
Boundary_% 0.35 0.72 0.91 0.42 1.00
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 9
Charts saved: top5_runs.png, avg_vs_sr.png, role_runs.png, boundaries.png
1.Table 2.Top Runs 3.Best SR 4.Roles 5.Search 6.Compare 7.Impact 8.Correlation 9.Charts 0.Exit
Enter choice: 0
Well played!
- Start
- Create DataFrame and calculated columns
- Display menu and read choice
- Valid option? → No: 'Invalid choice'
- Sort / filter / group / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Player table | 15 rows with Average and SR | PASS |
| 2 | Top scorers | 5 rows | PASS |
| 3 | Best SR | Players with 500+ balls | PASS |
| 4 | Role analysis | 3 roles | PASS |
| 5 | Search 'sharma' | Matching players | PASS |
| 6 | Compare two | Side-by-side table | PASS |
| 7 | Impact players | Filtered rows | PASS |
| 8 | Correlation | Matrix | PASS |
| 9 | Charts | 4 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
cr. - 9 functions are defined (lines 29โ86) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
table() | 29โ30 | Table | main program (menu) |
top_runs() | 33โ34 | Top runs | main program (menu) |
best_sr() | 37โ38 | Best sr | main program (menu) |
roles() | 41โ43 | Roles | main program (menu) |
search() | 46โ49 | Search | main program (menu) |
compare() | 52โ56 | Compare | main program (menu) |
impact() | 59โ62 | Impact | main program (menu) |
correlation() | 65โ66 | Correlation | main program (menu) |
charts() | 69โ86 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CRICKET PLAYER STATISTICS ANALYZER (+1 more lines)
- You type 1 at Enter choice:runs:
table()shows: Player Role M Runs Average SR Boundary_% Wkts (+16 more lines) - You type 2 at Enter choice:runs:
top_runs()shows: Player Runs Average SR (+6 more lines) - You type 3 at Enter choice:runs:
best_sr()shows: Player Balls Runs SR (+6 more lines) - You type 4 at Enter choice:runs:
roles()shows: Players Runs Avg_SR Wkts (+5 more lines) - You type 5 at Enter choice:runs:
search() - You type sharma at Player name contains:shows: Player Role Runs Average SR Wkts (+2 more lines)
- You type 6 at Enter choice:runs:
compare() - You type Virat Kohli at First player :
- You type Shubman Gill at Second player:shows: Player Virat Kohli Shubman Gill Better (+8 more lines)
- You type 7 at Enter choice:runs:
impact()shows: Player Average SR (+7 more lines) - You type 8 at Enter choice:runs:
correlation()shows: Runs Average SR Sixes Boundary_% (+6 more lines) - You type 9 at Enter choice:runs:
charts()shows: [chart is drawn] (+5 more lines) - You type 0 at Enter choice:shows: Well played!
โค Inside each function - line by line
table() - lines 29โ30
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Air Quality Index (AQI) Analyzer
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
aqi | DataFrame | Date, City, PM25, PM10, AQI |
Category | column | pd.cut of AQI into CPCB bands |
BANDS / LABELS | lists | 0,50,100,200,300,400,500 and names |
ADVICE | dict | Category -> health message |
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"))()
============================================================
AIR QUALITY INDEX ANALYZER
============================================================
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 1
Date City PM25 PM10 AQI Category
2026-11-01 Delhi 226.0 384.0 411 Severe
2026-11-02 Delhi 137.0 233.0 249 Poor
2026-11-03 Delhi 212.0 360.0 386 Very Poor
2026-11-04 Delhi 200.0 340.0 364 Very Poor
2026-11-05 Delhi 210.0 357.0 381 Very Poor
2026-11-06 Delhi 220.0 374.0 400 Very Poor
2026-11-07 Delhi 183.0 311.0 332 Very Poor
2026-11-08 Delhi 221.0 376.0 402 Severe
2026-11-09 Delhi 204.0 347.0 371 Very Poor
2026-11-10 Delhi 289.0 491.0 500 Severe
... total rows: 120
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 2
mean min max std
City
Delhi 337.3 240 500 66.3
Kolkata 191.5 128 260 35.4
Mumbai 140.0 76 194 27.2
Bengaluru 87.0 49 118 16.3
Most polluted city: Delhi | Cleanest: Bengaluru
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 3
Category Good Satisfactory Moderate Poor Very Poor Severe
City
Bengaluru 1 22 7 0 0 0
Delhi 0 0 0 12 13 5
Kolkata 0 0 19 11 0 0
Mumbai 0 2 28 0 0 0
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 4
City: Delhi
AQI 7-day mean
Date
2026-11-07 332 360.4
2026-11-10 500 392.9
2026-11-13 331 381.7
2026-11-16 267 341.1
2026-11-19 287 281.9
2026-11-22 320 271.4
2026-11-25 300 280.0
2026-11-28 356 330.0
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 5
WORST 5 DAYS
Date City AQI Category
2026-11-10 Delhi 500 Severe
2026-11-30 Delhi 438 Severe
2026-11-27 Delhi 424 Severe
2026-11-01 Delhi 411 Severe
2026-11-08 Delhi 402 Severe
BEST 5 DAYS
Date City AQI Category
2026-11-23 Bengaluru 49 Good
2026-11-27 Bengaluru 66 Satisfactory
2026-11-19 Bengaluru 67 Satisfactory
2026-11-17 Bengaluru 68 Satisfactory
2026-11-15 Bengaluru 69 Satisfactory
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 6
City: Delhi
Date (yyyy-mm-dd): 2026-11-05
Delhi on 2026-11-05: AQI 381 (Very Poor) | PM2.5 210
Advice: Respiratory illness on long exposure. Stay indoors.
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 6
City: Chennai
Date (yyyy-mm-dd): 2026-11-05
No data for Chennai on 2026-11-05
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 7
Date City AQI
2026-11-01 Delhi 411
2026-11-08 Delhi 402
2026-11-10 Delhi 500
2026-11-27 Delhi 424
2026-11-30 Delhi 438
5 severe days in the month
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 8
Charts saved: aqi_trend.png, aqi_share.png, city_compare.png, pollutants.png
1.View 2.City Summary 3.Categories 4.Rolling 5.Worst/Best 6.Advisory 7.Severe 8.Charts 0.Exit
Enter choice: 0
Breathe safe!
- Start
- Create AQI data for 4 cities
- Add Category with pd.cut
- Display menu and read choice
- Valid option? → No: 'Invalid choice'
- Analyse / filter / plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | View data | 120 rows | PASS |
| 2 | City summary | Delhi highest mean | PASS |
| 3 | Category count | Table of bands | PASS |
| 4 | Rolling Delhi | 7-day mean | PASS |
| 5 | Worst days | Top 5 AQI | PASS |
| 6 | Advisory Delhi 2026-11-05 | Category + advice | PASS |
| 7 | Advisory with wrong city | 'No data' | PASS |
| 8 | Severe days | Rows with AQI > 400 | PASS |
| 9 | Charts | 4 PNG files | PASS |
โ 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
- Imports (line 1):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,numpy- fast arrays and maths are loaded. - Global variables / constants are created:
rng,days,BASE,frames,aqi,BANDS,LABELS,ADVICE. - 8 functions are defined (lines 27โ83) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
view() | 27โ29 | View | main program (menu) |
summary() | 32โ35 | Summary | main program (menu) |
categories() | 38โ39 | Categories | main program (menu) |
rolling() | 42โ46 | Rolling | main program (menu) |
worst_best() | 49โ52 | Worst best | main program (menu) |
advisory() | 55โ63 | Advisory | main program (menu) |
severe() | 66โ69 | Severe | main program (menu) |
charts() | 72โ83 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: AIR QUALITY INDEX ANALYZER (+1 more lines)
- You type 1 at Enter choice:runs:
view()shows: Date City PM25 PM10 AQI Category (+12 more lines) - You type 2 at Enter choice:runs:
summary()shows: mean min max std (+7 more lines) - You type 3 at Enter choice:runs:
categories()shows: Category Good Satisfactory Moderate Poor Very Poor Severe (+6 more lines) - You type 4 at Enter choice:runs:
rolling() - You type Delhi at City:shows: AQI 7-day mean (+10 more lines)
- You type 5 at Enter choice:runs:
worst_best()shows: WORST 5 DAYS (+14 more lines) - You type 6 at Enter choice:runs:
advisory() - You type Delhi at City:
- 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)
- You type 6 at Enter choice:runs:
advisory() - You type Chennai at City:
- You type 2026-11-05 at Date (yyyy-mm-dd):shows: No data for Chennai on 2026-11-05 (+1 more lines)
- You type 7 at Enter choice:runs:
severe()shows: Date City AQI (+7 more lines) - You type 8 at Enter choice:runs:
charts()shows: [chart is drawn] (+5 more lines) - You type 0 at Enter choice:shows: Breathe safe!
โค Inside each function - line by line
view() - lines 27โ29
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Smart Water Usage Tracker (SDG 6)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
days | list | 7 day names |
usage | list of float | Litres used each day |
members | int | Family size |
acts / share | lists | Activity names and % share |
NORM | int | 135 litres per person per day (urban norm) |
# =====================================================================
# 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")
==================================================
SMART WATER USAGE TRACKER (SDG 6)
==================================================
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 2
Please enter data first (option 1).
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 1
Number of family members: 4
Water used on Monday (litres): 560
Water used on Tuesday (litres): 610
Water used on Wednesday (litres): 585
Water used on Thursday (litres): -20
Invalid value! Please enter a positive number.
Water used on Thursday (litres): 540
Water used on Friday (litres): 620
Water used on Saturday (litres): 700
Water used on Sunday (litres): 565
Data saved for 7 days.
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 2
----- WEEKLY REPORT -----
Monday 560 L ###########
Tuesday 610 L ############
Wednesday 585 L ###########
Thursday 540 L ##########
Friday 620 L ############
Saturday 700 L ##############
Sunday 565 L ###########
Total water used : 4180.0 litres
Average per day : 597.14 litres
Highest usage day : Saturday ( 700.0 L )
Lowest usage day : Thursday ( 540.0 L )
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 3
Per person per day : 149.29 litres (norm = 135 L)
ABOVE NORM by 14.3 L/person/day
Extra water used this week: 400.0 litres
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 4
Activity Share Litres
Bathing 30% 1254 ***************
Toilet flush 22% 920 ***********
Washing clothes 18% 752 *********
Cooking & drinking 8% 334 ****
Utensils 12% 502 ******
Cleaning/garden 10% 418 *****
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 5
ALERT: Saturday used 700 L (average 597 L) - check for leaks / wastage
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 6
Target reduction (%): 15
Litres saved per week : 627.0
Litres saved per year : 32604
Money saved per year : Rs. 1630.2
That is enough drinking water for 29.8 people for a year!
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 7
Largest use: Bathing
Tips: 1) Use a bucket instead of a shower 2) Fix leaking taps (a drip wastes ~30 L/day)
3) Reuse RO waste water for mopping 4) Run washing machine on full load
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 9
Invalid choice
1.Enter Data 2.Report 3.Norm Check 4.Break-up 5.Spike Detector 6.Saving Planner 7.Tips 0.Exit
Enter choice: 0
Every drop counts. Goodbye!
- Start
- Show menu and read choice
- Choice is 1 (enter data)? → No: check data exists and run report
- Read members and 7 daily values
- Compute total, average, max, min
- Per person > 135 L? → No: 'Within limit'
- Show saving and tips
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Report before entering data | 'Enter data first' | PASS |
| 2 | Members 4, 7 values | Data stored | PASS |
| 3 | Weekly report | Total 4180 L, highest Saturday | PASS |
| 4 | Norm check | 149.3 L/person - above norm | PASS |
| 5 | Spike detector | Saturday (700 L) flagged | PASS |
| 6 | Saving 15 % | Litres and Rs. saved | PASS |
| 7 | Negative litres | 'Invalid value' re-asked | PASS |
| 8 | Choice 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
- Global variables / constants are created:
days,acts,share,usage,members. - 8 functions are defined (lines 13โ87) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
read_number(msg) | 13โ19 | Keeps asking until a non-negative number is typed. | enter_data() |
enter_data() | 22โ28 | Enter data | main program |
report() | 31โ40 | Report | main program |
norm_check() | 43โ51 | Norm check | main program |
breakup() | 54โ59 | Breakup | main program |
spikes() | 62โ70 | Spikes | main program |
planner() | 73โ80 | Planner | main program |
tips() | 83โ87 | Tips | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: SMART WATER USAGE TRACKER (SDG 6) (+1 more lines)
- You type 2 at Enter choice:shows: Please enter data first (option 1). (+1 more lines)
- You type 1 at Enter choice:runs:
enter_data() - You type 4 at Number of family members:runs:
read_number() - You type 560 at Water used on Monday (litres):runs:
read_number() - You type 610 at Water used on Tuesday (litres):runs:
read_number() - You type 585 at Water used on Wednesday (litres):runs:
read_number() - You type -20 at Water used on Thursday (litres):shows: Invalid value! Please enter a positive number.
- You type 540 at Water used on Thursday (litres):runs:
read_number() - You type 620 at Water used on Friday (litres):runs:
read_number() - You type 700 at Water used on Saturday (litres):runs:
read_number() - You type 565 at Water used on Sunday (litres):shows: Data saved for 7 days. (+1 more lines)
- You type 2 at Enter choice:runs:
report()shows: ----- WEEKLY REPORT ----- (+12 more lines) - You type 3 at Enter choice:runs:
norm_check()shows: Per person per day : 149.29 litres (norm = 135 L) (+3 more lines) - You type 4 at Enter choice:runs:
breakup()shows: Activity Share Litres (+7 more lines) - You type 5 at Enter choice:runs:
spikes()shows: ALERT: Saturday used 700 L (average 597 L) - check for leaks / wastage (+1 more lines) - You type 6 at Enter choice:runs:
planner() - You type 15 at Target reduction (%):shows: Litres saved per week : 627.0 (+4 more lines)
- You type 7 at Enter choice:runs:
tips()shows: Largest use: Bathing (+3 more lines) - You type 9 at Enter choice:shows: Invalid choice (+1 more lines)
- You type 0 at Enter choice:shows: Every drop counts. Goodbye!
โค Inside each function - line by line
read_number() - lines 13โ19
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Home Electricity Saver (SDG 7)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
names, watts_list, hours_list | lists | Appliance details |
units() | function | watts x hours x 30 / 1000 |
SLABS | list | Units limit and rate per slab |
CO2 | float | 0.82 kg CO2 per kWh |
# =====================================================================
# 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")
==================================================== HOME ELECTRICITY SAVER (SDG 7) ==================================================== 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : Fan Power (watts) : 75 Hours per day : 10 Fan added -> 22.5 units per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : LED Bulbs Power (watts) : 40 Hours per day : 6 LED Bulbs added -> 7.2 units per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : Refrigerator Power (watts) : 150 Hours per day : 24 Refrigerator added -> 108.0 units per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : AC Power (watts) : 1500 Hours per day : 6 AC added -> 270.0 units per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : TV Power (watts) : 100 Hours per day : 30 Hours must be 0-24 and watts positive. Not added. 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 1 Appliance name : TV Power (watts) : 100 Hours per day : 4 TV added -> 12.0 units per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 2 Appliance Watts Hrs Units/mo Cost(Rs.) Chart ------------------------------------------------------------ Fan 75 10.0 22.5 87.28 ## LED Bulbs 40 6.0 7.2 27.93 Refrigerator 150 24.0 108.0 418.94 ########## AC 1500 6.0 270.0 1047.35 ########################### TV 100 4.0 12.0 46.55 # ------------------------------------------------------------ TOTAL 419.7 1628.05 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 3 Total units: 419.7 Units 1 - 200.0 @ Rs. 3.0 = Rs. 600.00 Units 201 - 400.0 @ Rs. 4.5 = Rs. 900.00 Units 401 - 419.7 @ Rs. 6.5 = Rs. 128.05 Bill amount: Rs. 1628.05 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 4 Highest consumer: AC - 64.3 % of units 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 5 Appliance: AC Reduce by hours/day: 2 Units saved per month: 90.0 | Money saved: Rs. 444.40/month, Rs. 5332.80/year 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 6 Appliance: LED Bulbs New appliance uses what % less power? 30 LED Bulbs: 7.2 -> 5.0 units; saving Rs. 14.04 per month 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 7 Monthly CO2: 344.2 kg | Yearly: 4.13 tonnes Trees needed to absorb it: about 197 (a tree absorbs ~21 kg CO2/year) 1.Add 2.Bill Table 3.Slab Bill 4.Highest 5.Fewer Hours 6.Replace 7.Carbon 0.Exit Enter choice: 0 Save energy, save money!
- Start
- Show menu and read choice
- Choice is Add? → No: run selected report
- Read name, watts, hours
- Valid values? → No: show error
- Append to lists
- Show bill / saving
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Add Fan 75 W 10 h | 22.5 units/month | PASS |
| 2 | Hours 30 | 'Hours must be 0-24' | PASS |
| 3 | Bill table | Rows for 5 appliances | PASS |
| 4 | Slab bill | Slab-wise amounts | PASS |
| 5 | Highest consumer | AC | PASS |
| 6 | Reduce AC by 2 h | Units and Rs. saved | PASS |
| 7 | Replace 'LED Bulbs' with 30 % power | Saving shown | PASS |
| 8 | Carbon | kg CO2 and trees | PASS |
โ 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
- Global variables / constants are created:
SLABS,CO2. - 10 functions are defined (lines 10โ95) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
units(i) | 10โ11 | Units | total_units(), table(), highest(), replace() |
add() | 14โ22 | Add | main program |
total_units() | 25โ26 | Total units | table(), show_slabs(), fewer_hours(), replace() |
slab_bill(u) | 29โ37 | Slab bill | table(), show_slabs(), fewer_hours(), replace() |
table() | 40โ48 | Table | main program |
show_slabs() | 51โ60 | Show slabs | main program |
highest() | 63โ66 | Highest | main program |
fewer_hours() | 69โ78 | Fewer hours | main program |
replace() | 81โ89 | Replace | main program |
carbon() | 92โ95 | Carbon | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HOME ELECTRICITY SAVER (SDG 7) (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type Fan at Appliance name :
- You type 75 at Power (watts) :
- You type 10 at Hours per day :shows: Fan added -> 22.5 units per month (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type LED Bulbs at Appliance name :
- You type 40 at Power (watts) :
- You type 6 at Hours per day :shows: LED Bulbs added -> 7.2 units per month (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type Refrigerator at Appliance name :
- You type 150 at Power (watts) :
- You type 24 at Hours per day :shows: Refrigerator added -> 108.0 units per month (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type AC at Appliance name :
- You type 1500 at Power (watts) :
- You type 6 at Hours per day :shows: AC added -> 270.0 units per month (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type TV at Appliance name :
- You type 100 at Power (watts) :
- You type 30 at Hours per day :shows: Hours must be 0-24 and watts positive. Not added. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type TV at Appliance name :
- You type 100 at Power (watts) :
- You type 4 at Hours per day :shows: TV added -> 12.0 units per month (+1 more lines)
- 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) - 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) - You type 4 at Enter choice:runs:
highest()โunits()ร5shows: Highest consumer: AC - 64.3 % of units (+1 more lines) - You type 5 at Enter choice:runs:
fewer_hours() - You type AC at Appliance:
- You type 2 at Reduce by hours/day:runs:
total_units()โunits()ร5 โslab_bill()ร2shows: Units saved per month: 90.0 | Money saved: Rs. 444.40/month, Rs. 5332.80/year (+1 more lines) - You type 6 at Enter choice:runs:
replace() - You type LED Bulbs at Appliance:
- You type 30 at New appliance uses what % less power?runs:
units()โtotal_units()โunits()ร7 โslab_bill()ร2shows: LED Bulbs: 7.2 -> 5.0 units; saving Rs. 14.04 per month (+1 more lines) - You type 7 at Enter choice:runs:
carbon()โtotal_units()โunits()ร5shows: Monthly CO2: 344.2 kg | Yearly: 4.13 tonnes (+2 more lines) - You type 0 at Enter choice:shows: Save energy, save money!
โค Inside each function - line by line
units() - lines 10โ11
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Car Spotting and Tabulating - Probability Analyser
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
cars | list | Observed colours (title case) |
colours | list | Unique colours in order |
counts | list | Count of each colour |
evening | list | Second survey |
# =====================================================================
# 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")
==================================================== CAR SPOTTING & TABULATING - PROBABILITY ==================================================== 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 2 Enter observations first (option 1). 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 1 Enter car colours seen (comma separated): 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 Total cars observed: 30 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 2 Colour Count Probability % Bar ---------------------------------------------------- White 11 0.367 36.7% *********** Silver 6 0.200 20.0% ****** Black 4 0.133 13.3% **** Red 4 0.133 13.3% **** Blue 3 0.100 10.0% *** Grey 2 0.067 6.7% ** ---------------------------------------------------- Sum of all probabilities = 1.0 (always) 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 3 Mode (most common) : White - 11 cars Least common : ['Grey'] 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 4 Colour: red P(Red) = 4/30 = 0.133 P(not Red) = 1 - 0.133 = 0.867 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 4 Colour: purple P(Purple) = 0/30 = 0.000 P(not Purple) = 1 - 0.000 = 1.000 This is an IMPOSSIBLE event in our data. 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 5 Colour A: white Colour B: silver P(White or Silver) = 0.367 + 0.200 = 0.567 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 6 How many next cars to simulate? 20 Simulated: White, Silver, Silver, Blue, White, White, Black, Silver, Red, Silver, Red, Red, Red, Black, White, Black, White, Red, Silver, Red White expected 7.3 simulated 5 Silver expected 4.0 simulated 5 Black expected 2.7 simulated 3 Red expected 2.7 simulated 6 Blue expected 2.0 simulated 1 Grey expected 1.3 simulated 0 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 7 Evening colours (comma separated): black, white, black, silver, black, red, white, black, grey, black, white, silver, black, blue, white EVENING SURVEY Colour Count Probability % Bar ---------------------------------------------------- Black 6 0.400 40.0% ****** White 4 0.267 26.7% **** Silver 2 0.133 13.3% ** Red 1 0.067 6.7% * Grey 1 0.067 6.7% * Blue 1 0.067 6.7% * ---------------------------------------------------- Sum of all probabilities = 1.0 (always) Colour Morning Evening White 0.37 0.27 Silver 0.20 0.13 Black 0.13 0.40 Red 0.13 0.07 Blue 0.10 0.07 Grey 0.07 0.07 1.Enter 2.Table 3.Mode 4.P(colour) 5.P(A or B) 6.Simulate 7.Evening Survey 0.Exit Enter choice: 0 Bye!
- Start
- Show menu and read choice
- Observations entered? → No: ask to enter
- Count each colour and divide by total
- Show table / probability
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | 30 colours | Total 30 | PASS |
| 2 | Frequency table | White 11 -> 0.367 | PASS |
| 3 | Mode | White | PASS |
| 4 | P(Red) | 0.133 | PASS |
| 5 | P(Purple) | 0 (impossible event) | PASS |
| 6 | P(White or Silver) | 0.567 | PASS |
| 7 | Simulate 20 | Predicted counts | PASS |
| 8 | Evening survey | Comparison table | PASS |
โ 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
- Imports (line 5):
random- random number functions are loaded. - Global variables / constants are created:
cars. - 10 functions are defined (lines 10โ80) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
to_list(text) | 10โ11 | To list | enter(), evening() |
unique(lst) | 14โ19 | Unique | table(), mode_least(), simulate(), evening() |
enter() | 22โ25 | Enter | main program |
table(data) | 28โ36 | Table | evening(), main program |
mode_least() | 39โ43 | Mode least | main program |
p(colour) | 46โ47 | P | query(), p_or(), simulate() |
query() | 50โ56 | Query | main program |
p_or() | 59โ61 | P or | main program |
simulate() | 64โ71 | Simulate | main program |
evening() | 74โ80 | Evening | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CAR SPOTTING & TABULATING - PROBABILITY (+1 more lines)
- You type 2 at Enter choice:shows: Enter observations first (option 1). (+1 more lines)
- You type 1 at Enter choice:runs:
enter() - 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) - You type 2 at Enter choice:runs:
table()โunique()shows: Colour Count Probability % Bar (+8 more lines) - You type 3 at Enter choice:runs:
mode_least()โunique()shows: Mode (most common) : White - 11 cars (+2 more lines) - You type 4 at Enter choice:runs:
query() - You type red at Colour:runs:
p()shows: P(Red) = 4/30 = 0.133 (+2 more lines) - You type 4 at Enter choice:runs:
query() - You type purple at Colour:runs:
p()shows: P(Purple) = 0/30 = 0.000 (+3 more lines) - You type 5 at Enter choice:runs:
p_or() - You type white at Colour A:
- You type silver at Colour B:runs:
p()ร4shows: P(White or Silver) = 0.367 + 0.200 = 0.567 (+1 more lines) - You type 6 at Enter choice:runs:
simulate() - You type 20 at How many next cars to simulate?runs:
unique()โp()ร6shows: Simulated: White, Silver, Silver, Blue, White, White, Black, Silver, Red, Silver, Red, Red (+7 more lines) - You type 7 at Enter choice:runs:
evening() - 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()ร2shows: EVENING SURVEY (+16 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
to_list() - lines 10โ11
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Rule-Based Crop Advisor for Farmers (SDG 2)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
CROPS | list of lists | crop, sowing, harvest, yield q/acre, MSP Rs./q, cost Rs./acre, NPK, water |
farmers / advice | lists | Names and crops advised |
advise() | function | Rule base returning crop and reason |
# =====================================================================
# 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")
================================================== RULE-BASED CROP ADVISOR (SDG 2) ================================================== 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Ramesh Season (Kharif/Rabi/Zaid): Kharif Soil type (clay/loamy/sandy/black): clay Expected rainfall (mm): 1200 Recommended crop for Ramesh: Rice Reason (rule fired): Rule K1: high rainfall + water-holding soil 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Sita Season (Kharif/Rabi/Zaid): Kharif Soil type (clay/loamy/sandy/black): black Expected rainfall (mm): 700 Recommended crop for Sita: Cotton Reason (rule fired): Rule K2: black soil retains moisture 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Gurpreet Season (Kharif/Rabi/Zaid): Rabi Soil type (clay/loamy/sandy/black): loamy Expected rainfall (mm): 400 Recommended crop for Gurpreet: Wheat Reason (rule fired): Rule R1: cool season + loamy soil 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Bhola Season (Kharif/Rabi/Zaid): Rabi Soil type (clay/loamy/sandy/black): sandy Expected rainfall (mm): 300 Recommended crop for Bhola: Mustard Reason (rule fired): Rule R2: light soil, little water 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Anil Season (Kharif/Rabi/Zaid): Zaid Soil type (clay/loamy/sandy/black): sandy Expected rainfall (mm): 100 Recommended crop for Anil: Watermelon Reason (rule fired): Rule Z1: short summer season crop 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 1 Farmer name: Test Season (Kharif/Rabi/Zaid): winter Soil type (clay/loamy/sandy/black): clay Expected rainfall (mm): 500 Sorry - Unknown season - please enter Kharif, Rabi or Zaid. 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 2 Crop: Wheat Wheat: NPK 50:25:12 kg/acre (N:P:K) | Irrigation: 4-6 irrigations; first at 21 days Tip: get a Soil Health Card test before applying fertiliser. 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 3 Crop: Wheat Area (acres): 5 Expected yield : 100.0 quintals Income @ MSP : Rs. 258,500 Cost : Rs. 125,000 Profit : Rs. 133,500 (107 % return) 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 4 Crop: Rice Rice: sow in Jun-Jul, harvest in Oct-Nov 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 5 No Farmer Crop 1 Ramesh Rice 2 Sita Cotton 3 Gurpreet Wheat 4 Bhola Mustard 5 Anil Watermelon Rice : 1 farmer(s) Cotton : 1 farmer(s) Wheat : 1 farmer(s) Mustard : 1 farmer(s) Watermelon: 1 farmer(s) Note: rule-based advice; verify with the local Krishi Vigyan Kendra. 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 6 K1 Kharif + rain>=1000 + clay/loamy -> Rice | K2 Kharif + black -> Cotton K3 Kharif + rain>=500 -> Maize | K4 Kharif otherwise -> Bajra R1 Rabi + loamy + rain<600 -> Wheat | R2 Rabi + sandy -> Mustard | R3 Rabi otherwise -> Gram Z1 Zaid -> Watermelon 1.Advise 2.Fertiliser & Water 3.Profit 4.Calendar 5.Summary 6.Rules 0.Exit Enter choice: 0 Jai Kisan!
- Start
- Show menu and read choice
- Choice is Advise? → No: run other option
- Read season, soil, rainfall
- Season = Kharif? → No: check Rabi / Zaid rules
- Apply rules to choose crop
- Show crop and reason
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Kharif, clay, 1200 mm | Rice | PASS |
| 2 | Kharif, black, 700 mm | Cotton | PASS |
| 3 | Rabi, loamy, 400 mm | Wheat | PASS |
| 4 | Rabi, sandy | Mustard | PASS |
| 5 | Zaid | Watermelon | PASS |
| 6 | Season 'winter' | 'Unknown season' | PASS |
| 7 | Profit Wheat 5 acres | Profit shown | PASS |
| 8 | Calendar Rice | Jun-Jul / Oct-Nov | PASS |
โ 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
- Global variables / constants are created:
CROPS. - 8 functions are defined (lines 17โ100) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
find(crop) | 17โ21 | Find | fert_water(), profit(), calendar() |
advise(season, soil, rain) | 24โ42 | The rule base: returns (crop, reason). | advise_farmer() |
advise_farmer() | 45โ56 | Advise farmer | main program |
fert_water() | 59โ65 | Fert water | main program |
profit() | 68โ78 | Profit | main program |
calendar() | 81โ83 | Calendar | main program |
summary() | 86โ93 | Summary | main program |
rules() | 96โ100 | Rules | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: RULE-BASED CROP ADVISOR (SDG 2) (+1 more lines)
- You type 1 at Enter choice:runs:
advise_farmer() - You type Ramesh at Farmer name:
- You type Kharif at Season (Kharif/Rabi/Zaid):
- You type clay at Soil type (clay/loamy/sandy/black):
- You type 1200 at Expected rainfall (mm):runs:
advise()shows: Recommended crop for Ramesh: Rice (+2 more lines) - You type 1 at Enter choice:runs:
advise_farmer() - You type Sita at Farmer name:
- You type Kharif at Season (Kharif/Rabi/Zaid):
- You type black at Soil type (clay/loamy/sandy/black):
- You type 700 at Expected rainfall (mm):runs:
advise()shows: Recommended crop for Sita: Cotton (+2 more lines) - You type 1 at Enter choice:runs:
advise_farmer() - You type Gurpreet at Farmer name:
- You type Rabi at Season (Kharif/Rabi/Zaid):
- You type loamy at Soil type (clay/loamy/sandy/black):
- You type 400 at Expected rainfall (mm):runs:
advise()shows: Recommended crop for Gurpreet: Wheat (+2 more lines) - You type 1 at Enter choice:runs:
advise_farmer() - You type Bhola at Farmer name:
- You type Rabi at Season (Kharif/Rabi/Zaid):
- You type sandy at Soil type (clay/loamy/sandy/black):
- You type 300 at Expected rainfall (mm):runs:
advise()shows: Recommended crop for Bhola: Mustard (+2 more lines) - You type 1 at Enter choice:runs:
advise_farmer() - You type Anil at Farmer name:
- You type Zaid at Season (Kharif/Rabi/Zaid):
- You type sandy at Soil type (clay/loamy/sandy/black):
- You type 100 at Expected rainfall (mm):runs:
advise()shows: Recommended crop for Anil: Watermelon (+2 more lines) - You type 1 at Enter choice:runs:
advise_farmer() - You type Test at Farmer name:
- You type winter at Season (Kharif/Rabi/Zaid):
- You type clay at Soil type (clay/loamy/sandy/black):
- You type 500 at Expected rainfall (mm):runs:
advise()shows: Sorry - Unknown season - please enter Kharif, Rabi or Zaid. (+1 more lines) - You type 2 at Enter choice:runs:
fert_water() - 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) - You type 3 at Enter choice:runs:
profit() - You type Wheat at Crop:runs:
find() - You type 5 at Area (acres):shows: Expected yield : 100.0 quintals (+4 more lines)
- You type 4 at Enter choice:runs:
calendar() - You type Rice at Crop:runs:
find()shows: Rice: sow in Jun-Jul, harvest in Oct-Nov (+1 more lines) - You type 5 at Enter choice:runs:
summary()shows: No Farmer Crop (+12 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Personalised Learning Quiz - AI Project Cycle (SDG 4)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
questions / answers / topics / hints | lists | Parallel lists of the question bank |
names, scores | lists | Students and their scores |
t_right, t_total | lists | Class-wide topic counters |
# =====================================================================
# 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")
================================================== PERSONALISED AI LEARNING QUIZ (SDG 4) ================================================== 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 1 Enter your name: Meera Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)? Your answer (h = hint): cv Correct! Q2. [Domains] Google Translate belongs to which AI domain? Your answer (h = hint): nlp Correct! Q3. [Domains] Netflix recommendations belong to which AI domain? Your answer (h = hint): data Correct! Q4. [Project Cycle] Name the FIRST stage of the AI Project Cycle. Your answer (h = hint): problem scoping Correct! Q5. [Project Cycle] Collecting data from surveys and sensors is called ____ ____. Your answer (h = hint): h Hint: Starts with 'data' Your answer (h = hint): data acquisition Correct! Q6. [Modelling] A model where the developer writes all rules is called ____ based. Your answer (h = hint): rule Correct! Q7. [Domains] Rock-paper-scissors move prediction comes under which domain? Your answer (h = hint): data Correct! Q8. [Evaluation] Predicted YES and actually YES is called a ____ ____. Your answer (h = hint): true positive Correct! Q9. [Evaluation] Predicted NO but actually YES is called a ____ ____. Your answer (h = hint): false negative Correct! Q10. [Project Cycle] Training the AI model is done in which stage? Your answer (h = hint): modelling Correct! Q11. [Evaluation] (TP + TN) / Total is called ____. Your answer (h = hint): accuracy Correct! Q12. [Project Cycle] Making the model available to users is called ____. Your answer (h = hint): deployment Correct! ----- REPORT CARD: Meera ----- Domains : 4/4 **** Project Cycle : 4/4 **** Modelling : 1/1 * Evaluation : 3/3 *** Score: 12 / 12 = 100.0 % Level: ADVANCED - try Python projects next. 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 1 Enter your name: Arjun Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)? Your answer (h = hint): cv Correct! Q2. [Domains] Google Translate belongs to which AI domain? Your answer (h = hint): nlp Correct! Q3. [Domains] Netflix recommendations belong to which AI domain? Your answer (h = hint): netflix Oops! Correct answer: data Q4. [Project Cycle] Name the FIRST stage of the AI Project Cycle. Your answer (h = hint): data acquisition Oops! Correct answer: problem scoping Q5. [Project Cycle] Collecting data from surveys and sensors is called ____ ____. Your answer (h = hint): h Hint: Starts with 'data' Your answer (h = hint): data acquisition Correct! Q6. [Modelling] A model where the developer writes all rules is called ____ based. Your answer (h = hint): rule Correct! Q7. [Domains] Rock-paper-scissors move prediction comes under which domain? Your answer (h = hint): data Correct! Q8. [Evaluation] Predicted YES and actually YES is called a ____ ____. Your answer (h = hint): true negative Oops! Correct answer: true positive Q9. [Evaluation] Predicted NO but actually YES is called a ____ ____. Your answer (h = hint): false negative Correct! Q10. [Project Cycle] Training the AI model is done in which stage? Your answer (h = hint): evaluation Oops! Correct answer: modelling Q11. [Evaluation] (TP + TN) / Total is called ____. Your answer (h = hint): precision Oops! Correct answer: accuracy Q12. [Project Cycle] Making the model available to users is called ____. Your answer (h = hint): deployment Correct! ----- REPORT CARD: Arjun ----- Domains : 3/4 *** Project Cycle : 2/4 ** Modelling : 1/1 * Evaluation : 1/3 * Score: 7 / 12 = 58.3 % Level: INTERMEDIATE - revise Evaluation 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 2 Topic (Domains/Project Cycle/Modelling/Evaluation): Evaluation Predicted YES and actually YES is called a ____ ____. Your answer (h = hint): true positive Correct! Predicted NO but actually YES is called a ____ ____. Your answer (h = hint): false negative Correct! (TP + TN) / Total is called ____. Your answer (h = hint): accuracy Correct! Practice score in Evaluation: 3/3 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 2 Topic (Domains/Project Cycle/Modelling/Evaluation): xyz No such topic. 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 3 1. Meera 12/12 2. Arjun 7/12 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 4 Domains class accuracy 87.5 % Project Cycle class accuracy 75.0 % Modelling class accuracy 100.0 % Evaluation class accuracy 77.8 % Teacher should re-teach: Project Cycle 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 5 Domains : 4 questions Project Cycle : 4 questions Modelling : 1 questions Evaluation : 3 questions Total: 12 1.Full Quiz 2.Practice Topic 3.Leaderboard 4.Class Weak Topics 5.Bank Stats 0.Exit Enter choice: 0 Keep learning!
- Start
- Show menu and read choice
- Choice is Full Quiz? → No: run other option
- Read name
- Ask question; 'h' shows hint
- Answer correct? → No: show correct answer
- Update topic scores
- Report card and recommendation
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | All correct | ADVANCED level | PASS |
| 2 | 7/12 correct | INTERMEDIATE + weak topic to revise | PASS |
| 3 | Type 'h' | Hint shown and asked again | PASS |
| 4 | Practice 'Evaluation' | Only evaluation questions | PASS |
| 5 | Practice 'xyz' | 'No such topic' | PASS |
| 6 | Leaderboard | Sorted list | PASS |
| 7 | Class weak topics | Accuracy per topic | PASS |
โ 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
- Global variables / constants are created:
questions,answers,topics,hints,TOPICS. - 6 functions are defined (lines 26โ99) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
ask(i) | 26โ41 | Asks question i; returns True if correct. 'h' shows a hint. | full_quiz(), practice() |
full_quiz() | 44โ66 | Full quiz | main program |
practice() | 69โ79 | Practice | main program |
leaderboard() | 82โ85 | Leaderboard | main program |
class_weak() | 88โ93 | Class weak | main program |
bank() | 96โ99 | Bank | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: PERSONALISED AI LEARNING QUIZ (SDG 4) (+1 more lines)
- You type 1 at Enter choice:runs:
full_quiz() - You type Meera at Enter your name:runs:
ask()shows: Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)? - You type cv at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type nlp at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type data at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type problem scoping at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type h at Your answer (h = hint):shows: Hint: Starts with 'data'
- You type data acquisition at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type rule at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type data at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type true positive at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type false negative at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type modelling at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type accuracy at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type deployment at Your answer (h = hint):shows: Correct! (+8 more lines)
- You type 1 at Enter choice:runs:
full_quiz() - You type Arjun at Enter your name:runs:
ask()shows: Q1. [Domains] Face unlock in phones belongs to which AI domain (cv/nlp/data)? - You type cv at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type nlp at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type netflix at Your answer (h = hint):runs:
ask()shows: Oops! Correct answer: data (+1 more lines) - You type data acquisition at Your answer (h = hint):runs:
ask()shows: Oops! Correct answer: problem scoping (+1 more lines) - You type h at Your answer (h = hint):shows: Hint: Starts with 'data'
- You type data acquisition at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type rule at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type data at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type true negative at Your answer (h = hint):runs:
ask()shows: Oops! Correct answer: true positive (+1 more lines) - You type false negative at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type evaluation at Your answer (h = hint):runs:
ask()shows: Oops! Correct answer: modelling (+1 more lines) - You type precision at Your answer (h = hint):runs:
ask()shows: Oops! Correct answer: accuracy (+1 more lines) - You type deployment at Your answer (h = hint):shows: Correct! (+8 more lines)
- You type 2 at Enter choice:runs:
practice() - You type Evaluation at Topic (Domains/Project Cycle/Modelling/Evaluation):runs:
ask()shows: Predicted YES and actually YES is called a ____ ____. - You type true positive at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type false negative at Your answer (h = hint):runs:
ask()shows: Correct! (+1 more lines) - You type accuracy at Your answer (h = hint):shows: Correct! (+2 more lines)
- You type 2 at Enter choice:runs:
practice() - You type xyz at Topic (Domains/Project Cycle/Modelling/Evaluation):shows: No such topic. (+1 more lines)
- You type 3 at Enter choice:runs:
leaderboard()shows: 1. Meera 12/12 (+2 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Preventable Blindness Screening - Model Evaluator (SDG 3)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
actual | list | 1 = disease, 0 = healthy (20 patients) |
model_a / model_b | lists | Predictions of two models |
scores | list of float | Model probability of disease |
matrix() | function | Returns TP, FP, TN, FN |
# =====================================================================
# 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")
=======================================================
AI SCREENING MODEL EVALUATOR (SDG 3)
=======================================================
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 1
Patient Actual Model A Score
P01 1 1 0.91
P02 0 0 0.12
P03 1 1 0.84
P04 1 0 0.42 <- wrong
P05 0 0 0.08
P06 0 1 0.63 <- wrong
P07 1 1 0.77
P08 0 0 0.35
P09 1 1 0.88
P10 0 0 0.21
P11 1 1 0.95
P12 0 0 0.15
P13 0 1 0.58 <- wrong
P14 1 1 0.81
P15 0 0 0.05
P16 1 0 0.38 <- wrong
P17 1 1 0.72
P18 0 0 0.27
P19 0 0 0.18
P20 1 1 0.93
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 2
Reality: Disease Reality: Healthy
Predicted Disease TP = 8 FP = 2
Predicted Healthy FN = 2 TN = 8
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 3
Accuracy = (TP+TN)/Total = 16/20 = 80.0 %
Precision = TP/(TP+FP) = 8/10 = 0.80
Recall = TP/(TP+FN) = 8/10 = 0.80
F1 score = 2PR/(P+R) = 0.80
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 4
P04 - FALSE NEGATIVE: disease missed! (score 0.42 )
P06 - false positive: extra check-up needed
P13 - false positive: extra check-up needed
P16 - FALSE NEGATIVE: disease missed! (score 0.38 )
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 5
Model TP FP TN FN Accuracy Recall
Model A 8 2 8 2 80% 0.80
Model B 10 3 7 0 85% 1.00
Safer choice for screening: Model B (fewest missed patients)
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 6
Threshold (0-1): 0.3
Threshold 0.3: TP 10 FP 3 TN 7 FN 0
at 0.3: FN = 0, FP = 3
at 0.5: FN = 2, FP = 2
at 0.7: FN = 2, FP = 0
Lower threshold -> fewer missed patients but more false alarms.
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 6
Threshold (0-1): abc
Invalid value.
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 7
In medical screening a FALSE NEGATIVE means a sick patient is told 'healthy'.
He may not visit a doctor and can lose eyesight. So we prefer HIGH RECALL,
and AI should only ASSIST doctors, who re-check every 'healthy' result.
1.Data 2.Matrix 3.Metrics 4.Missed 5.Compare 6.Threshold 7.Ethics 0.Exit
Enter choice: 0
Bye!
- Start
- Show menu and read choice
- Loop over actual and predicted pairs
- actual = 1 and predicted = 1? → No: check FP / TN / FN
- Count TP, FP, TN, FN
- Compute metrics
- Show matrix / metrics
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Confusion matrix Model A | TP 8, FP 2, TN 8, FN 2 | PASS |
| 2 | Accuracy | 80 % | PASS |
| 3 | Recall | 0.8 | PASS |
| 4 | Missed patients | P04 and P16 | PASS |
| 5 | Compare | Model B has fewer FN | PASS |
| 6 | Threshold 0.3 | FN drops, FP rises | PASS |
| 7 | Threshold 'abc' | Invalid value | PASS |
โ 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
- Global variables / constants are created:
actual,model_a,model_b,scores,patients. - 9 functions are defined (lines 13โ95) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
matrix(act, pred) | 13โ24 | Matrix | show_matrix(), show_metrics(), compare(), threshold() |
metrics(TP, FP, TN, FN) | 27โ32 | Metrics | show_metrics(), compare() |
show_data() | 35โ39 | Show data | main program |
show_matrix() | 42โ46 | Show matrix | main program |
show_metrics() | 49โ55 | Show metrics | main program |
missed() | 58โ63 | Missed | main program |
compare() | 66โ75 | Compare | main program |
threshold() | 78โ89 | Threshold | main program |
ethics() | 92โ95 | Ethics | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: AI SCREENING MODEL EVALUATOR (SDG 3) (+1 more lines)
- You type 1 at Enter choice:runs:
show_data()shows: Patient Actual Model A Score (+21 more lines) - You type 2 at Enter choice:runs:
show_matrix()โmatrix()shows: Reality: Disease Reality: Healthy (+3 more lines) - You type 3 at Enter choice:runs:
show_metrics()โmatrix()โmetrics()shows: Accuracy = (TP+TN)/Total = 16/20 = 80.0 % (+4 more lines) - You type 4 at Enter choice:runs:
missed()shows: P04 - FALSE NEGATIVE: disease missed! (score 0.42 ) (+4 more lines) - You type 5 at Enter choice:runs:
compare()โmatrix()โmetrics()โmatrix()โmetrics()shows: Model TP FP TN FN Accuracy Recall (+4 more lines) - You type 6 at Enter choice:runs:
threshold() - You type 0.3 at Threshold (0-1):runs:
matrix()ร4shows: Threshold 0.3: TP 10 FP 3 TN 7 FN 0 (+5 more lines) - You type 6 at Enter choice:runs:
threshold() - You type abc at Threshold (0-1):shows: Invalid value. (+1 more lines)
- 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) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
matrix() - lines 13โ24
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Top 10 Songs Data Explorer
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
songs, genre | lists | Song names and genre |
last_week, this_week | lists | Million streams |
growth | list | Growth % calculated |
# =====================================================================
# 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")
================================================== TOP SONGS DATA EXPLORER ================================================== 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 1 Rank Song Genre Streams Growth Chart 1 Song C Pop 14.8M -2.6% |||||||||||||| 2 Song J Pop 13.5M 3.1% ||||||||||||| 3 Song A Pop 13.1M 9.2% ||||||||||||| 4 Song B Folk 12.4M 30.5% |||||||||||| 5 Song H Pop 11.9M 16.7% ||||||||||| 6 Song E Rap 11.6M 5.5% ||||||||||| 7 Song F Folk 9.1M 40.0% ||||||||| 8 Song G Indie 8.2M -7.9% |||||||| 9 Song D Indie 7.9M 1.3% ||||||| 10 Song I Rap 7.0M 40.0% ||||||| 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 2 Song A 12.0 -> 13.1 UP 9.2% Song B 9.5 -> 12.4 UP 30.5% Song C 15.2 -> 14.8 DOWN -2.6% Song D 7.8 -> 7.9 UP 1.3% Song E 11.0 -> 11.6 UP 5.5% Song F 6.5 -> 9.1 UP 40.0% Song G 8.9 -> 8.2 DOWN -7.9% Song H 10.2 -> 11.9 UP 16.7% Song I 5.0 -> 7.0 UP 40.0% Song J 13.1 -> 13.5 UP 3.1% Fastest growing: Song F (+40.0%) Biggest fall : Song G (-7.9%) 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 3 Average streams: 10.95 million Above average : ['Song A', 'Song B', 'Song C', 'Song E', 'Song H', 'Song J'] 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 4 Genre Songs Streams Average Pop 4 53.3 13.32 Folk 2 21.5 10.75 Indie 2 16.1 8.05 Rap 2 18.6 9.30 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 5 Song name: Song E Song E (Rap): last week 11.0M, this week 11.6M, growth 5.5% 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 5 Song name: Song Z Song not found. 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 6 Predicted No.1: Song B with about 16.2 M streams Predicted No.2: Song C with about 14.4 M streams Predicted No.3: Song A with about 14.3 M streams 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 7 Song name: Song K Genre: Indie Last week streams (M): 4.2 This week streams (M): 8.8 Added. Songs in chart data: 11 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 1 Rank Song Genre Streams Growth Chart 1 Song C Pop 14.8M -2.6% |||||||||||||| 2 Song J Pop 13.5M 3.1% ||||||||||||| 3 Song A Pop 13.1M 9.2% ||||||||||||| 4 Song B Folk 12.4M 30.5% |||||||||||| 5 Song H Pop 11.9M 16.7% ||||||||||| 6 Song E Rap 11.6M 5.5% ||||||||||| 7 Song F Folk 9.1M 40.0% ||||||||| 8 Song K Indie 8.8M 109.5% |||||||| 9 Song G Indie 8.2M -7.9% |||||||| 10 Song D Indie 7.9M 1.3% ||||||| 11 Song I Rap 7.0M 40.0% ||||||| 1.Chart 2.Growth 3.Above Avg 4.Genres 5.Search 6.Predict 7.Add Song 0.Exit Enter choice: 0 Keep listening!
- Start
- Calculate growth list
- Show menu and read choice
- Choice valid? → No: 'Invalid choice'
- Sort / filter / predict
- Show result
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Chart | Song C No. 1 | PASS |
| 2 | Growth | Song F +40 % | PASS |
| 3 | Above average | List of songs | PASS |
| 4 | Genre summary | Pop, Folk, Indie, Rap | PASS |
| 5 | Search 'Song E' | Details | PASS |
| 6 | Search 'Song Z' | Not found | PASS |
| 7 | Predict | Next No. 1 | PASS |
| 8 | Add song | List grows to 11 | PASS |
โ 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
- Global variables / constants are created:
songs,genre,last_week,this_week. - 8 functions are defined (lines 11โ67) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
growth(i) | 11โ12 | Growth | chart(), growth_report(), search(), predict() |
chart() | 15โ19 | Chart | main program |
growth_report() | 22โ28 | Growth report | main program |
above() | 31โ34 | Above | main program |
genres() | 37โ45 | Genres | main program |
search() | 48โ54 | Search | main program |
predict() | 57โ61 | Predict | main program |
add() | 64โ67 | Add | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: TOP SONGS DATA EXPLORER (+1 more lines)
- You type 1 at Enter choice:runs:
chart()โgrowth()ร10shows: Rank Song Genre Streams Growth Chart (+11 more lines) - You type 2 at Enter choice:runs:
growth_report()โgrowth()ร10shows: Song A 12.0 -> 13.1 UP 9.2% (+12 more lines) - You type 3 at Enter choice:runs:
above()shows: Average streams: 10.95 million (+2 more lines) - You type 4 at Enter choice:runs:
genres()shows: Genre Songs Streams Average (+5 more lines) - You type 5 at Enter choice:runs:
search() - 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) - You type 5 at Enter choice:runs:
search() - You type Song Z at Song name:shows: Song not found. (+1 more lines)
- You type 6 at Enter choice:runs:
predict()โgrowth()ร10shows: Predicted No.1: Song B with about 16.2 M streams (+3 more lines) - You type 7 at Enter choice:runs:
add() - You type Song K at Song name:
- You type Indie at Genre:
- You type 4.2 at Last week streams (M):
- You type 8.8 at This week streams (M):shows: Added. Songs in chart data: 11 (+1 more lines)
- You type 1 at Enter choice:runs:
chart()โgrowth()ร11shows: Rank Song Genre Streams Growth Chart (+12 more lines) - You type 0 at Enter choice:shows: Keep listening!
โค Inside each function - line by line
growth() - lines 11โ12
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Family Health & BMI Advisor (SDG 3)
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
๐ฏ Objectives
- Calculate BMI using arithmetic expressions
- Classify values into categories with if-elif rules
- Summarise categories with counters and give advice
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
names, ages, genders, hts, wts, acts | lists | Member details |
bmi() | function | weight / (height in m)^2 |
category() | function | BMI class |
FACTOR | list | Activity multipliers 1.2 / 1.55 / 1.75 |
# =====================================================================
# 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")
================================================== FAMILY HEALTH & BMI ADVISOR (SDG 3) ================================================== 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 2 Add members first. 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 1 Name : Papa Age : 45 Gender M/F : M Height (cm) : 170 Weight (kg) : 92 Activity 1-Sedentary 2-Moderate 3-Active: 1 Papa added. BMI = 31.8 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 1 Name : Mummy Age : 42 Gender M/F : F Height (cm) : 160 Weight (kg) : 66 Activity 1-Sedentary 2-Moderate 3-Active: 2 Mummy added. BMI = 25.8 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 1 Name : Riya Age : 15 Gender M/F : F Height (cm) : 150 Weight (kg) : 40 Activity 1-Sedentary 2-Moderate 3-Active: 3 Riya added. BMI = 17.8 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 1 Name : Kabir Age : 17 Gender M/F : M Height (cm) : 165 Weight (kg) : 60 Activity 1-Sedentary 2-Moderate 3-Active: 3 Kabir added. BMI = 22.0 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 1 Name : Test Age : 20 Gender M/F : M Height (cm) : 0 Weight (kg) : 50 Invalid height / weight. Member not added. 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 2 Name Age Ht(cm) Wt(kg) BMI Category -------------------------------------------------- Papa 45 170 92 31.8 Obese Mummy 42 160 66 25.8 Overweight Riya 15 150 40 17.8 Underweight Kabir 17 165 60 22.0 Normal 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 3 Papa healthy weight 53.5 - 72.0 kg (20.0 kg above) Mummy healthy weight 47.4 - 63.7 kg (2.3 kg above) Riya healthy weight 41.6 - 56.0 kg (1.6 kg below) Kabir healthy weight 50.4 - 67.8 kg (in range) 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 4 Papa calories ~2115 kcal/day | water ~3.2 L/day Mummy calories ~1998 kcal/day | water ~2.3 L/day Riya calories ~1928 kcal/day | water ~1.4 L/day Kabir calories ~2715 kcal/day | water ~2.1 L/day 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 5 Underweight : 1 * Normal : 1 * Overweight : 1 * Obese : 1 * Family average BMI: 24.4 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 6 Papa (Obese): Consult a doctor, plan diet with a nutritionist, start with light daily walks. Mummy (Overweight): Walk 45 min daily, avoid sugary drinks and fried snacks, eat more salad. Riya (Underweight): Eat protein-rich food (dal, paneer, eggs), add healthy snacks, do strength exercise. Kabir (Normal): Great! Keep 60 min activity, balanced meals and 8 hours sleep. Note: general tips only - consult a doctor for medical advice. 1.Add Member 2.BMI Table 3.Healthy Range 4.Calories & Water 5.Summary 6.Tips 0.Exit Enter choice: 0 Stay healthy!
- Start
- Show menu and read choice
- Choice is Add? → No: check members exist
- Read member details
- BMI = weight / height^2
- BMI < 18.5? → No: check other categories
- Show table / tips
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Papa 170 cm 92 kg | BMI 31.8 Obese | PASS |
| 2 | Mummy 160/66 | 25.8 Overweight | PASS |
| 3 | Riya 150/40 | 17.8 Underweight | PASS |
| 4 | Height 0 | 'Invalid height' | PASS |
| 5 | Healthy range 170 cm | 53.5-72.0 kg | PASS |
| 6 | Calories | Estimate per member | PASS |
| 7 | Summary | Counts and average | PASS |
โ 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
- Global variables / constants are created:
FACTOR,TIPS. - 8 functions are defined (lines 13โ75) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
bmi(i) | 13โ14 | Bmi | add(), table(), summary(), tips() |
category(b) | 17โ24 | Category | table(), summary(), tips() |
add() | 27โ38 | Add | main program |
table() | 41โ45 | Table | main program |
ranges() | 48โ54 | Ranges | main program |
needs() | 57โ61 | Needs | main program |
summary() | 64โ68 | Summary | main program |
tips() | 71โ75 | Tips | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: FAMILY HEALTH & BMI ADVISOR (SDG 3) (+1 more lines)
- You type 2 at Enter choice:shows: Add members first. (+1 more lines)
- You type 1 at Enter choice:runs:
add() - You type Papa at Name :
- You type 45 at Age :
- You type M at Gender M/F :
- You type 170 at Height (cm) :
- You type 92 at Weight (kg) :
- You type 1 at Activity 1-Sedentary 2-Moderate 3-Active:runs:
bmi()shows: Papa added. BMI = 31.8 (+1 more lines) - You type 1 at Enter choice:runs:
add() - You type Mummy at Name :
- You type 42 at Age :
- You type F at Gender M/F :
- You type 160 at Height (cm) :
- You type 66 at Weight (kg) :
- You type 2 at Activity 1-Sedentary 2-Moderate 3-Active:runs:
bmi()shows: Mummy added. BMI = 25.8 (+1 more lines) - You type 1 at Enter choice:runs:
add() - You type Riya at Name :
- You type 15 at Age :
- You type F at Gender M/F :
- You type 150 at Height (cm) :
- You type 40 at Weight (kg) :
- You type 3 at Activity 1-Sedentary 2-Moderate 3-Active:runs:
bmi()shows: Riya added. BMI = 17.8 (+1 more lines) - You type 1 at Enter choice:runs:
add() - You type Kabir at Name :
- You type 17 at Age :
- You type M at Gender M/F :
- You type 165 at Height (cm) :
- You type 60 at Weight (kg) :
- You type 3 at Activity 1-Sedentary 2-Moderate 3-Active:runs:
bmi()shows: Kabir added. BMI = 22.0 (+1 more lines) - You type 1 at Enter choice:runs:
add() - You type Test at Name :
- You type 20 at Age :
- You type M at Gender M/F :
- You type 0 at Height (cm) :
- You type 50 at Weight (kg) :shows: Invalid height / weight. Member not added. (+1 more lines)
- You type 2 at Enter choice:runs:
table()โbmi()ร2 โcategory()โbmi()ร2 โcategory()โbmi()ร2 โcategory()โbmi()ร2shows: Name Age Ht(cm) Wt(kg) BMI Category (+5 more lines) - You type 3 at Enter choice:runs:
ranges()shows: Papa healthy weight 53.5 - 72.0 kg (20.0 kg above) (+4 more lines) - You type 4 at Enter choice:runs:
needs()shows: Papa calories ~2115 kcal/day | water ~3.2 L/day (+4 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Smart Waste Segregation Guide (SDG 12)
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
๐ฏ Objectives
- Represent knowledge as keyword lists
- Classify items using membership tests
- Count and report category-wise percentages
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
wet, dry, ewaste, hazard | lists | Keywords for each category |
log_items, log_cats | lists | Items classified today |
classify() | function | Returns category and bin |
SAMPLE | list of pairs | Items with correct labels for testing |
# =====================================================================
# 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")
======================================================= SMART WASTE SEGREGATION GUIDE (SDG 12) ======================================================= 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 1 Enter waste items (comma separated): banana peel, plastic bottle, old mobile charger, newspaper, tea leaves, used battery, chips packet, broken thermometer, vegetable peels, mystery object, diaper banana peel -> Wet : Green bin (compost) plastic bottle -> Dry : Blue bin (recycle) old mobile charger -> E-waste : E-waste collection centre newspaper -> Dry : Blue bin (recycle) tea leaves -> Wet : Green bin (compost) used battery -> E-waste : E-waste collection centre chips packet -> Dry : Blue bin (recycle) broken thermometer -> Hazardous : Red bin / special disposal vegetable peels -> Wet : Green bin (compost) mystery object -> Unknown : Ask teacher / teach a new rule diaper -> Unknown : Ask teacher / teach a new rule 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 2 New keyword: diaper Category (wet/dry/ewaste/hazard): hazard Rule learnt: 'diaper' -> hazard 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 1 Enter waste items (comma separated): diaper, egg shells diaper -> Hazardous : Red bin / special disposal egg shells -> Wet : Green bin (compost) 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 3 Items classified today: 13 Wet : 4 ( 31 %) #### Dry : 3 ( 23 %) ### E-waste : 2 ( 15 %) ## Hazardous : 2 ( 15 %) ## Unknown : 2 ( 15 %) ## 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 4 Wet items today: 4 (~2.0 kg at 0.5 kg each) Compost after 45 days: ~0.6 kg | in a month (x30): ~18 kg 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 5 apple core fruit expected Wet got Wet OK milk packet expected Dry got Dry OK tv remote expected E-waste got E-waste OK expired medicine expected Hazardous got Hazardous OK flower garland expected Wet got Wet OK cold drink can expected Dry got Dry OK usb cable expected E-waste got E-waste OK paint tin expected Hazardous got Hazardous OK cooked food expected Wet got Wet OK rubber slipper expected Dry got Unknown WRONG Accuracy = 9/10 = 90 % 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 2 New keyword: slipper Category (wet/dry/ewaste/hazard): dry Rule learnt: 'slipper' -> dry 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 5 apple core fruit expected Wet got Wet OK milk packet expected Dry got Dry OK tv remote expected E-waste got E-waste OK expired medicine expected Hazardous got Hazardous OK flower garland expected Wet got Wet OK cold drink can expected Dry got Dry OK usb cable expected E-waste got E-waste OK paint tin expected Hazardous got Hazardous OK cooked food expected Wet got Wet OK rubber slipper expected Dry got Dry OK Accuracy = 10/10 = 100 % 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 6 Hazardous : ['thermometer', 'medicine', 'syringe', 'paint', 'pesticide', 'diaper'] E-waste : ['charger', 'mobile', 'battery', 'cable', 'bulb', 'earphone', 'remote'] Wet : ['peel', 'food', 'tea', 'vegetable', 'fruit', 'egg', 'leaves', 'flower'] Dry : ['plastic', 'paper', 'newspaper', 'bottle', 'cardboard', 'packet', 'can', 'glass', 'slipper'] Order of checking: Hazardous -> E-waste -> Wet -> Dry 1.Classify 2.Teach Keyword 3.Summary 4.Compost 5.Test Accuracy 6.Rules 0.Exit Enter choice: 0 Segregate at source!
- Start
- Show menu and read choice
- Choice is Classify? → No: run other option
- Read items
- Hazard keyword? → No: check e-waste, wet, dry
- Assign category and bin
- Show bin; count
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | banana peel | Wet - Green bin | PASS |
| 2 | plastic bottle | Dry - Blue bin | PASS |
| 3 | used battery | E-waste | PASS |
| 4 | broken thermometer | Hazardous | PASS |
| 5 | mystery object | Unknown | PASS |
| 6 | Teach 'diaper' -> hazard | Next time classified Hazardous | PASS |
| 7 | Accuracy test | 9/10, then 10/10 after teaching slipper -> dry | PASS |
| 8 | Compost 5 kg | About 1.5 kg compost | PASS |
โ 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
- Global variables / constants are created:
wet,dry,ewaste,hazard,BINS,SAMPLE. - 7 functions are defined (lines 17โ78) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
classify(item) | 17โ26 | Classify | classify_items(), test_accuracy() |
classify_items() | 29โ35 | Classify items | main program |
teach() | 38โ46 | Teach | main program |
summary() | 49โ54 | Summary | main program |
compost() | 57โ60 | Compost | main program |
test_accuracy() | 63โ70 | Test accuracy | main program |
rules() | 73โ78 | Rules | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: SMART WASTE SEGREGATION GUIDE (SDG 12) (+1 more lines)
- You type 1 at Enter choice:runs:
classify_items() - 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()ร11shows: banana peel -> Wet : Green bin (compost) (+11 more lines) - You type 2 at Enter choice:runs:
teach() - You type diaper at New keyword:
- You type hazard at Category (wet/dry/ewaste/hazard):shows: Rule learnt: 'diaper' -> hazard (+1 more lines)
- You type 1 at Enter choice:runs:
classify_items() - You type diaper, egg shells at Enter waste items (comma separated):runs:
classify()ร2shows: diaper -> Hazardous : Red bin / special disposal (+2 more lines) - You type 3 at Enter choice:runs:
summary()shows: Items classified today: 13 (+6 more lines) - You type 4 at Enter choice:runs:
compost()shows: Wet items today: 4 (~2.0 kg at 0.5 kg each) (+2 more lines) - You type 5 at Enter choice:runs:
test_accuracy()โclassify()ร10shows: apple core fruit expected Wet got Wet OK (+11 more lines) - You type 2 at Enter choice:runs:
teach() - You type slipper at New keyword:
- You type dry at Category (wet/dry/ewaste/hazard):shows: Rule learnt: 'slipper' -> dry (+1 more lines)
- You type 5 at Enter choice:runs:
test_accuracy()โclassify()ร10shows: apple core fruit expected Wet got Wet OK (+11 more lines) - You type 6 at Enter choice:runs:
rules()shows: Hazardous : ['thermometer', 'medicine', 'syringe', 'paint', 'pesticide', 'diaper'] (+5 more lines) - You type 0 at Enter choice:shows: Segregate at source!
โค Inside each function - line by line
classify() - lines 17โ26
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Class Attendance Analyser and Predictor (SDG 4)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
names | list | 8 student names |
att | list of str | One string per student, 'P'/'A' per day |
days | list | Day names |
prob | float | Total presents / (students x days) |
# =====================================================================
# 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")
================================================== CLASS ATTENDANCE ANALYSER (SDG 4) ================================================== 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 1 Name Record % Status Anu PPPPPP 100.0% Regular Bilal PAPAPP 66.7% Needs support Chetna PPPPAP 83.3% Regular Dev AAPPPA 50.0% Needs support Esha PPPPPP 100.0% Regular Farhan PPAPPP 83.3% Regular Gita PPPPPA 83.3% Regular Harry PAAPPP 66.7% Needs support Class attendance: 38/48 = 79.2 % 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 2 Mon: 7/8 ####### Tue: 5/8 ##### Wed: 6/8 ###### Thu: 7/8 ####### Fri: 7/8 ####### Sat: 6/8 ###### Lowest attendance day : Tue Highest attendance day: Mon 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 3 P(student present on a day) = 0.792 P(student absent) = 0.208 Expected present tomorrow (class of 40): 32 P(Anu present tomorrow) = 1.00 P(Bilal present tomorrow) = 0.67 P(Chetna present tomorrow) = 0.83 P(Dev present tomorrow) = 0.50 P(Esha present tomorrow) = 1.00 P(Farhan present tomorrow) = 0.83 P(Gita present tomorrow) = 0.83 P(Harry present tomorrow) = 0.67 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 4 Marking attendance for D7 Anu (P/A): P Bilal (P/A): P Chetna (P/A): P Dev (P/A): A Esha (P/A): X Enter P or A only. Esha (P/A): P Farhan (P/A): P Gita (P/A): P Harry (P/A): P Attendance saved. Days recorded: 7 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 1 Name Record % Status Anu PPPPPPP 100.0% Regular Bilal PAPAPPP 71.4% Needs support Chetna PPPPAPP 85.7% Regular Dev AAPPPAA 42.9% Needs support Esha PPPPPPP 100.0% Regular Farhan PPAPPPP 85.7% Regular Gita PPPPPAP 85.7% Regular Harry PAAPPPP 71.4% Needs support Class attendance: 45/56 = 80.4 % 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 5 WARNING: Bilal PAPAPPP -> 2 absences; inform class teacher / parents WARNING: Dev AAPPPAA -> consecutive absences; inform class teacher / parents WARNING: Harry PAAPPPP -> consecutive absences; inform class teacher / parents 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 6 Student name: Esha Esha : Mon-P Tue-P Wed-P Thu-P Fri-P Sat-P D7-P Present 7 / 7 = 100.0 % 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 6 Student name: Zara Student not found. 1.Report 2.Day-wise 3.Probability 4.Mark Today 5.Early Warning 6.Search 0.Exit Enter choice: 0 Bye!
- Start
- Show menu and read choice
- Choice is Mark? → No: run report
- Read P/A for each student
- Input is P or A? → No: ask again
- Append to strings
- Show report / warning
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Weekly report | Dev 50 % Needs support | PASS |
| 2 | Day-wise | Lowest day shown | PASS |
| 3 | Probability | 0.792 | PASS |
| 4 | Mark day with 'X' | Asked again | PASS |
| 5 | Mark day | 7 days now | PASS |
| 6 | Early warning | Students with AA | PASS |
| 7 | Search 'Esha' | 100 % | PASS |
| 8 | Search 'Zara' | Not found | PASS |
โ 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
- Global variables / constants are created:
days,names,att. - 6 functions are defined (lines 10โ76) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
report() | 10โ17 | Report | main program |
day_wise() | 20โ30 | Day wise | main program |
probability() | 33โ40 | Probability | main program |
mark() | 43โ54 | Mark | main program |
warning() | 57โ66 | Warning | main program |
search() | 69โ76 | Search | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CLASS ATTENDANCE ANALYSER (SDG 4) (+1 more lines)
- You type 1 at Enter choice:runs:
report()shows: Name Record % Status (+10 more lines) - You type 2 at Enter choice:runs:
day_wise()shows: Mon: 7/8 ####### (+8 more lines) - You type 3 at Enter choice:runs:
probability()shows: P(student present on a day) = 0.792 (+11 more lines) - You type 4 at Enter choice:runs:
mark()shows: Marking attendance for D7 - You type P at Anu (P/A):
- You type P at Bilal (P/A):
- You type P at Chetna (P/A):
- You type A at Dev (P/A):
- You type X at Esha (P/A):shows: Enter P or A only.
- You type P at Esha (P/A):
- You type P at Farhan (P/A):
- You type P at Gita (P/A):
- You type P at Harry (P/A):shows: Attendance saved. Days recorded: 7 (+1 more lines)
- You type 1 at Enter choice:runs:
report()shows: Name Record % Status (+10 more lines) - You type 5 at Enter choice:runs:
warning()shows: WARNING: Bilal PAPAPPP -> 2 absences; inform class teacher / parents (+3 more lines) - You type 6 at Enter choice:runs:
search() - 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)
- You type 6 at Enter choice:runs:
search() - You type Zara at Student name:shows: Student not found. (+1 more lines)
- You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
report() - lines 10โ17
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Palmer Penguin Species Predictor (Statistical Data)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Penguins data (species, island, bill, flipper, mass) |
features | list | Columns used by the model |
mu, sd | Series | Mean and std of training data for scaling |
centroids | DataFrame | Mean scaled point of each species |
# =====================================================================
# 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")
=======================================================
PALMER PENGUIN SPECIES PREDICTOR
=======================================================
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 1
Dataset shape: (333, 8)
Species count:
species
Adelie 146
Gentoo 119
Chinstrap 68
Species on each island:
species Adelie Chinstrap Gentoo
island
Biscoe 44 0 119
Dream 55 68 0
Torgersen 47 0 0
Average measurements:
bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
species
Adelie 38.8 18.3 190.1 3706.2
Chinstrap 48.8 18.4 195.8 3733.1
Gentoo 47.6 15.0 217.2 5092.4
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 2
Training rows: 266 | Testing rows: 67
Learnt centroids (scaled):
bill_length_mm bill_depth_mm flipper_length_mm
species
Adelie -0.953 0.572 -0.781
Chinstrap 0.927 0.664 -0.339
Gentoo 0.641 -1.119 1.186
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 3
Correct: 62 / 67 -> Accuracy 92.54 %
Predicted Adelie Chinstrap Gentoo
Actual
Adelie 26 3 0
Chinstrap 2 10 0
Gentoo 0 0 26
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 4
Species Precision Recall Support
Adelie 0.93 0.90 29
Chinstrap 0.77 0.83 12
Gentoo 1.00 1.00 26
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 5
flipper accuracy 76.12 %
bill length + bill depth accuracy 86.57 %
bill length + bill depth + flipper accuracy 92.54 %
Best feature set: option 3 - more useful features -> better model
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 6
Bill length (mm) : 47.5
Bill depth (mm) : 15.0
Flipper length (mm): 217
distance to Adelie : 3.027
distance to Chinstrap : 2.361
distance to Gentoo : 0.037
Predicted species: Gentoo
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 6
Bill length (mm) : 39
Bill depth (mm) : 18.5
Flipper length (mm): 185
distance to Adelie : 0.391
distance to Chinstrap : 2.000
distance to Gentoo : 3.313
Predicted species: Adelie
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 7
flipper accuracy 76.12 %
bill length + bill depth accuracy 86.57 %
bill length + bill depth + flipper accuracy 92.54 %
Best feature set: option 3 - more useful features -> better model
Charts saved: penguin_scatter.png, penguin_box.png, penguin_accuracy.png
1.Explore 2.Train 3.Evaluate 4.Per-class 5.Experiment 6.Predict 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Load penguins.csv
- Show menu and read choice
- Model trained? → No: train first (option 2)
- Scale input with training mean / std
- Find nearest centroid
- Show species and distances
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Explore | 333 rows, 3 species | PASS |
| 2 | Evaluate before training | 'Train the model first' | PASS |
| 3 | Train | 266 train / 67 test | PASS |
| 4 | Evaluate | Accuracy 92.54 % (62/67) | PASS |
| 5 | Per-class report | Precision / recall | PASS |
| 6 | Experiment | 76 % -> 87 % -> 93 % as features are added | PASS |
| 7 | Predict 47.5, 15.0, 217 | Gentoo | PASS |
| 8 | Predict 39, 18.5, 185 | Adelie | PASS |
โ 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
- Imports (line 5):
numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
df,ALL,model. - 10 functions are defined (lines 14โ100) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
explore() | 14โ18 | Explore | main program |
fit(features, seed) | 21โ28 | Fit | train_model(), experiment() |
predict(m, row) | 31โ34 | Predict | preds(), new_penguin() |
train_model() | 37โ41 | Train model | main program |
preds(m) | 44โ45 | Preds | evaluate(), per_class(), experiment() |
evaluate() | 48โ53 | Evaluate | main program |
per_class() | 56โ63 | Per class | main program |
experiment() | 66โ76 | Experiment | charts(), main program |
new_penguin() | 79โ84 | New penguin | main program |
charts() | 87โ100 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: PALMER PENGUIN SPECIES PREDICTOR (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
explore()shows: Dataset shape: (333, 8) (+18 more lines) - You type 2 at Enter choice:runs:
train_model()โfit()shows: Training rows: 266 | Testing rows: 67 (+7 more lines) - You type 3 at Enter choice:runs:
evaluate()โpreds()โpredict()ร67shows: Correct: 62 / 67 -> Accuracy 92.54 % (+6 more lines) - You type 4 at Enter choice:runs:
per_class()โpreds()โpredict()ร67shows: Species Precision Recall Support (+4 more lines) - 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) - You type 6 at Enter choice:runs:
new_penguin() - You type 47.5 at Bill length (mm) :
- You type 15.0 at Bill depth (mm) :
- You type 217 at Flipper length (mm):runs:
predict()shows: distance to Adelie : 3.027 (+4 more lines) - You type 6 at Enter choice:runs:
new_penguin() - You type 39 at Bill length (mm) :
- You type 18.5 at Bill depth (mm) :
- You type 185 at Flipper length (mm):runs:
predict()shows: distance to Adelie : 0.391 (+4 more lines) - You type 7 at Enter choice:runs:
charts()โexperiment()โfit()โpreds()โpredict()ร67 โfit()โpreds()โpredict()ร67shows: [chart is drawn] (+8 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
explore() - lines 14โ18
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Coral Bleaching Early Detector (Computer Vision)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
folder | str | coral_images directory |
S_MAX, V_MIN | int | Thresholds for 'white' pixels |
results | list | (name, image, %, status) |
mask | bool array | True where pixel is bleached |
# =====================================================================
# 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")
======================================================= CORAL BLEACHING EARLY DETECTOR (Computer Vision) ======================================================= 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 2 6 reef images ready in coral_images Thresholds: S < 60, V > 170 Image Bleached % Status reef_1.jpg 1.5% Healthy reef_2.jpg 3.4% Healthy reef_3.jpg 17.5% Partly bleached - monitor reef_4.jpg 20.2% Partly bleached - monitor reef_5.jpg 34.2% Partly bleached - monitor reef_6.jpg 47.5% Severely bleached - ALERT Average bleaching: 20.7 % 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 1 6 reef images ready in coral_images 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 2 Thresholds: S < 60, V > 170 Image Bleached % Status reef_1.jpg 1.5% Healthy reef_2.jpg 3.4% Healthy reef_3.jpg 17.5% Partly bleached - monitor reef_4.jpg 20.2% Partly bleached - monitor reef_5.jpg 34.2% Partly bleached - monitor reef_6.jpg 47.5% Severely bleached - ALERT Average bleaching: 20.7 % 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 4 reef_6.jpg: 47.5% -> Severely bleached - ALERT reef_5.jpg: 34.2% -> Partly bleached - monitor reef_4.jpg: 20.2% -> Partly bleached - monitor reef_3.jpg: 17.5% -> Partly bleached - monitor Healthy reefs: ['reef_1.jpg', 'reef_2.jpg'] 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 3 Max saturation for white (0-255): 80 Min brightness for white (0-255): 150 Thresholds updated - run Analyse again. 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 2 Thresholds: S < 80, V > 150 Image Bleached % Status reef_1.jpg 2.0% Healthy reef_2.jpg 3.7% Healthy reef_3.jpg 18.0% Partly bleached - monitor reef_4.jpg 20.5% Partly bleached - monitor reef_5.jpg 34.4% Partly bleached - monitor reef_6.jpg 47.5% Severely bleached - ALERT Average bleaching: 21.0 % 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 3 Max saturation for white (0-255): 60 Min brightness for white (0-255): 170 Thresholds updated - run Analyse again. 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 5 Image number (1-6): 3 x (0-159): 40 y (0-119): 60 BGR = (183,59,202) HSV = (154,181,202) -> coloured / water 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 6 Charts saved: coral_results.png, coral_bars.png, coral_mask.png 1.Generate 2.Analyse 3.Thresholds 4.Alerts 5.Pixel Inspector 6.Charts 0.Exit Enter choice: 0 Save our reefs!
- Start
- Show menu and read choice
- Images exist? → No: generate images
- Read image, convert to HSV
- mask = (S < S_MAX) & (V > V_MIN)
- % = mask pixels / total
- % >= 40? → No: check >= 15
- Status and report
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Analyse before images | Images generated first | PASS |
| 2 | Analyse | 6 images with % | PASS |
| 3 | reef_6 | ALERT | PASS |
| 4 | reef_1 | Healthy | PASS |
| 5 | Thresholds 80/150 | More pixels detected | PASS |
| 6 | Pixel (40,60) | HSV values | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
os- file and folder operations,cv2- OpenCV image processing,numpy- fast arrays and maths,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
folder,results. - 8 functions are defined (lines 14โ93) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
generate() | 14โ27 | Generate | analyse(), main program |
bleach_mask(img) | 30โ32 | Bleach mask | analyse(), charts() |
status(p) | 35โ36 | Status | analyse() |
analyse() | 39โ50 | Analyse | alerts(), charts(), main program |
thresholds() | 53โ57 | Thresholds | main program |
alerts() | 60โ66 | Alerts | main program |
inspector() | 69โ74 | Inspector | main program |
charts() | 77โ93 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
School Canteen Review Sentiment Analyser (NLP)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
reviews | list | Canteen reviews |
positive / negative | sets | Sentiment lexicon including negated forms |
stop_words | set | Words removed |
TOPICS | dict | Keywords for complaint areas |
# =====================================================================
# 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")
=======================================================
CANTEEN REVIEW SENTIMENT ANALYSER (NLP)
=======================================================
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 1
[Positive] (score +2) The samosa is tasty and fresh!
[Negative] (score -2) Food was not good, very oily.
[Neutral ] (score +0) Canteen opens at 10 am.
[Positive] (score +3) Loved the healthy sprouts salad, great price.
[Negative] (score -3) Long queue and slow service, I am unhappy.
[Positive] (score +2) The staff is polite and the place is clean.
[Negative] (score -2) Juice was stale and too sweet.
[Positive] (score +2) Excellent idli, nice chutney.
[Neutral ] (score +0) Menu changes every Monday.
[Neutral ] (score +0) Not bad, but the plates were dirty.
Summary: {'Positive': 4, 'Negative': 3, 'Neutral': 3}
Satisfaction index: 40 % positive
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 2
Enter a sentence: The paneer roll was not fresh and the counter is dirty!
1. Lower case : the paneer roll was not fresh and the counter is dirty!
2. No punctuation : the paneer roll was not fresh and the counter is dirty
3. Tokens : ['the', 'paneer', 'roll', 'was', 'not', 'fresh', 'and', 'the', 'counter', 'is', 'dirty']
4. Stop words out : ['paneer', 'roll', 'not', 'fresh', 'counter', 'dirty']
5. Sentiment words : ['-fresh_not', '-dirty']
6. Score / label : -2 -> Negative
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 3
Vocabulary size: 37
10 1 #
bad 1 #
canteen 1 #
changes 1 #
chutney 1 #
clean 1 #
dirty 1 #
excellent 1 #
food 1 #
fresh 1 #
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 4
New review: Great pav bhaji, quick and polite service.
Review added. Total reviews: 11
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 1
[Positive] (score +2) The samosa is tasty and fresh!
[Negative] (score -2) Food was not good, very oily.
[Neutral ] (score +0) Canteen opens at 10 am.
[Positive] (score +3) Loved the healthy sprouts salad, great price.
[Negative] (score -3) Long queue and slow service, I am unhappy.
[Positive] (score +2) The staff is polite and the place is clean.
[Negative] (score -2) Juice was stale and too sweet.
[Positive] (score +2) Excellent idli, nice chutney.
[Neutral ] (score +0) Menu changes every Monday.
[Neutral ] (score +0) Not bad, but the plates were dirty.
[Positive] (score +3) Great pav bhaji, quick and polite service.
Summary: {'Positive': 5, 'Negative': 3, 'Neutral': 3}
Satisfaction index: 45 % positive
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 5
Food : mentioned in 3 reviews
Service : mentioned in 3 reviews
Hygiene : mentioned in 2 reviews
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 6
Charts saved: sentiment_pie.png, word_freq.png, review_scores.png
1.Analyse All 2.Step-by-step 3.Bag of Words 4.Add Review 5.Topics 6.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Show menu and read choice
- Clean text (lower, punctuation)
- Tokenise and remove stop words
- Word is 'not'? → No: look up word in lexicon
- Join with next word (negation)
- Score +1 / -1
- Label Positive / Negative / Neutral
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | 'The samosa is tasty and fresh!' | Positive (+2) | PASS |
| 2 | 'Food was not good, very oily.' | Negative | PASS |
| 3 | 'Canteen opens at 10 am.' | Neutral | PASS |
| 4 | 'Not bad, but plates were dirty' | Neutral (+1 -1) | PASS |
| 5 | Add review | List grows | PASS |
| 6 | Bag of words | Top words | PASS |
| 7 | Topics | Hygiene / service counts | PASS |
โ 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
- Imports (line 4):
string- ready-made sets of characters,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
reviews,positive,negative,stop_words,TOPICS. - 9 functions are defined (lines 18โ105) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
tokens_of(text) | 18โ20 | Tokens of | analyse_all(), step_by_step(), bag(), topics() |
score_of(tokens) | 23โ34 | Score of | analyse_all(), step_by_step(), charts() |
label(s) | 37โ38 | Label | analyse_all(), step_by_step(), charts() |
analyse_all() | 41โ49 | Analyse all | main program |
step_by_step() | 52โ61 | Step by step | main program |
bag() | 64โ74 | Bag | main program |
add() | 77โ79 | Add | main program |
topics() | 82โ85 | Topics | main program |
charts() | 88โ105 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CANTEEN REVIEW SENTIMENT ANALYSER (NLP) (+1 more lines)
- 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) - You type 2 at Enter choice:runs:
step_by_step() - 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) - You type 3 at Enter choice:runs:
bag()โtokens_of()ร10shows: Vocabulary size: 37 (+11 more lines) - You type 4 at Enter choice:runs:
add() - You type Great pav bhaji, quick and polite service. at New review:shows: Review added. Total reviews: 11 (+1 more lines)
- 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) - You type 5 at Enter choice:runs:
topics()โtokens_of()ร134shows: Food : mentioned in 3 reviews (+3 more lines) - 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) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
tokens_of() - lines 18โ20
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Delhi Air Quality (AQI) Statistical Analyser (SDG 11)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Day, AQI, Category, 7-day avg, Week |
bins / names | lists | CPCB AQI bands |
ADVICE | dict | Health advice per category |
# =====================================================================
# 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")
=======================================================
DELHI AQI STATISTICAL ANALYSER (SDG 11)
=======================================================
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 1
Day AQI Category 7-day avg
1 286 Poor NaN
2 301 Very Poor NaN
3 322 Very Poor NaN
4 356 Very Poor NaN
5 389 Very Poor NaN
6 412 Severe NaN
7 438 Severe 357.7
8 402 Severe 374.3
9 371 Very Poor 384.3
10 344 Very Poor 387.4
11 318 Very Poor 382.0
12 296 Poor 368.7
13 275 Poor 349.1
14 301 Very Poor 329.6
15 333 Very Poor 319.7
16 365 Very Poor 318.9
17 398 Very Poor 326.6
18 421 Severe 341.3
19 387 Very Poor 354.3
20 352 Very Poor 365.3
21 330 Very Poor 369.4
22 309 Very Poor 366.0
23 287 Poor 354.9
24 262 Poor 335.4
25 248 Poor 310.7
26 266 Poor 293.4
27 293 Poor 285.0
28 315 Very Poor 282.9
29 342 Very Poor 287.6
30 301 Very Poor 289.6
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 2
Mean : 334.0
Median : 326.0
Mode : [301]
Std dev : 50.96
Range : 190 (248 to 438)
Quartiles Q1, Q2, Q3: [297.25, 326.0, 369.5]
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 3
Category
Good 0
Satisfactory 0
Moderate 0
Poor 8
Very Poor 18
Severe 4
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 4
mean min max
Week
1 357.7 286 438
2 329.6 275 402
3 369.4 330 421
4 282.9 248 315
5 321.5 301 342
Worst week: 3
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 5
Day (1-30): 7
Day 7: AQI 438 -> Severe. Advice: Health emergency - avoid going out, schools may close.
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 5
Day (1-30): 40
Day must be 1-30.
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 6
5 worst days:
Day AQI Category
7 438 Severe
18 421 Severe
6 412 Severe
8 402 Severe
17 398 Very Poor
Days to avoid outdoor activity (AQI > 300): 22 days -> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 28, 29, 30]
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 7
Charts saved: aqi_trend.png, aqi_category.png, aqi_hist.png
1.Data 2.Statistics 3.Categories 4.Weekly 5.Advisory 6.Worst Days 7.Charts 0.Exit
Enter choice: 0
Breathe clean!
- Start
- Create DataFrame and categories
- Show menu and read choice
- Valid option? → No: 'Invalid choice'
- Calculate statistics / filter
- Show result or chart
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Statistics | Mean 334.0, median 326, mode 301 | PASS |
| 2 | Category count | Poor / Very Poor / Severe | PASS |
| 3 | Weekly | 5 weeks | PASS |
| 4 | Advisory day 7 | Severe advice | PASS |
| 5 | Advisory day 40 | 'Day must be 1-30' | PASS |
| 6 | Worst days | Day 7 = 438 | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 5):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
aqi,df,bins,names,ADVICE. - 7 functions are defined (lines 20โ72) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
show() | 20โ21 | Show | main program |
stats() | 24โ30 | Stats | main program |
categories() | 33โ34 | Categories | main program |
weekly() | 37โ40 | Weekly | main program |
advisory() | 43โ49 | Advisory | main program |
worst() | 52โ55 | Worst | main program |
charts() | 58โ72 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: DELHI AQI STATISTICAL ANALYSER (SDG 11) (+1 more lines)
- You type 1 at Enter choice:runs:
show()shows: Day AQI Category 7-day avg (+31 more lines) - You type 2 at Enter choice:runs:
stats()shows: Mean : 334.0 (+6 more lines) - You type 3 at Enter choice:runs:
categories()shows: Category (+7 more lines) - You type 4 at Enter choice:runs:
weekly()shows: mean min max (+8 more lines) - You type 5 at Enter choice:runs:
advisory() - 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)
- You type 5 at Enter choice:runs:
advisory() - You type 40 at Day (1-30):shows: Day must be 1-30. (+1 more lines)
- You type 6 at Enter choice:runs:
worst()shows: 5 worst days: (+8 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Breathe clean!
โค Inside each function - line by line
show() - lines 20โ21
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Study Hours vs Marks - Regression Predictor
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
hours, marks | NumPy arrays | Training data |
m, c | float | Slope and intercept |
pred | array | m x hours + c |
mse | float | Mean squared error |
# =====================================================================
# 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")
================================================== STUDY HOURS vs MARKS PREDICTOR ================================================== 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 3 Train the model first (option 2). 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 2 Model learnt : marks = 7.91 x hours + 30.59 Meaning : every extra hour adds about 7.9 marks 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 1 No Hours Marks 1 1.0 38 2 1.5 42 3 2.0 45 4 2.5 52 5 3.0 55 6 3.5 58 7 4.0 63 8 4.5 66 9 5.5 75 10 6.0 78 11 7.0 86 12 8.0 93 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 3 Hours Actual Predicted Error 1.0 38 38.5 -0.5 1.5 42 42.5 -0.5 2.0 45 46.4 -1.4 2.5 52 50.4 1.6 3.0 55 54.3 0.7 3.5 58 58.3 -0.3 4.0 63 62.3 0.7 4.5 66 66.2 -0.2 5.5 75 74.1 0.9 6.0 78 78.1 -0.1 7.0 86 86.0 0.0 8.0 93 93.9 -0.9 MSE 0.655 | RMSE 0.809 | r 0.9988 | R^2 0.9977 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 4 Trained on 9 students, tested on 3 hours 2.0: actual 45, predicted 46.6 hours 4.0: actual 63, predicted 62.3 hours 7.0: actual 86, predicted 85.9 Test RMSE: 1.023 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 5 Study hours of a new student: 5 Predicted marks: 70.2 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 5 Study hours of a new student: 12 Predicted marks: 100 (capped at 100) 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 5 Study hours of a new student: -2 Hours must be 0-16. 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 6 Target marks: 90 Study about 7.5 hours per day to reach 90 marks (if the trend holds). 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 7 Charts saved: regression_line.png, residuals.png, train_test.png 1.Data 2.Train 3.Evaluate 4.Train-Test 5.Predict 6.Hours for Target 7.Charts 0.Exit Enter choice: 0 Study smart!
- Start
- Show menu and read choice
- Model trained? → No: train with polyfit
- pred = m x h + c
- Error = actual - predicted
- Show metrics / prediction
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Train | marks = 7.91 x hours + 30.59 | PASS |
| 2 | Evaluate | r ~ 0.99 | PASS |
| 3 | Train-test | Test RMSE small | PASS |
| 4 | Predict 5 h | ~ 70 | PASS |
| 5 | Predict 12 h | Capped at 100 | PASS |
| 6 | Target 90 | Hours needed | PASS |
| 7 | Predict -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
- Imports (line 4):
numpy- fast arrays and maths,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
hours,marks,model. - 7 functions are defined (lines 12โ78) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
train() | 12โ16 | Train | main program |
show() | 19โ22 | Show | main program |
evaluate() | 25โ33 | Evaluate | main program |
train_test() | 36โ45 | Train test | main program |
predict() | 48โ54 | Predict | main program |
hours_for() | 57โ60 | Hours for | main program |
charts() | 63โ78 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: STUDY HOURS vs MARKS PREDICTOR (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 2 at Enter choice:runs:
train()shows: Model learnt : marks = 7.91 x hours + 30.59 (+2 more lines) - You type 1 at Enter choice:runs:
show()shows: No Hours Marks (+13 more lines) - You type 3 at Enter choice:runs:
evaluate()shows: Hours Actual Predicted Error (+14 more lines) - You type 4 at Enter choice:runs:
train_test()shows: Trained on 9 students, tested on 3 (+5 more lines) - You type 5 at Enter choice:runs:
predict() - You type 5 at Study hours of a new student:shows: Predicted marks: 70.2 (+1 more lines)
- You type 5 at Enter choice:runs:
predict() - You type 12 at Study hours of a new student:shows: Predicted marks: 100 (capped at 100) (+1 more lines)
- You type 5 at Enter choice:runs:
predict() - You type -2 at Study hours of a new student:shows: Hours must be 0-16. (+1 more lines)
- You type 6 at Enter choice:runs:
hours_for() - 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)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Study smart!
โค Inside each function - line by line
train() - lines 12โ16
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Image Filter Studio - Convolution in Action (Computer Vision)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
img / gray | NumPy arrays | Colour (BGR) and grayscale images |
kernels | dict | Name -> 3x3 kernel |
outputs | dict | Filtered images |
grid | 5x5 array | Small matrix for manual convolution |
# =====================================================================
# 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")
================================================== IMAGE FILTER STUDIO (Computer Vision) ================================================== 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 1 Colour image shape (rows, cols, channels): (300, 400, 3) Total pixels: 120000 | data type: uint8 Pixel at (50, 50) BGR: [220 192 132] | gray: 177 Gray min/max/mean: 79 / 221 / 154.2 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 2 Filter Mean Std Bright px Original 154.2 30.8 2452 Blur 154.2 30.5 2345 Sharpen 154.1 34.5 3966 Edge 3.4 20.5 420 Emboss 152.9 36.5 3487 Sobel-X 1.7 16.5 367 Edge / Sobel give dark images with bright edges; Blur reduces std (smoother). 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 3 Input 5x5 grid (dark | bright boundary): [[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]] Edge kernel: [[-1 -1 -1] [-1 8 -1] [-1 -1 -1]] Patch at centre: [[10 10 80] [10 10 80] [10 10 80]] Centre output = sum(patch x kernel) = -210 Full 3x3 output (valid convolution): [[ 0 -210 210] [ 0 -210 210] [ 0 -210 210]] Large values appear exactly at the boundary column - that is an EDGE! 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 4 Enter 9 kernel numbers separated by space: 0.11 0.11 0.11 0.11 0.11 0.11 0.11 0.11 0.11 Your kernel: [[0.11 0.11 0.11] [0.11 0.11 0.11] [0.11 0.11 0.11]] Output mean 152.7 std 30.1 (original std 30.8) 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 4 Enter 9 kernel numbers separated by space: a b c Enter 9 numbers only. 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 5 Resize percent: 50 Original: (300, 400, 3) | resized: (150, 200, 3) | centre crop: (150, 200, 3) 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 6 Charts saved: filters.png, kernel_demo.png, histograms.png 1.Info 2.Apply Filters 3.Manual Convolution 4.Custom Kernel 5.Resize/Crop 6.Charts 0.Exit Enter choice: 0 Bye!
- Start
- Read flower.jpg
- Image found? → No: show error and stop
- Show menu and read choice
- Select kernel
- cv2.filter2D(gray, -1, kernel)
- Show statistics / images
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Image info | Shape (rows, cols, 3) | PASS |
| 2 | Apply filters | 5 outputs with statistics | PASS |
| 3 | Manual convolution | Centre value calculated | PASS |
| 4 | Custom kernel all 1/9 | Same as blur | PASS |
| 5 | Kernel with letters | 'Enter 9 numbers' | PASS |
| 6 | Resize 50 % | Half shape | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
cv2- OpenCV image processing,numpy- fast arrays and maths,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
img,gray,kernels,grid. - 6 functions are defined (lines 18โ92) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
info() | 18โ22 | Info | main program |
apply_all() | 25โ31 | Apply all | main program |
manual() | 34โ47 | Manual | main program |
custom() | 50โ59 | Custom | main program |
resize_crop() | 62โ67 | Resize crop | main program |
charts() | 70โ92 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
School Helpdesk Chatbot (Script Bot)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
intents | dict | name -> (keywords, reply) |
hits | dict | Times each intent was used |
unanswered.txt | text file | Questions bot could not answer |
log | list | Conversation lines |
# =====================================================================
# 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")
=======================================================
KV HELPDESK CHATBOT (Script Bot)
=======================================================
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 1
Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'bye' to end.
You: Hi
Bot: Hello! I am KV Helpdesk Bot. How can I help you?
You: What are the school timings?
Bot: School timings: 7:50 AM to 1:50 PM (Mon-Sat).
You: Is there a bus facility near Rohini?
Bot: School has no own bus; approved private vans are listed at the office.
You: When is the library open?
Bot: Library is open 8:00 AM to 1:30 PM. Issue period: 14 days.
You: Who won the IPL?
Bot: Sorry, I can answer only school-related questions. I have noted your query for the office.
You: How do I pay the fees?
Bot: Fees are paid online through the KVS UBI fee portal every quarter.
You: Is the canteen open on Saturday?
Bot: Sorry, I can answer only school-related questions. I have noted your query for the office.
You: bye
Bot: Thank you! Have a great day.
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 3
Admin password: abc
Access denied.
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 3
Admin password: kv@123
Intent name: canteen
Keywords (comma separated): canteen, food, lunch
Reply: Canteen is open 9:30 AM to 12:30 PM on all working days.
Intent 'canteen' added. The bot now knows 8 intents.
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 1
Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'bye' to end.
You: Is the canteen open on Saturday?
Bot: Canteen is open 9:30 AM to 12:30 PM on all working days.
You: bye
Bot: Thank you! Have a great day.
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 2
greet keys=['hi', 'hello', 'namaste', 'hey']
-> Hello! I am KV Helpdesk Bot. How can I help you?
timing keys=['timing', 'time', 'start', 'close']
-> School timings: 7:50 AM to 1:50 PM (Mon-Sat).
fees keys=['fee', 'pay', 'payment']
-> Fees are paid online through the KVS UBI fee portal every quarter.
library keys=['library', 'book']
-> Library is open 8:00 AM to 1:30 PM. Issue period: 14 days.
transport keys=['bus', 'transport', 'van']
-> School has no own bus; approved private vans are listed at the office.
admission keys=['admission', 'admit', 'seat']
-> Admissions follow KVS guidelines; Class 1 registration is online.
exam keys=['exam', 'test', 'result']
-> Half-yearly exams in September, session-ending exams in February/March.
canteen keys=['canteen', 'food', 'lunch']
-> Canteen is open 9:30 AM to 12:30 PM on all working days.
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 4
1. Who won the IPL?
2. Is the canteen open on Saturday?
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 5
Messages: 8 | Answered: 6 | Unanswered: 2
Answer rate: 75.0 %
Intent usage:
greet # 1
timing # 1
fees # 1
library # 1
transport # 1
canteen # 1
Chat log (last 3):
[10:05] How do I pay the fees?
[10:06] Is the canteen open on Saturday?
[10:07] Is the canteen open on Saturday?
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 6
Feature Script bot Smart bot
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
1.Chat 2.Intents 3.Add Intent 4.Unanswered 5.Statistics 6.Script vs Smart 0.Exit
Enter choice: 0
Goodbye!
- Start
- Show menu
- Read user message
- Message is 'bye'? → No: search intents
- Keyword matched? → No: save to unanswered.txt
- Print reply
- Update statistics
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | 'Hi' | Greeting | PASS |
| 2 | 'What are the school timings?' | Timing reply | PASS |
| 3 | 'bus near Rohini' | Transport reply | PASS |
| 4 | 'Who won the IPL?' | Sorry + saved | PASS |
| 5 | Add intent 'canteen' | New reply works | PASS |
| 6 | Wrong admin password | Denied | PASS |
| 7 | Statistics | Answered 5 / 6 | PASS |
โ 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
- Imports (line 4):
os- file and folder operations,datetime- dates and times are loaded. - Global variables / constants are created:
intents,hits,log,stats. - 7 functions are defined (lines 22โ93) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
reply_to(msg) | 22โ28 | Reply to | chat() |
chat() | 31โ47 | Chat | main program |
show_intents() | 50โ52 | Show intents | main program |
add_intent() | 55โ64 | Add intent | main program |
unanswered() | 67โ73 | Unanswered | main program |
statistics() | 76โ86 | Statistics | main program |
compare() | 89โ93 | Compare | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: KV HELPDESK CHATBOT (Script Bot) (+1 more lines)
- You type 1 at Enter choice:runs:
chat()shows: Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'by - You type Hi at You:runs:
reply_to()shows: Bot: Hello! I am KV Helpdesk Bot. How can I help you? - 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). - 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. - 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. - 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 - 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. - 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 - You type bye at You:shows: Bot: Thank you! Have a great day. (+1 more lines)
- You type 3 at Enter choice:runs:
add_intent() - You type abc at Admin password:shows: Access denied. (+1 more lines)
- You type 3 at Enter choice:runs:
add_intent() - You type kv@123 at Admin password:
- You type canteen at Intent name:
- You type canteen, food, lunch at Keywords (comma separated):
- 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)
- You type 1 at Enter choice:runs:
chat()shows: Bot: Namaste! Ask me about timings, fees, library, transport, admission or exams. Type 'by - 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. - You type bye at You:shows: Bot: Thank you! Have a great day. (+1 more lines)
- You type 2 at Enter choice:runs:
show_intents()shows: greet keys=['hi', 'hello', 'namaste', 'hey'] (+16 more lines) - You type 4 at Enter choice:runs:
unanswered()shows: 1. Who won the IPL? (+2 more lines) - You type 5 at Enter choice:runs:
statistics()shows: Messages: 8 | Answered: 6 | Unanswered: 2 (+13 more lines) - You type 6 at Enter choice:runs:
compare()shows: Feature Script bot Smart bot (+5 more lines) - You type 0 at Enter choice:shows: Goodbye!
โค Inside each function - line by line
reply_to() - lines 22โ28
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Rainfall and Temperature Explorer (SDG 13)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Month, Rainfall_mm, Avg_Temp_C |
SEASON | dict | Month -> season |
monsoon | float | Jun-Sep rainfall |
# =====================================================================
# 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")
=======================================================
RAINFALL & TEMPERATURE EXPLORER (SDG 13)
=======================================================
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 1
Month Rainfall_mm Avg_Temp_C Season
Jan 19 14 Winter
Feb 20 17 Winter
Mar 15 23 Summer
Apr 10 29 Summer
May 25 33 Summer
Jun 70 34 Monsoon
Jul 210 31 Monsoon
Aug 233 30 Monsoon
Sep 124 29 Monsoon
Oct 15 26 Post-monsoon
Nov 6 20 Post-monsoon
Dec 9 15 Winter
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 2
Rainfall_mm Avg_Temp_C
count 12.0 12.0
mean 63.0 25.1
std 81.5 7.1
min 6.0 14.0
25% 13.8 19.2
50% 19.5 27.5
75% 83.5 30.2
max 233.0 34.0
Annual rainfall: 756 mm
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 3
Wettest month : Aug 233 mm
Driest month : Nov 6 mm
Hottest month : Jun 34 C
Coolest month : Jan 14 C
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 4
Rain Temp Share_%
Season
Monsoon 637 31.0 84.3
Summer 50 28.3 6.6
Winter 48 15.3 6.3
Post-monsoon 21 23.0 2.8
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 5
Correlation (rain vs temp): 0.507
Interpretation: positive - rain falls in the warm months
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 6
Change in monsoon rainfall (%): -20
Annual rainfall: 756 mm -> 629 mm
Status: DEFICIENT year (drought risk)
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 7
Charts saved: rain_temp.png, monthly_rain_pie.png, season_bar.png
1.Data 2.Statistics 3.Extremes 4.Seasons 5.Correlation 6.What-if 7.Charts 0.Exit
Enter choice: 0
Act on climate!
- Start
- read_csv('rainfall.csv')
- Show menu and read choice
- Valid option? → No: 'Invalid choice'
- Compute statistics / groupby
- Show result / chart
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Show data | 12 months | PASS |
| 2 | Extremes | Wettest Jul/Aug | PASS |
| 3 | Season summary | Monsoon highest | PASS |
| 4 | Correlation | Value -1 to 1 | PASS |
| 5 | What-if -20 % | New annual total | PASS |
| 6 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
df,SEASON. - 7 functions are defined (lines 13โ60) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
show() | 13โ14 | Show | main program |
stats() | 17โ19 | Stats | main program |
extremes() | 22โ26 | Extremes | main program |
seasons() | 29โ32 | Seasons | main program |
correlation() | 35โ38 | Correlation | main program |
what_if() | 41โ45 | What if | main program |
charts() | 48โ60 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: RAINFALL & TEMPERATURE EXPLORER (SDG 13) (+1 more lines)
- You type 1 at Enter choice:runs:
show()shows: Month Rainfall_mm Avg_Temp_C Season (+13 more lines) - You type 2 at Enter choice:runs:
stats()shows: Rainfall_mm Avg_Temp_C (+10 more lines) - You type 3 at Enter choice:runs:
extremes()shows: Wettest month : Aug 233 mm (+4 more lines) - You type 4 at Enter choice:runs:
seasons()shows: Rain Temp Share_% (+6 more lines) - You type 5 at Enter choice:runs:
correlation()shows: Correlation (rain vs temp): 0.507 (+2 more lines) - You type 6 at Enter choice:runs:
what_if() - You type -20 at Change in monsoon rainfall (%):shows: Annual rainfall: 756 mm -> 629 mm (+2 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Act on climate!
โค Inside each function - line by line
show() - lines 13โ14
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Smart Waste Bin Fill-Level Monitor (SDG 11)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
bins | DataFrame | Bin, Zone, Fill, Hours_since_pickup |
Rate | column | Fill % per hour |
Status | column | pd.cut OK / HALF / FULL |
THRESHOLD | int | 80 % pickup level |
# =====================================================================
# 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")
=======================================================
SMART BIN MONITOR (SDG 11)
=======================================================
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 1
Bin Zone Fill Hours_since_pickup Status Rate
B01 A 92 30 FULL 3.07
B02 A 35 8 OK 4.38
B03 A 81 26 FULL 3.12
B04 B 67 20 HALF 3.35
B05 B 88 28 FULL 3.14
B06 B 22 6 OK 3.67
B07 C 95 34 FULL 2.79
B08 C 54 18 HALF 3.00
B09 C 40 12 HALF 3.33
B10 C 79 24 HALF 3.29
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 2
ALERT: bins to empty today (fill >= 80 %):
Bin Zone Fill
B07 C 95
B01 A 92
B05 B 88
B03 A 81
Pickup route: Depot -> B07 -> B01 -> B05 -> B03 -> Depot
Trips saved today: 6 of 10 (60 % fuel saving)
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 3
Bins Avg_Fill Full
Zone
A 3 69.3 2
B 3 59.0 1
C 4 67.0 1
Most loaded zone: A
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 4
Bin Fill Rate_%/h Hours_to_full
B07 95 2.79 1.8
B01 92 3.07 2.6
B05 88 3.14 3.8
B03 81 3.12 6.1
B10 79 3.29 6.4
B04 67 3.35 9.9
B02 35 4.38 14.8
B08 54 3.00 15.3
B09 40 3.33 18.0
B06 22 3.67 21.3
Bins that will be full within 6 hours: ['B01', 'B05', 'B07']
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 5
Bin id: B02
New fill %: 85
B02 updated -> FULL
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 5
Bin id: B03
New fill %: 120
Fill must be 0-100.
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 2
ALERT: bins to empty today (fill >= 80 %):
Bin Zone Fill
B07 C 95
B01 A 92
B05 B 88
B02 A 85
B03 A 81
Pickup route: Depot -> B07 -> B01 -> B05 -> B02 -> B03 -> Depot
Trips saved today: 5 of 10 (50 % fuel saving)
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 6
Bin emptied: B07
B07 emptied. Status OK.
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 1
Bin Zone Fill Hours_since_pickup Status Rate
B01 A 92 30 FULL 3.07
B02 A 85 8 FULL 10.62
B03 A 81 26 FULL 3.12
B04 B 67 20 HALF 3.35
B05 B 88 28 FULL 3.14
B06 B 22 6 OK 3.67
B07 C 0 0 OK 0.00
B08 C 54 18 HALF 3.00
B09 C 40 12 HALF 3.33
B10 C 79 24 HALF 3.29
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 7
Charts saved: bin_levels.png, zone_fill.png, fill_forecast.png
1.Status 2.Pickup 3.Zones 4.Predict 5.Update Sensor 6.Empty Bin 7.Charts 0.Exit
Enter choice: 0
Clean city, green city!
- Start
- Create bin DataFrame
- Show menu and read choice
- Choice is Update? → No: run report
- Read bin and fill
- 0 <= fill <= 100? → No: error
- Update and recompute status
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Status | 10 bins | PASS |
| 2 | Pickup | B07, B01, B05, B03 route | PASS |
| 3 | Zone summary | Zone A highest | PASS |
| 4 | Predict | Hours to full | PASS |
| 5 | Update B02 = 85 | B02 becomes FULL | PASS |
| 6 | Update 120 | 'Fill must be 0-100' | PASS |
| 7 | Empty B07 | Fill 0, OK | PASS |
โ 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
- Imports (line 4):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
THRESHOLD,bins. - 8 functions are defined (lines 15โ79) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
refresh() | 15โ17 | Refresh | update(), empty(), main program |
status() | 20โ21 | Status | main program |
pickup() | 24โ29 | Pickup | main program |
zones() | 32โ35 | Zones | main program |
predict() | 38โ42 | Predict | main program |
update() | 45โ56 | Update | main program |
empty() | 59โ63 | Empty | main program |
charts() | 66โ79 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsruns:
refresh()shows: SMART BIN MONITOR (SDG 11) (+1 more lines) - You type 1 at Enter choice:runs:
status()shows: Bin Zone Fill Hours_since_pickup Status Rate (+11 more lines) - You type 2 at Enter choice:runs:
pickup()shows: ALERT: bins to empty today (fill >= 80 %): (+8 more lines) - You type 3 at Enter choice:runs:
zones()shows: Bins Avg_Fill Full (+6 more lines) - You type 4 at Enter choice:runs:
predict()shows: Bin Fill Rate_%/h Hours_to_full (+12 more lines) - You type 5 at Enter choice:runs:
update() - You type B02 at Bin id:
- You type 85 at New fill %:runs:
refresh()shows: B02 updated -> FULL (+1 more lines) - You type 5 at Enter choice:runs:
update() - You type B03 at Bin id:
- You type 120 at New fill %:shows: Fill must be 0-100. (+1 more lines)
- You type 2 at Enter choice:runs:
pickup()shows: ALERT: bins to empty today (fill >= 80 %): (+9 more lines) - You type 6 at Enter choice:runs:
empty() - You type B07 at Bin emptied:runs:
refresh()shows: B07 emptied. Status OK. (+1 more lines) - You type 1 at Enter choice:runs:
status()shows: Bin Zone Fill Hours_since_pickup Status Rate (+11 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Clean city, green city!
โค Inside each function - line by line
refresh() - lines 15โ17
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Crop Yield Data Insights (SDG 2)
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
๐ฏ Objectives
- Aggregate data using groupby with mean and max
- Calculate percentage growth between years
- Present insights using a grouped bar chart
๐ Data dictionary
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | State, Crop, Year, Yield |
avg | DataFrame | State x Crop average |
growth | DataFrame | % growth |
fc | DataFrame | 2025 forecast |
# =====================================================================
# 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")
=======================================================
CROP YIELD DATA INSIGHTS (SDG 2)
=======================================================
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 1
State Crop Year Yield
Punjab Wheat 2022 48.2
Punjab Wheat 2023 49.0
Punjab Wheat 2024 50.1
Punjab Rice 2022 41.5
Punjab Rice 2023 42.3
Punjab Rice 2024 43.0
Haryana Wheat 2022 46.0
Haryana Wheat 2023 46.8
Haryana Wheat 2024 47.9
Haryana Rice 2022 32.4
Haryana Rice 2023 33.0
Haryana Rice 2024 34.1
UP Wheat 2022 34.1
UP Wheat 2023 35.0
UP Wheat 2024 35.6
UP Rice 2022 26.2
UP Rice 2023 27.0
UP Rice 2024 27.4
MP Wheat 2022 33.0
MP Wheat 2023 34.2
MP Wheat 2024 35.5
MP Rice 2022 22.8
MP Rice 2023 23.5
MP Rice 2024 24.6
Bihar Wheat 2022 28.9
Bihar Wheat 2023 29.4
Bihar Wheat 2024 30.2
Bihar Rice 2022 24.1
Bihar Rice 2023 24.6
Bihar Rice 2024 25.0
Records: 30
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 2
Average yield by crop:
Crop
Rice 30.10
Wheat 38.93
Average yield by state:
Crop Rice Wheat
State
Bihar 24.57 29.50
Haryana 33.17 46.90
MP 23.63 34.23
Punjab 42.27 49.10
UP 26.87 34.90
Best state - Wheat: Punjab | Rice: Punjab
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 3
Growth 2022 -> 2024 (%):
Crop Rice Wheat
State
Bihar 3.73 4.50
Haryana 5.25 4.13
MP 7.89 7.58
Punjab 3.61 3.94
UP 4.58 4.40
Fastest growing - Wheat: MP | Rice: MP
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 4
Year 2022 2023 2024 Avg_increase Forecast_2025
State Crop
Bihar Rice 24.1 24.6 25.0 0.45 25.4
Wheat 28.9 29.4 30.2 0.65 30.8
Haryana Rice 32.4 33.0 34.1 0.85 35.0
Wheat 46.0 46.8 47.9 0.95 48.8
MP Rice 22.8 23.5 24.6 0.90 25.5
Wheat 33.0 34.2 35.5 1.25 36.8
Punjab Rice 41.5 42.3 43.0 0.75 43.8
Wheat 48.2 49.0 50.1 0.95 51.1
UP Rice 26.2 27.0 27.4 0.60 28.0
Wheat 34.1 35.0 35.6 0.75 36.4
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 5
State: Bihar
Crop Rice Wheat
Year
2022 24.1 28.9
2023 24.6 29.4
2024 25.0 30.2
Wheat: below the 5-state average by 9.43 q/ha
Rice: below the 5-state average by 5.53 q/ha
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 5
State: Goa
State not found in data.
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 6
States above the average:
Wheat: ['Haryana', 'Punjab'] (average 38.93)
Rice: ['Haryana', 'Punjab'] (average 30.10)
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 7
Charts saved: crop_yield.png, yield_trend.png, growth_heatmap.png
1.Data 2.Averages 3.Growth 4.Forecast 5.State Report 6.Above Average 7.Charts 0.Exit
Enter choice: 0
Jai Kisan!
- Start
- Build DataFrame from dictionary
- Show menu and read choice
- Valid option? → No: 'Invalid choice'
- groupby / unstack / compute
- Show result / chart
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Data | 30 records | PASS |
| 2 | Averages | Punjab best | PASS |
| 3 | Growth | MP fastest wheat | PASS |
| 4 | Forecast | 2025 values | PASS |
| 5 | State 'Bihar' | Bihar rows | PASS |
| 6 | State 'Goa' | Not found | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
data,rows,df,avg,first,last,growth. - 7 functions are defined (lines 24โ82) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
show() | 24โ26 | Show | main program |
averages() | 29โ32 | Averages | main program |
growth_rep() | 35โ37 | Growth rep | main program |
forecast() | 40โ44 | Forecast | main program |
state_report() | 47โ57 | State report | main program |
above() | 60โ64 | Above | main program |
charts() | 67โ82 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CROP YIELD DATA INSIGHTS (SDG 2) (+1 more lines)
- You type 1 at Enter choice:runs:
show()shows: State Crop Year Yield (+32 more lines) - You type 2 at Enter choice:runs:
averages()shows: Average yield by crop: (+13 more lines) - You type 3 at Enter choice:runs:
growth_rep()shows: Growth 2022 -> 2024 (%): (+9 more lines) - You type 4 at Enter choice:runs:
forecast()shows: Year 2022 2023 2024 Avg_increase Forecast_2025 (+12 more lines) - You type 5 at Enter choice:runs:
state_report() - You type Bihar at State:shows: Crop Rice Wheat (+7 more lines)
- You type 5 at Enter choice:runs:
state_report() - You type Goa at State:shows: State not found in data. (+1 more lines)
- You type 6 at Enter choice:runs:
above()shows: States above the average: (+3 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Jai Kisan!
โค Inside each function - line by line
show() - lines 24โ26
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Rainfall Data Analysis and Visualisation (rainfall.csv)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Month, Rainfall_mm, Avg_Temp_C, Season |
r | Series | Rainfall column |
season_of | dict | Month -> season |
q1, q3, iqr | float | Quartiles and inter-quartile range |
# =====================================================================
# 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"))()
=======================================================
RAINFALL DATA ANALYSIS (SDG 13)
=======================================================
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 1
Month Rainfall_mm Avg_Temp_C Season
Jan 19 14 Winter
Feb 20 17 Winter
Mar 15 23 Summer
Apr 10 29 Summer
May 25 33 Summer
Jun 70 34 Monsoon
Jul 210 31 Monsoon
Aug 233 30 Monsoon
Sep 124 29 Monsoon
Oct 15 26 Post-monsoon
Nov 6 20 Post-monsoon
Dec 9 15 Winter
Months loaded: 12 | Total: 756 mm
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 2
Mean : 63.0
Median : 19.5
Mode : 15 (statistics.mode)
Skew : 1.487 -> right-skewed (monsoon months pull the mean up)
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 3
Variance (sample) : 6644.55
Variance (population): 6090.83
Std deviation : 81.51
Range : 227
Q1 = 13.75, Q3 = 83.5, IQR = 69.75
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 4
Total Mean Temp Share_%
Season
Monsoon 637 159.2 31.0 84.3
Summer 50 16.7 28.3 6.6
Winter 48 16.0 15.3 6.3
Post-monsoon 21 10.5 23.0 2.8
Months above average: ['Jun', 'Jul', 'Aug', 'Sep']
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 5
Normal range: -90.88 to 188.12 mm
Outlier months:
Month Rainfall_mm
Jul 210
Aug 233
These are monsoon months - outliers here are real, not errors.
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 6
Month Rain Z-score MinMax
Jan 19 -0.54 0.057
Feb 20 -0.53 0.062
Mar 15 -0.59 0.040
Apr 10 -0.65 0.018
May 25 -0.47 0.084
Jun 70 0.09 0.282
Jul 210 1.80 0.899
Aug 233 2.09 1.000
Sep 124 0.75 0.520
Oct 15 -0.59 0.040
Nov 6 -0.70 0.000
Dec 9 -0.66 0.013
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 7
Charts saved: rain_dashboard.png, rain_box.png, rain_cumulative.png
1.View 2.Central Tendency 3.Dispersion 4.Seasons 5.Outliers 6.Z-score 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Read rainfall.csv
- Show menu and read choice
- Valid option? → No: 'Invalid choice'
- Compute statistics
- Show result / charts
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | View | 12 rows | PASS |
| 2 | Central tendency | Mean 63.0, median 19.5 | PASS |
| 3 | Dispersion | Std 81.5 | PASS |
| 4 | Season | Monsoon 637 mm | PASS |
| 5 | Outliers | Jul, Aug, Sep flagged | PASS |
| 6 | Z-score | Aug highest | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 5):
pandas- data tables (Series & DataFrame),statistics- mean, median, mode functions,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
df,r,season_of,iqr. - 7 functions are defined (lines 18โ74) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
view() | 18โ20 | View | main program (menu) |
central() | 23โ27 | Central | main program (menu) |
dispersion() | 30โ35 | Dispersion | main program (menu) |
seasons() | 38โ42 | Seasons | main program (menu) |
outliers() | 45โ50 | Outliers | main program (menu) |
zscore() | 53โ56 | Zscore | main program (menu) |
charts() | 59โ74 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: RAINFALL DATA ANALYSIS (SDG 13) (+1 more lines)
- You type 1 at Enter choice:runs:
view()shows: Month Rainfall_mm Avg_Temp_C Season (+14 more lines) - You type 2 at Enter choice:runs:
central()shows: Mean : 63.0 (+4 more lines) - You type 3 at Enter choice:runs:
dispersion()shows: Variance (sample) : 6644.55 (+5 more lines) - You type 4 at Enter choice:runs:
seasons()shows: Total Mean Temp Share_% (+7 more lines) - You type 5 at Enter choice:runs:
outliers()shows: Normal range: -90.88 to 188.12 mm (+6 more lines) - You type 6 at Enter choice:runs:
zscore()shows: Month Rain Z-score MinMax (+13 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
view() - lines 18โ20
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
House Price Predictor - Linear Regression (SDG 11)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Area, Bedrooms, Age, Metro_km, Price_lakh |
FEAT | list | Feature names |
model | LinearRegression | Trained model |
X_train ... y_test | DataFrames | Split data |
# =====================================================================
# 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")
=======================================================
HOUSE PRICE PREDICTOR (Linear Regression)
=======================================================
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 1
Area Bedrooms Age Metro_km Price_lakh
0 700 1 19 0.3 43.8
1 692 1 11 5.1 39.1
2 1695 3 17 2.9 105.5
3 1248 2 6 0.9 86.8
4 1385 3 0 4.5 92.8
Area Bedrooms Age Metro_km Price_lakh
count 60.0 60.0 60.0 60.0 60.0
mean 1349.9 2.5 10.7 2.8 88.7
std 442.8 1.1 8.0 1.8 32.5
min 543.0 1.0 0.0 0.3 26.4
25% 1006.2 2.0 4.0 1.1 64.4
50% 1357.5 2.5 9.0 2.6 90.4
75% 1740.8 3.0 18.0 4.5 119.6
max 1991.0 4.0 24.0 6.0 138.4
Correlation with price:
Area 0.983
Bedrooms 0.953
Age -0.268
Metro_km -0.213
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 2
Model trained on 45 flats; testing on 15
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 3
Area : +0.063 lakh per unit
Bedrooms : +3.202 lakh per unit
Age : -0.475 lakh per unit
Metro_km : -2.077 lakh per unit
Intercept: 6.198
Price = 6.20 + 0.063*Area + 3.20*Bed -0.48*Age -2.08*Metro
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 4
Set MAE RMSE R2
Train 1.91 2.44 0.994
Test 2.04 2.49 0.993
Small gap between train and test -> no overfitting.
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 5
Area only : test RMSE 5.92, R2 0.958
All features : test RMSE 2.49, R2 0.993
More relevant features -> better predictions.
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 6
Area (sq ft) : 1100
Bedrooms : 2
Age of building : 5
Distance to metro : 1.5
Estimated price: Rs. 76.83 lakh (Rs. 6,984 per sq ft)
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 6
Area (sq ft) : 50
Area must be 300-5000 sq ft.
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 7
Charts saved: house_pred.png, house_coef.png, house_residuals.png
1.Explore 2.Train 3.Coefficients 4.Evaluate 5.Compare 6.Predict 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Create dataset
- Show menu and read choice
- Model trained? → No: train first
- model.predict()
- Calculate MAE, RMSE, R2
- Show result
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Explore | 60 rows, Area most correlated | PASS |
| 2 | Evaluate before training | 'Train first' | PASS |
| 3 | Coefficients | Area +, Age -, Metro - | PASS |
| 4 | Evaluate | Test R2 0.993, train 0.994 | PASS |
| 5 | Compare | All features better | PASS |
| 6 | Predict 1100, 2, 5, 1.5 | Estimated price | PASS |
| 7 | Area 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
- 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_scoreare loaded. - Global variables / constants are created:
rng,n,area,bed,age,metro,price,df,FEAT,model. - 8 functions are defined (lines 24โ91) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
explore() | 24โ27 | Explore | main program |
train() | 30โ33 | Train | main program |
coefficients() | 36โ40 | Coefficients | main program |
scores(m, Xtr, Xte) | 43โ48 | Scores | evaluate(), compare() |
evaluate() | 51โ56 | Evaluate | main program |
compare() | 59โ65 | Compare | main program |
predict() | 68โ75 | Predict | main program |
charts() | 78โ91 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HOUSE PRICE PREDICTOR (Linear Regression) (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
explore()shows: Area Bedrooms Age Metro_km Price_lakh (+20 more lines) - You type 2 at Enter choice:runs:
train()shows: Model trained on 45 flats; testing on 15 (+1 more lines) - You type 3 at Enter choice:runs:
coefficients()shows: Area : +0.063 lakh per unit (+6 more lines) - You type 4 at Enter choice:runs:
evaluate()โscores()shows: Set MAE RMSE R2 (+4 more lines) - You type 5 at Enter choice:runs:
compare()โscores()ร2shows: Area only : test RMSE 5.92, R2 0.958 (+3 more lines) - You type 6 at Enter choice:runs:
predict() - You type 1100 at Area (sq ft) :
- You type 2 at Bedrooms :
- You type 5 at Age of building :
- You type 1.5 at Distance to metro :shows: Estimated price: Rs. 76.83 lakh (Rs. 6,984 per sq ft) (+1 more lines)
- You type 6 at Enter choice:runs:
predict() - You type 50 at Area (sq ft) :shows: Area must be 300-5000 sq ft. (+1 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
explore() - lines 24โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Iris Flower Classifier using k-Nearest Neighbour
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
iris | Bunch | data, target, names |
scores | list | Accuracy for each k |
best_k | int | k with highest accuracy |
model | KNeighborsClassifier | Trained classifier |
# =====================================================================
# 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")
=======================================================
IRIS FLOWER CLASSIFIER (KNN)
=======================================================
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 3
Find the best k first (option 2).
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 1
Data shape: (150, 4) | classes: ['setosa', 'versicolor', 'virginica']
Training flowers: 105 Test flowers: 45
setosa mean Sepal length 5.01, Sepal width 3.43, Petal length 1.46, Petal width 0.25
versicolor mean Sepal length 5.94, Sepal width 2.77, Petal length 4.26, Petal width 1.33
virginica mean Sepal length 6.59, Sepal width 2.97, Petal length 5.55, Petal width 2.03
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 2
k = 1 : 95.56 % ############################
k = 2 : 95.56 % ############################
k = 3 : 97.78 % #############################
k = 4 : 95.56 % ############################
k = 5 : 97.78 % #############################
k = 6 : 97.78 % #############################
k = 7 : 97.78 % #############################
k = 8 : 97.78 % #############################
k = 9 : 97.78 % #############################
k = 10 : 97.78 % #############################
k = 11 : 97.78 % #############################
k = 12 : 95.56 % ############################
k = 13 : 95.56 % ############################
k = 14 : 93.33 % ############################
k = 15 : 95.56 % ############################
Best k = 3
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 3
Accuracy: 97.78 %
Confusion matrix (rows = actual setosa, versicolor, virginica):
[[15 0 0]
[ 0 14 1]
[ 0 0 15]]
precision recall f1-score support
setosa 1.00 1.00 1.00 15
versicolor 1.00 0.93 0.97 15
virginica 0.94 1.00 0.97 15
accuracy 0.98 45
macro avg 0.98 0.98 0.98 45
weighted avg 0.98 0.98 0.98 45
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 4
Sepal length: 6.3
Sepal width: 2.9
Petal length: 5.6
Petal width: 1.8
Predicted species: VIRGINICA | votes share: {'setosa': 0.0, 'versicolor': 0.0, 'virginica': 1.0}
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 4
Sepal length: 5.0
Sepal width: 3.4
Petal length: 1.5
Petal width: 0.2
Predicted species: SETOSA | votes share: {'setosa': 1.0, 'versicolor': 0.0, 'virginica': 0.0}
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 4
Sepal length: -1
Sepal width: 2
Petal length: 3
Petal width: 4
Measurements must be positive.
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 5
Sepal length: 6.3
Sepal width: 2.9
Petal length: 5.6
Petal width: 1.8
distance 0.000 -> virginica [6.3 2.9 5.6 1.8]
distance 0.245 -> virginica [6.5 3. 5.5 1.8]
distance 0.245 -> virginica [6.4 3.1 5.5 1.8]
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 6
Charts saved: knn_k.png, iris_scatter.png, iris_confusion.png
1.Explore 2.Best k 3.Evaluate 4.Predict 5.Neighbours 6.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Load iris and split
- Show menu and read choice
- Best k found? → No: compute scores for k=1..15
- Fit KNN with best k
- Predict / evaluate
- Show result
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Explore | 150 x 4, 3 classes | PASS |
| 2 | Best k | Accuracy table | PASS |
| 3 | Evaluate | Confusion matrix | PASS |
| 4 | Predict 6.3, 2.9, 5.6, 1.8 | virginica | PASS |
| 5 | Predict 5.0, 3.4, 1.5, 0.2 | setosa | PASS |
| 6 | Negative value | 'Measurements must be positive' | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
numpy- fast arrays and maths,matplotlib.pyplot- drawing charts,load_iris,train_test_split,KNeighborsClassifier,accuracy_score,confusion_matrix,classification_reportare loaded. - Global variables / constants are created:
iris,NAMES,state. - 7 functions are defined (lines 17โ84) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
explore() | 17โ22 | Explore | main program |
best_k() | 25โ35 | Best k | main program |
evaluate() | 38โ42 | Evaluate | main program |
read_flower() | 45โ50 | Read flower | predict(), neighbours() |
predict() | 53โ57 | Predict | main program |
neighbours() | 60โ65 | Neighbours | main program |
charts() | 68โ84 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: IRIS FLOWER CLASSIFIER (KNN) (+1 more lines)
- You type 3 at Enter choice:shows: Find the best k first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
explore()shows: Data shape: (150, 4) | classes: ['setosa', 'versicolor', 'virginica'] (+5 more lines) - You type 2 at Enter choice:runs:
best_k()shows: k = 1 : 95.56 % ############################ (+16 more lines) - You type 3 at Enter choice:runs:
evaluate()shows: Accuracy: 97.78 % (+12 more lines) - You type 4 at Enter choice:runs:
predict()โread_flower() - You type 6.3 at Sepal length:
- You type 2.9 at Sepal width:
- You type 5.6 at Petal length:
- You type 1.8 at Petal width:shows: Predicted species: VIRGINICA | votes share: {'setosa': 0.0, 'versicolor': 0.0, 'virginica' (+1 more lines)
- You type 4 at Enter choice:runs:
predict()โread_flower() - You type 5.0 at Sepal length:
- You type 3.4 at Sepal width:
- You type 1.5 at Petal length:
- You type 0.2 at Petal width:shows: Predicted species: SETOSA | votes share: {'setosa': 1.0, 'versicolor': 0.0, 'virginica': 0 (+1 more lines)
- You type 4 at Enter choice:runs:
predict()โread_flower() - You type -1 at Sepal length:
- You type 2 at Sepal width:
- You type 3 at Petal length:
- You type 4 at Petal width:shows: Measurements must be positive. (+1 more lines)
- You type 5 at Enter choice:runs:
neighbours()โread_flower() - You type 6.3 at Sepal length:
- You type 2.9 at Sepal width:
- You type 5.6 at Petal length:
- You type 1.8 at Petal width:shows: distance 0.000 -> virginica [6.3 2.9 5.6 1.8] (+3 more lines)
- You type 6 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
explore() - lines 17โ22
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Customer Segmentation using k-Means Clustering (SDG 8)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Income_k, Spending, Cluster |
scaler | StandardScaler | Fitted scaler |
km | KMeans | Fitted model |
prof | DataFrame | Cluster profile with segment names |
# =====================================================================
# 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")
=======================================================
CUSTOMER SEGMENTATION (k-Means)
=======================================================
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 3
Customers Avg_income Avg_spending Segment
Cluster
0 15 80.0 17.2 Careful savers
1 15 25.0 77.1 Impulse buyers
2 15 23.4 18.8 Budget shoppers
3 15 78.7 82.1 Premium customers
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 1
Income_k Spending
0 20.2 10.7
1 23.5 22.9
2 31.8 20.8
3 21.7 14.5
4 29.5 31.4
5 26.6 11.4
6 19.3 31.2
7 26.2 7.9
Customers: 60
Income_k Spending
count 60.0 60.0
mean 51.8 48.8
std 28.3 31.7
min 13.0 7.9
25% 24.3 17.5
50% 54.3 48.8
75% 79.8 78.8
max 90.4 95.3
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 2
k = 1 : inertia 120.0 ##############################
k = 2 : inertia 62.1 ###############
k = 3 : inertia 30.1 #######
k = 4 : inertia 4.3 #
k = 5 : inertia 3.6
k = 6 : inertia 3.1
k = 7 : inertia 2.5
k = 8 : inertia 2.1
The curve bends at k = 4 -> choose 4 clusters.
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 3
Customers Avg_income Avg_spending Segment
Cluster
0 15 80.0 17.2 Careful savers
1 15 25.0 77.1 Impulse buyers
2 15 23.4 18.8 Budget shoppers
3 15 78.7 82.1 Premium customers
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 4
- Careful savers -> quality & warranty offers
- Impulse buyers -> festival combos, easy EMI
- Budget shoppers -> discount coupons, value packs
- Premium customers -> loyalty card, new arrivals preview
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 5
Annual income (thousand Rs): 85
Spending score (1-100): 90
Customer belongs to cluster 3: Premium customers -> loyalty card, new arrivals preview
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 5
Annual income (thousand Rs): 20
Spending score (1-100): 15
Customer belongs to cluster 2: Budget shoppers -> discount coupons, value packs
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 6
Number of clusters k (2-8): 2
Customers Avg_income Avg_spending Segment
Cluster
0 30 24.2 47.9 Budget shoppers
1 30 79.3 49.7 Careful savers
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 6
Number of clusters k (2-8): 1
k must be 2-8.
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 7
Charts saved: kmeans_segments.png, kmeans_elbow.png, segment_sizes.png
1.View 2.Elbow 3.Cluster 4.Actions 5.New Customer 6.Try k 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Create customer data and scale
- Show menu and read choice
- Clustered? → No: fit k-Means
- Profile clusters and name segments
- Show profile / segment
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Elbow | Inertia drops sharply till k = 4 | PASS |
| 2 | Cluster | 4 segments of ~15 | PASS |
| 3 | Actions | 4 actions | PASS |
| 4 | New customer 85, 90 | Premium customers | PASS |
| 5 | New customer 20, 15 | Budget shoppers | PASS |
| 6 | k = 2 | 2-cluster profile | PASS |
| 7 | k = 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
- Imports (line 4):
numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,KMeans,StandardScalerare loaded. - Global variables / constants are created:
rng,groups,df,scaler,X,ACTIONS,state. - 9 functions are defined (lines 20โ88) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
seg_name(inc, sp) | 20โ22 | Seg name | profile() |
view() | 25โ28 | View | main program |
elbow() | 31โ37 | Elbow | main program |
profile(k) | 40โ46 | Profile | cluster(), try_k() |
cluster() | 49โ52 | Cluster | main program |
actions() | 55โ57 | Actions | main program |
new_customer() | 60โ64 | New customer | main program |
try_k() | 67โ72 | Try k | main program |
charts() | 75โ88 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CUSTOMER SEGMENTATION (k-Means) (+1 more lines)
- You type 3 at Enter choice:runs:
cluster()โprofile()โseg_name()ร4shows: Customers Avg_income Avg_spending Segment (+6 more lines) - You type 1 at Enter choice:runs:
view()shows: Income_k Spending (+19 more lines) - You type 2 at Enter choice:runs:
elbow()shows: k = 1 : inertia 120.0 ############################## (+9 more lines) - You type 3 at Enter choice:runs:
cluster()โprofile()โseg_name()ร4shows: Customers Avg_income Avg_spending Segment (+6 more lines) - You type 4 at Enter choice:runs:
actions()shows: - Careful savers -> quality & warranty offers (+4 more lines) - You type 5 at Enter choice:runs:
new_customer() - You type 85 at Annual income (thousand Rs):
- You type 90 at Spending score (1-100):shows: Customer belongs to cluster 3: Premium customers -> loyalty card, new arrivals preview (+1 more lines)
- You type 5 at Enter choice:runs:
new_customer() - You type 20 at Annual income (thousand Rs):
- You type 15 at Spending score (1-100):shows: Customer belongs to cluster 2: Budget shoppers -> discount coupons, value packs (+1 more lines)
- You type 6 at Enter choice:runs:
try_k() - You type 2 at Number of clusters k (2-8):runs:
profile()โseg_name()ร2shows: Customers Avg_income Avg_spending Segment (+4 more lines) - You type 6 at Enter choice:runs:
try_k() - You type 1 at Number of clusters k (2-8):shows: k must be 2-8. (+1 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
seg_name() - lines 20โ22
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Ice-Cream Ordering Chatbot with Intent Matching
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
MENU | dict | flavour -> price (small) |
SIZE | dict | size -> price multiplier |
NUM | dict | number words -> int |
cart | list | (flavour, size, qty) |
orders.txt | text file | Saved bill |
# =====================================================================
# 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}")
============================================================
Bot: Welcome to Cool Scoops! Order in your own words, e.g. '2 large mango'.
Other commands: menu, cancel <flavour>, offers, bill, bye
============================================================
You: hello
Bot: Hello! What would you like today?
You: show me the menu
Bot: Chocolate Rs.60, Vanilla Rs.50, Mango Rs.55, Butterscotch Rs.65, Strawberry Rs.55 (small; medium x1.4, large x1.8)
You: 2 large chocolate cups please
Bot: Added 2 large chocolate. Cart has 2 scoop(s). Anything else?
You: I want mango
Bot: Which size - small, medium or large?
You: tiny
Bot: Please choose small, medium or large.
Bot: Which size - small, medium or large?
You: small
Bot: Added 1 small mango. Cart has 3 scoop(s). Anything else?
You: one butterscotch medium
Bot: Added 1 medium butterscotch. Cart has 4 scoop(s). Anything else?
You: any offers today?
Bot: Buy 3 or more scoops and get 10% off the bill!
You: pizza please
Bot: Sorry, which flavour? We have chocolate, vanilla, mango, butterscotch, strawberry
You: cancel butterscotch
Bot: Removed butterscotch from your order.
You: three vanilla small
Bot: Added 3 small vanilla. Cart has 6 scoop(s). Anything else?
You: what time do you close
Bot: We are open 11 AM to 11 PM, all days.
You: bill
Bot: ----- BILL -----
2 x large chocolate Rs.216
1 x small mango Rs.55
3 x small vanilla Rs.150
Sub-total Rs.421 Discount Rs.42 GST 5% Rs.18.95
TOTAL Rs.397.95
(bill saved to orders.txt)
You: bye
Bot: Thank you for visiting Cool Scoops!
Conversation summary:
[greet ] hello
[menu ] show me the menu
[order ] 2 large chocolate cups please
[order ] I want mango
[order ] one butterscotch medium
[offers ] any offers today?
[order ] pizza please
[cancel ] cancel butterscotch
[order ] three vanilla small
[timing ] what time do you close
[bill ] bill
[bye ] bye
- Start
- Read user message
- Clean and tokenise
- Intent bye? → No: detect other intent
- Intent order? → No: menu / cancel / bill / offers
- Extract flavour, size, quantity
- Size missing? → No: add to cart
- Ask for size (slot filling)
- Reply
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | 'hello' | Greeting | PASS |
| 2 | 'show me the menu' | Menu with prices | PASS |
| 3 | '2 large chocolate cups please' | Added 2 large chocolate | PASS |
| 4 | 'I want mango' | Asks size | PASS |
| 5 | 'one butterscotch medium' | Qty word understood | PASS |
| 6 | 'cancel butterscotch' | Removed | PASS |
| 7 | 'any offers' | Offer message | PASS |
| 8 | 'bill' | Bill with discount and GST | PASS |
| 9 | 'pizza' | Asks valid flavour | PASS |
โ 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
- Imports (line 4):
string- ready-made sets of characters are loaded. - Global variables / constants are created:
MENU,SIZE,NUM,INTENTS. - 4 functions are defined (lines 14โ46) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
clean(msg) | 14โ15 | Clean | main program |
intent_of(tokens) | 18โ22 | Intent of | main program |
entities(tokens) | 25โ29 | Entities | main program |
bill() | 32โ46 | Bill | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: Bot: Welcome to Cool Scoops! Order in your own words, e.g. '2 large mango'. (+1 more lines)
- You type hello at You:runs:
clean()โintent_of()shows: Bot: Hello! What would you like today? - 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 - 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? - You type I want mango at You:runs:
clean()โintent_of()โentities() - You type tiny at Bot: Which size - small, medium or large? You:runs:
clean()shows: Bot: Please choose small, medium or large. - 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? - 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? - You type any offers today? at You:runs:
clean()โintent_of()shows: Bot: Buy 3 or more scoops and get 10% off the bill! - You type pizza please at You:runs:
clean()โintent_of()โentities()shows: Bot: Sorry, which flavour? We have chocolate, vanilla, mango, butterscotch, strawberry - You type cancel butterscotch at You:runs:
clean()โintent_of()โentities()shows: Bot: Removed butterscotch from your order. - 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? - 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. - You type bill at You:runs:
clean()โintent_of()โbill()shows: Bot: ----- BILL ----- (+6 more lines) - 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Student Performance Correlation Study (SDG 4)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Study_hrs, Sleep_hrs, Screen_hrs, Attendance, Marks |
corr | DataFrame | Correlation matrix |
strength() | function | Label for |r| |
# =====================================================================
# 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"))()
=======================================================
STUDENT PERFORMANCE CORRELATION STUDY (SDG 4)
=======================================================
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 1
Study_hrs Sleep_hrs Screen_hrs Attendance Marks
0 4.8 6.7 5.0 85.4 81.4
1 2.9 8.3 3.4 87.7 71.1
2 5.2 7.8 5.9 68.0 70.2
3 4.3 6.2 2.0 79.6 76.8
4 1.0 8.3 1.1 66.5 57.4
5 5.9 8.2 1.5 82.3 100.0
6 4.7 6.5 5.3 76.5 69.6
7 4.8 6.2 3.8 70.1 79.1
Study_hrs Sleep_hrs Screen_hrs Attendance Marks
count 40.00 40.00 40.00 40.00 40.00
mean 3.43 6.91 3.90 81.23 70.77
std 1.60 1.01 1.69 9.69 12.59
min 0.70 5.00 1.10 65.80 49.70
25% 2.15 6.18 2.50 73.47 62.28
50% 3.35 7.05 3.70 82.10 70.65
75% 4.80 7.72 5.30 87.80 79.03
max 5.90 8.40 6.80 98.50 100.00
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 2
Study_hrs Sleep_hrs Screen_hrs Attendance Marks
Study_hrs 1.000 0.010 0.208 0.327 0.869
Sleep_hrs 0.010 1.000 0.024 -0.113 0.081
Screen_hrs 0.208 0.024 1.000 -0.065 -0.175
Attendance 0.327 -0.113 -0.065 1.000 0.478
Marks 0.869 0.081 -0.175 0.478 1.000
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 3
Study_hrs r = +0.869 strong positive
Attendance r = +0.478 moderate positive
Sleep_hrs r = +0.081 weak positive
Screen_hrs r = -0.175 weak negative
Strongest positive factor: Study_hrs | strongest negative: Screen_hrs
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 4
Pearson Spearman
Study_hrs 0.869 0.866
Sleep_hrs 0.081 0.100
Screen_hrs -0.175 -0.118
Attendance 0.478 0.471
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 5
Students Avg_marks Avg_study
Screen_group
High (>4 h) 17 67.4 3.6
Low (<=4 h) 23 73.3 3.3
Difference in average marks: 5.9
Note: correlation shows association, not cause.
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 6
Your study hours: 2
Your sleep hours: 6
Your screen hours: 5
Study_hrs : 2.0 h (more than 25 % of class)
Sleep_hrs : 6.0 h (more than 22 % of class)
Screen_hrs : 5.0 h (more than 65 % of class)
Tip: reduce screen time - it has a negative relation with marks.
Tip: add 1.4 h of study to reach the class average.
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 7
Charts saved: corr_heatmap.png, scatter_matrix.png, screen_groups.png
1.View 2.Matrix 3.Factors 4.Spearman 5.Groups 6.Habit Check 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Create data
- Show menu and read choice
- Valid option? → No: 'Invalid choice'
- df.corr() / groupby
- Show result / charts
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Correlation matrix | 5 x 5, diagonal 1 | PASS |
| 2 | Factors | Study hours strongest + | PASS |
| 3 | Screen time | Negative r | PASS |
| 4 | Spearman | Similar values | PASS |
| 5 | Group comparison | Lower marks with more screen | PASS |
| 6 | Habit check 2, 6, 5 | Advice | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
rng,n,marks,df,corr. - 8 functions are defined (lines 18โ81) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
strength(r) | 18โ21 | Strength | factors() |
view() | 24โ26 | View | main program (menu) |
matrix() | 29โ30 | Matrix | main program (menu) |
factors() | 33โ37 | Factors | main program (menu) |
spearman() | 40โ43 | Spearman | main program (menu) |
groups() | 46โ51 | Groups | main program (menu) |
habit() | 54โ62 | Habit | main program (menu) |
charts() | 65โ81 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: STUDENT PERFORMANCE CORRELATION STUDY (SDG 4) (+1 more lines)
- You type 1 at Enter choice:runs:
view()shows: Study_hrs Sleep_hrs Screen_hrs Attendance Marks (+18 more lines) - You type 2 at Enter choice:runs:
matrix()shows: Study_hrs Sleep_hrs Screen_hrs Attendance Marks (+6 more lines) - You type 3 at Enter choice:runs:
factors()โstrength()ร4shows: Study_hrs r = +0.869 strong positive (+5 more lines) - You type 4 at Enter choice:runs:
spearman()shows: Pearson Spearman (+5 more lines) - You type 5 at Enter choice:runs:
groups()shows: Students Avg_marks Avg_study (+6 more lines) - You type 6 at Enter choice:runs:
habit() - You type 2 at Your study hours:
- You type 6 at Your sleep hours:
- You type 5 at Your screen hours:shows: Study_hrs : 2.0 h (more than 25 % of class) (+5 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
strength() - lines 18โ21
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
SMS Spam Detector using Naive Bayes (SDG 16)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
spam / ham | lists | Training messages |
vec | CountVectorizer | Vocabulary and word counts |
model | MultinomialNB | Classifier |
X_tr, X_te, y_tr, y_te | lists | Train-test split (75:25) |
# =====================================================================
# 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")
======================================================= SMS SPAM DETECTOR (Naive Bayes) ======================================================= 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 4 Train the model first (option 2). 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 1 Messages: 52 | spam: 26 | ham: 26 Train: 39 | Test: 13 Sample spam: Congratulations you won a lottery of 25 lakh claim now Sample ham : Mom I will reach home by 6 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 2 Vocabulary size: 173 Confusion matrix [[TN FP] [FN TP]]: [[5 1] [0 7]] Accuracy 0.923 | Precision 0.875 | Recall 1.000 | F1 0.933 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 3 now spam/ham likelihood ratio 8.67 click spam/ham likelihood ratio 7.71 link spam/ham likelihood ratio 5.78 blocked spam/ham likelihood ratio 4.82 fee spam/ham likelihood ratio 3.85 account spam/ham likelihood ratio 3.85 claim spam/ham likelihood ratio 3.85 get spam/ham likelihood ratio 3.85 update spam/ham likelihood ratio 2.89 urgent spam/ham likelihood ratio 2.89 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 4 Type an SMS to check: Your electricity will be disconnected tonight, call this number now Prediction: SPAM / FRAUD (spam probability 1.00) Most spam-like words in it: ['now', 'electricity', 'be', 'disconnected'] 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 4 Type an SMS to check: Please bring your AI practical file tomorrow Prediction: HAM (genuine) (spam probability 0.01) Most spam-like words in it: ['your', 'ai', 'file', 'bring'] 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 4 Type an SMS to check: Your OTP is 1234 do not share it with anyone Prediction: HAM (genuine) (spam probability 0.05) Most spam-like words in it: ['otp', 'share', 'your', 'is'] 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 5 threshold 0.3: precision 0.64 recall 1.00 threshold 0.5: precision 0.88 recall 1.00 threshold 0.7: precision 1.00 recall 1.00 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 6 * 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. 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 7 now spam/ham likelihood ratio 8.67 click spam/ham likelihood ratio 7.71 link spam/ham likelihood ratio 5.78 blocked spam/ham likelihood ratio 4.82 fee spam/ham likelihood ratio 3.85 account spam/ham likelihood ratio 3.85 claim spam/ham likelihood ratio 3.85 get spam/ham likelihood ratio 3.85 update spam/ham likelihood ratio 2.89 urgent spam/ham likelihood ratio 2.89 threshold 0.3: precision 0.64 recall 1.00 threshold 0.5: precision 0.88 recall 1.00 threshold 0.7: precision 1.00 recall 1.00 Charts saved: spam_confusion.png, spam_words.png, spam_threshold.png 1.Summary 2.Train 3.Spam Words 4.Check SMS 5.Thresholds 6.Tips 7.Charts 0.Exit Enter choice: 0 Stay alert, stay safe!
- Start
- Build dataset and split
- Show menu and read choice
- Model trained? → No: train first
- Vectorise message
- predict_proba
- Probability >= 0.5? → No: HAM
- SPAM warning
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Train | Accuracy shown | PASS |
| 2 | Top words | now, click, claim... | PASS |
| 3 | 'Your electricity will be disconnected tonight, call now' | SPAM | PASS |
| 4 | 'Please bring your AI practical file tomorrow' | HAM | PASS |
| 5 | 'Your OTP is 1234 do not share' | HAM | PASS |
| 6 | Threshold 0.3 | Higher recall | PASS |
| 7 | Check before training | 'Train first' | PASS |
| 8 | Charts | 3 PNG files | PASS |
โ 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
- 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_scoreare loaded. - Global variables / constants are created:
spam,ham,texts,labels,vec,model. - 7 functions are defined (lines 43โ111) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 43โ46 | Summary | main program |
train() | 49โ56 | Train | main program |
spam_words(n) | 59โ66 | Spam words | charts(), main program |
check() | 69โ77 | Check | main program |
thresholds() | 80โ87 | Thresholds | charts(), main program |
tips() | 90โ93 | Tips | main program |
charts() | 96โ111 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: SMS SPAM DETECTOR (Naive Bayes) (+1 more lines)
- You type 4 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
summary()shows: Messages: 52 | spam: 26 | ham: 26 (+4 more lines) - You type 2 at Enter choice:runs:
train()shows: Vocabulary size: 173 (+5 more lines) - You type 3 at Enter choice:runs:
spam_words()shows: now spam/ham likelihood ratio 8.67 (+10 more lines) - You type 4 at Enter choice:runs:
check() - 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)
- You type 4 at Enter choice:runs:
check() - 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)
- You type 4 at Enter choice:runs:
check() - 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)
- You type 5 at Enter choice:runs:
thresholds()shows: threshold 0.3: precision 0.64 recall 1.00 (+3 more lines) - You type 6 at Enter choice:runs:
tips()shows: * Never share OTP, PIN or CVV - banks never ask for them. (+4 more lines) - You type 7 at Enter choice:runs:
charts()โspam_words()โthresholds()shows: [chart is drawn] (+17 more lines) - You type 0 at Enter choice:shows: Stay alert, stay safe!
โค Inside each function - line by line
summary() - lines 43โ46
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Crop Recommendation System using KNN (SDG 2)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | N, P, K, Temp, Humidity, pH, Rainfall, Crop |
cols | list | 7 feature names |
model | Pipeline | MinMaxScaler + KNN |
cv_scores | dict | k -> mean CV accuracy |
# =====================================================================
# 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")
=======================================================
CROP RECOMMENDATION SYSTEM (KNN)
=======================================================
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 4
Train the model first (option 3).
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 1
Records: 200 | Crops: ['rice', 'wheat', 'maize', 'cotton', 'chickpea']
N P K Temp Humidity pH Rainfall
Crop
chickpea 37.7 65.7 79.0 18.3 16.4 7.4 81.6
cotton 119.2 45.5 18.7 23.3 79.8 6.8 80.4
maize 77.0 46.5 19.5 22.7 65.4 6.3 83.4
rice 79.2 45.2 40.7 23.8 80.9 6.4 221.4
wheat 60.7 49.3 40.9 19.8 56.6 6.8 75.7
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 2
k = 3: folds [0.975 0.95 0.975 0.975 0.975] -> mean 97.00 %
k = 5: folds [0.975 0.95 0.975 1. 1. ] -> mean 98.00 %
k = 7: folds [1. 0.975 0.975 1. 1. ] -> mean 99.00 %
k = 9: folds [0.975 0.975 0.95 1. 1. ] -> mean 98.00 %
Best k: 7
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 3
Model trained with k = 7. Hold-out accuracy: 100.00 %
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 4
N : 85
P : 45
K : 40
Temp : 25
Humidity : 82
pH : 6.4
Rainfall : 210
Recommended crop: RICE
rice 100.0 % ####################
wheat 0.0 %
maize 0.0 %
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 4
N : 25
P : 65
K : 80
Temp : 19
Humidity : 17
pH : 7.2
Rainfall : 80
Recommended crop: CHICKPEA
chickpea 100.0 % ####################
wheat 0.0 %
rice 0.0 %
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 4
N : 60
P : 50
K : 40
Temp : 20
Humidity : 55
pH : 15
Rainfall : 75
pH must be 0-14 and humidity 0-100.
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 5
chickpea cotton maize rice wheat
chickpea 10 0 0 0 0
cotton 0 10 0 0 0
maize 0 0 10 0 0
rice 0 0 0 10 0
wheat 0 0 0 0 10
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 6
Charts saved: crop_k.png, crop_profile.png, crop_confusion.png
1.Summary 2.Choose k 3.Train 4.Recommend 5.Test Report 6.Charts 0.Exit
Enter choice: 0
Jai Kisan!
- Start
- Create dataset
- Show menu and read choice
- Model trained? → No: train with best k
- Read soil report
- Values valid? → No: show error
- predict_proba and sort
- Top 3 crops
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Summary | 200 records, 5 crops | PASS |
| 2 | CV | Accuracy for k = 3..9 | PASS |
| 3 | Report 85, 45, 40, 25, 82, 6.4, 210 | RICE | PASS |
| 4 | Report 25, 65, 80, 19, 17, 7.2, 80 | CHICKPEA | PASS |
| 5 | pH 15 | 'pH must be 0-14' | PASS |
| 6 | Test report | Confusion matrix | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- 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_scoreare loaded. - Global variables / constants are created:
rng,profile,spread,rows,cols,df. - 6 functions are defined (lines 25โ82) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 25โ27 | Summary | main program |
choose_k() | 30โ36 | Choose k | main program |
train() | 39โ44 | Train | main program |
recommend() | 47โ57 | Recommend | main program |
test_report() | 60โ64 | Test report | main program |
charts() | 67โ82 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CROP RECOMMENDATION SYSTEM (KNN) (+1 more lines)
- You type 4 at Enter choice:shows: Train the model first (option 3). (+1 more lines)
- You type 1 at Enter choice:runs:
summary()shows: Records: 200 | Crops: ['rice', 'wheat', 'maize', 'cotton', 'chickpea'] (+8 more lines) - 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) - You type 3 at Enter choice:runs:
train()shows: Model trained with k = 7. Hold-out accuracy: 100.00 % (+1 more lines) - You type 4 at Enter choice:runs:
recommend() - You type 85 at N :
- You type 45 at P :
- You type 40 at K :
- You type 25 at Temp :
- You type 82 at Humidity :
- You type 6.4 at pH :
- You type 210 at Rainfall :shows: Recommended crop: RICE (+4 more lines)
- You type 4 at Enter choice:runs:
recommend() - You type 25 at N :
- You type 65 at P :
- You type 80 at K :
- You type 19 at Temp :
- You type 17 at Humidity :
- You type 7.2 at pH :
- You type 80 at Rainfall :shows: Recommended crop: CHICKPEA (+4 more lines)
- You type 4 at Enter choice:runs:
recommend() - You type 60 at N :
- You type 50 at P :
- You type 40 at K :
- You type 20 at Temp :
- You type 55 at Humidity :
- You type 15 at pH :
- You type 75 at Rainfall :shows: pH must be 0-14 and humidity 0-100. (+1 more lines)
- You type 5 at Enter choice:runs:
test_report()shows: chickpea cotton maize rice wheat (+6 more lines) - You type 6 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Jai Kisan!
โค Inside each function - line by line
summary() - lines 25โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Household Energy Consumption Forecaster (SDG 7)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Month_no, Temp, Units |
train / test | DataFrames | Months 1-20 / 21-24 |
model | LinearRegression | Units = a + b*Month + c*Temp |
bill() | function | Slab-wise bill |
# =====================================================================
# 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")
=======================================================
HOUSEHOLD ENERGY FORECASTER (SDG 7)
=======================================================
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 1
Month_no Month Temp Units
1 Jan 14 126.0
2 Feb 17 161.0
3 Mar 23 211.0
4 Apr 29 247.0
5 May 33 312.0
6 Jun 34 317.0
7 Jul 31 281.0
8 Aug 30 287.0
9 Sep 29 277.0
10 Oct 26 252.0
11 Nov 20 196.0
12 Dec 15 160.0
13 Jan 14 137.0
14 Feb 17 173.0
15 Mar 23 225.0
16 Apr 29 294.0
17 May 33 325.0
18 Jun 34 332.0
19 Jul 31 302.0
20 Aug 30 301.0
21 Sep 29 297.0
22 Oct 26 269.0
23 Nov 20 236.0
24 Dec 15 189.0
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 2
Units = -1.5 + 1.58 x Month_no + 9.01 x Temp
Sep: actual 297, predicted 293, error +4
Oct: actual 269, predicted 268, error +1
Nov: actual 236, predicted 215, error +21
Dec: actual 189, predicted 172, error +17
MAE 11.0 units | MAPE 5.0 %
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 3
Month Units Bill (Rs.)
Jan 164 656
Feb 193 771
Mar 248 1090
Total for the quarter: Rs. 2517
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 4
Temperature change (degrees C): 2
Each month uses about +18.0 units -> Rs. +135 per month at top slab
Tip: setting the AC 2 degrees higher saves roughly the same as a 2-degree cooler month.
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 5
Season
Summer 304.5
Monsoon 290.8
Autumn 238.2
Spring 218.0
Winter 157.7
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 6
Charts saved: energy_forecast.png, energy_temp.png, energy_bill.png
1.Data 2.Train & Test 3.Forecast 4.What-if 5.Seasons 6.Charts 0.Exit
Enter choice: 0
Save energy!
- Start
- Create 24-month data
- Show menu and read choice
- Model trained? → No: train first
- Predict future units
- Compute bill with slabs
- Show forecast
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Train & test | MAE and MAPE | PASS |
| 2 | Forecast | Jan-Mar units and bill | PASS |
| 3 | What-if +2 C | Extra units | PASS |
| 4 | Seasonal summary | Summer highest | PASS |
| 5 | Forecast before train | 'Train first' | PASS |
| 6 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,LinearRegression,mean_absolute_errorare loaded. - Global variables / constants are created:
MONTHS,temps,rng,month_no,units,df,F,model. - 7 functions are defined (lines 21โ82) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
bill(u) | 21โ27 | Bill | forecast(), charts() |
view() | 30โ31 | View | main program |
train_test() | 34โ42 | Train test | main program |
forecast() | 45โ51 | Forecast | main program |
what_if() | 54โ58 | What if | main program |
seasonal() | 61โ65 | Seasonal | main program |
charts() | 68โ82 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HOUSEHOLD ENERGY FORECASTER (SDG 7) (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
view()shows: Month_no Month Temp Units (+25 more lines) - 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) - You type 3 at Enter choice:runs:
forecast()โbill()ร6shows: Month Units Bill (Rs.) (+5 more lines) - You type 4 at Enter choice:runs:
what_if() - 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)
- You type 5 at Enter choice:runs:
seasonal()shows: Season (+6 more lines) - You type 6 at Enter choice:runs:
charts()โbill()ร24shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Save energy!
โค Inside each function - line by line
bill() - lines 21โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
AI Bias Audit of a Loan-Approval Model (SDG 10)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Income, Good_history, Rural, Pin_zone, Approved |
audit() | function | Trains a tree and returns fairness metrics |
models | dict | Trained models A, B, C |
# =====================================================================
# 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")
=======================================================
AI BIAS AUDIT - LOAN APPROVAL (SDG 10)
=======================================================
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 1
Historical approval rate:
Rural
Urban 0.441
Rural 0.136
Disparate impact in history: 0.31
Same income & history, yet rural applicants were approved less -> biased data.
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 2
Model A: features ['Income', 'Good_history', 'Rural']
Test accuracy : 0.900
Approval urban/rural: 0.366 / 0.079
Disparate impact : 0.22 -> BIASED (below 0.8)
Equal-opportunity gap (qualified applicants): 0.70
Feature importance : {'Income': 0.306, 'Good_history': 0.444, 'Rural': 0.249}
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 3
Model B: features ['Income', 'Good_history']
Test accuracy : 0.775
Approval urban/rural: 0.242 / 0.206
Disparate impact : 0.85 -> FAIR
Equal-opportunity gap (qualified applicants): 0.09
Feature importance : {'Income': 0.391, 'Good_history': 0.609}
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 4
Model C: features ['Income', 'Good_history', 'Pin_zone']
Test accuracy : 0.883
Approval urban/rural: 0.419 / 0.145
Disparate impact : 0.35 -> BIASED (below 0.8)
Equal-opportunity gap (qualified applicants): 0.57
Feature importance : {'Income': 0.327, 'Good_history': 0.506, 'Pin_zone': 0.168}
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 5
Income (thousand Rs/month): 36
Good history 1/0: 1
Rural 1/0: 1
Model A: REJECTED
Model B: APPROVED
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 5
Income (thousand Rs/month): 36
Good history 1/0: 1
Rural 1/0: 0
Model A: APPROVED
Model B: APPROVED
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 6
[ ] 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
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 7
Charts saved: bias_audit.png, bias_history.png, bias_tree_importance.png
1.History 2.Model A 3.Model B 4.Proxy Test 5.Check Applicant 6.Ethics 7.Charts 0.Exit
Enter choice: 0
Fair AI for all!
- Start
- Simulate biased historical data
- Show menu and read choice
- Train decision tree on chosen features
- Approval rate urban vs rural
- Ratio >= 0.8? → No: 'BIASED'
- 'FAIR'
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Historical | Rural approval much lower | PASS |
| 2 | Model A | Disparate impact < 0.8 -> BIASED | PASS |
| 3 | Model B | Ratio improves | PASS |
| 4 | Model C (proxy) | Bias returns | PASS |
| 5 | Same applicant (36, good history) rural vs urban | Model A changes decision with location; Model B does not | PASS |
| 6 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts,DecisionTreeClassifier,train_test_splitare loaded. - Global variables / constants are created:
rng,n,income,history,rural,pin_zone,biased,approved,df. - 5 functions are defined (lines 22โ78) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
historical() | 22โ26 | Historical | main program |
audit(features, name) | 29โ45 | Audit | main program |
check() | 48โ54 | Check | main program |
ethics() | 57โ60 | Ethics | main program |
charts() | 63โ78 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: AI BIAS AUDIT - LOAN APPROVAL (SDG 10) (+1 more lines)
- You type 1 at Enter choice:runs:
historical()shows: Historical approval rate: (+6 more lines) - You type 2 at Enter choice:runs:
audit()shows: Model A: features ['Income', 'Good_history', 'Rural'] (+6 more lines) - You type 3 at Enter choice:runs:
audit()shows: Model B: features ['Income', 'Good_history'] (+6 more lines) - You type 4 at Enter choice:runs:
audit()shows: Model C: features ['Income', 'Good_history', 'Pin_zone'] (+6 more lines) - You type 5 at Enter choice:runs:
check() - You type 36 at Income (thousand Rs/month):
- You type 1 at Good history 1/0:
- You type 1 at Rural 1/0:shows: Model A: REJECTED (+2 more lines)
- You type 5 at Enter choice:runs:
check() - You type 36 at Income (thousand Rs/month):
- You type 1 at Good history 1/0:
- You type 0 at Rural 1/0:shows: Model A: APPROVED (+2 more lines)
- You type 6 at Enter choice:runs:
ethics()shows: [ ] Check training data for historical bias (+6 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Fair AI for all!
โค Inside each function - line by line
historical() - lines 22โ26
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
Breast Cancer Diagnosis Assistant - Classification & Evaluation (SDG 3)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
X, y | arrays | 30 features; 1 = malignant |
model | Pipeline | Scaler + LogisticRegression |
prob | array | Predicted malignant probability |
THRESH | float | Decision threshold |
# =====================================================================
# 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")
============================================================
BREAST CANCER DIAGNOSIS ASSISTANT (SDG 3)
============================================================
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 1
Samples: 569 | Features: 30
Malignant: 212 | Benign: 357
First 6 features: ['mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness', 'mean compactness']
Train: 426 | Test: 143
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 2
Logistic Regression trained on 426 patients.
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 3
Confusion matrix (positive = malignant)
TP = 49 FN = 4
FP = 1 TN = 89
Accuracy 0.9650 | Precision 0.9800 | Recall 0.9245 | F1 0.9515 | ROC-AUC 0.9962
Missed malignant cases (FN): 4 | False alarms (FP): 1
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 4
Threshold FN FP Recall Precision
0.2 2 3 0.962 0.944
0.3 2 1 0.962 0.981
0.4 3 1 0.943 0.980
0.5 4 1 0.925 0.980
0.6 5 0 0.906 1.000
0.7 5 0 0.906 1.000
For screening choose a lower threshold (e.g. 0.3) so fewer cancers are missed.
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 5
Model Accuracy Recall AUC
Logistic Regression 0.965 0.925 0.996
Decision Tree 0.895 0.736 0.934
KNN (k=5) 0.958 0.906 0.986
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 6
worst texture +1.366 (raises malignant risk)
radius error +1.267 (raises malignant risk)
worst symmetry +1.036 (raises malignant risk)
mean concave points +0.963 (raises malignant risk)
compactness error -0.927 (lowers malignant risk)
worst area +0.889 (raises malignant risk)
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 7
Patient T01: malignant probability 99.9 % -> HIGH | actual: Malignant
Patient T02: malignant probability 0.4 % -> LOW | actual: Benign
Patient T03: malignant probability 100.0 % -> HIGH | actual: Malignant
Patient T04: malignant probability 0.0 % -> LOW | actual: Benign
Patient T05: malignant probability 3.5 % -> LOW | actual: Benign
Note: AI assists doctors; final diagnosis needs biopsy.
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 8
Threshold FN FP Recall Precision
0.2 2 3 0.962 0.944
0.3 2 1 0.962 0.981
0.4 3 1 0.943 0.980
0.5 4 1 0.925 0.980
0.6 5 0 0.906 1.000
0.7 5 0 0.906 1.000
For screening choose a lower threshold (e.g. 0.3) so fewer cancers are missed.
Charts saved: cancer_cm.png, cancer_roc.png, cancer_threshold.png
1.Summary 2.Train 3.Evaluate 4.Thresholds 5.Compare 6.Top Features 7.Risk Report 8.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Load dataset and split
- Show menu and read choice
- Model trained? → No: train first
- prob = predict_proba
- prob >= threshold? → No: Benign
- Malignant - refer to doctor
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Summary | 569 x 30 | PASS |
| 2 | Evaluate | Accuracy ~ 98 % | PASS |
| 3 | Threshold 0.3 | FN reduced | PASS |
| 4 | Compare | LogReg best AUC | PASS |
| 5 | Top features | Texture / radius worst | PASS |
| 6 | Risk report | 5 patients with % | PASS |
| 7 | Evaluate 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
- 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_curveare loaded. - Global variables / constants are created:
data,state. - 9 functions are defined (lines 21โ102) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 21โ25 | Summary | main program |
train() | 28โ31 | Train | main program |
metrics(pred) | 34โ35 | Metrics | evaluate() |
evaluate() | 38โ44 | Evaluate | main program |
thresholds() | 47โ56 | Thresholds | charts(), main program |
compare() | 59โ66 | Compare | main program |
top_features() | 69โ73 | Top features | main program |
risk_report() | 76โ81 | Risk report | main program |
charts() | 84โ102 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: BREAST CANCER DIAGNOSIS ASSISTANT (SDG 3) (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
summary()shows: Samples: 569 | Features: 30 (+4 more lines) - You type 2 at Enter choice:runs:
train()shows: Logistic Regression trained on 426 patients. (+1 more lines) - You type 3 at Enter choice:runs:
evaluate()โmetrics()shows: Confusion matrix (positive = malignant) (+5 more lines) - You type 4 at Enter choice:runs:
thresholds()shows: Threshold FN FP Recall Precision (+8 more lines) - You type 5 at Enter choice:runs:
compare()shows: Model Accuracy Recall AUC (+4 more lines) - You type 6 at Enter choice:runs:
top_features()shows: worst texture +1.366 (raises malignant risk) (+6 more lines) - You type 7 at Enter choice:runs:
risk_report()shows: Patient T01: malignant probability 99.9 % -> HIGH | actual: Malignant (+6 more lines) - You type 8 at Enter choice:runs:
charts()โthresholds()shows: [chart is drawn] (+12 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
summary() - lines 21โ25
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Diabetes Progression Predictor - Regression with Cross-Validation (SDG 3)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
X, y | arrays | 10 features, target = disease progression after 1 year |
models | dict | Three regressors |
cv_rmse | dict | Mean CV RMSE per model |
best | str | Name of best model |
# =====================================================================
# 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")
============================================================ DIABETES PROGRESSION PREDICTOR (SDG 3) ============================================================ 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 3 Linear Regression : folds [54. 56. 50.8 53.5 56.2] -> 54.10 (+/- 1.94) Decision Tree : folds [63.9 62.7 60. 51.4 73.8] -> 62.34 (+/- 7.20) Random Forest : folds [57.5 58.1 50.5 54.6 60.1] -> 56.19 (+/- 3.33) Best model (lowest RMSE): Linear Regression Linear Regression trained on 353 patients. 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 1 Patients: 442 | Features: ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6'] Target range: 25.0 to 346.0 | mean 152.1 Train: 353 | Test: 89 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 2 Linear Regression : folds [54. 56. 50.8 53.5 56.2] -> 54.10 (+/- 1.94) Decision Tree : folds [63.9 62.7 60. 51.4 73.8] -> 62.34 (+/- 7.20) Random Forest : folds [57.5 58.1 50.5 54.6 60.1] -> 56.19 (+/- 3.33) Best model (lowest RMSE): Linear Regression 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 3 Linear Regression trained on 353 patients. 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 4 MAE 46.17 | MSE 3424.26 | RMSE 58.52 | R2 0.3322 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 5 s5 0.236 ############## s1 0.214 ############ bmi 0.181 ########## s2 0.104 ###### bp 0.098 ##### sex 0.078 #### s4 0.055 ### s6 0.014 age 0.011 s3 0.008 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 6 Test patient number (1-89): 5 Patient 5: predicted progression 187.4, actual 175, error -12.4 Risk: MODERATE 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 6 Test patient number (1-89): 500 Choose 1-89. 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 7 Charts saved: diabetes_pred.png, diabetes_cv.png, diabetes_importance.png 1.Summary 2.Cross-Validate 3.Train Best 4.Test Metrics 5.Importance 6.Predict 7.Charts 0.Exit Enter choice: 0 Bye!
- Start
- Load data, split 80:20
- Show menu and read choice
- Cross-validate each model
- Choose lowest RMSE
- Fit best model and test
- Show metrics / prediction
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Summary | 442 x 10 | PASS |
| 2 | CV | 3 RMSE values | PASS |
| 3 | Best model | Lowest RMSE | PASS |
| 4 | Test metrics | RMSE 58.5, R2 0.33 | PASS |
| 5 | Importance | s5, s1, bmi top | PASS |
| 6 | Patient 5 | Predicted vs actual | PASS |
| 7 | Patient 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
- 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_scoreare loaded. - Global variables / constants are created:
d,models. - 7 functions are defined (lines 21โ81) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 21โ24 | Summary | main program |
cross_validate() | 27โ33 | Cross validate | train_best(), main program |
train_best() | 36โ42 | Train best | main program |
test_metrics() | 45โ48 | Test metrics | main program |
importance() | 51โ56 | Importance | charts(), main program |
predict_patient() | 59โ66 | Predict patient | main program |
charts() | 69โ81 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: DIABETES PROGRESSION PREDICTOR (SDG 3) (+1 more lines)
- 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) - 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) - 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) - You type 3 at Enter choice:runs:
train_best()shows: Linear Regression trained on 353 patients. (+1 more lines) - 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) - You type 5 at Enter choice:runs:
importance()shows: s5 0.236 ############## (+10 more lines) - You type 6 at Enter choice:runs:
predict_patient() - You type 5 at Test patient number (1-89):shows: Patient 5: predicted progression 187.4, actual 175, error -12.4 (+2 more lines)
- You type 6 at Enter choice:runs:
predict_patient() - You type 500 at Test patient number (1-89):shows: Choose 1-89. (+1 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
summary() - lines 21โ24
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Handwritten Digit Recogniser using a Neural Network
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
X | array | 1797 x 64 pixel values / 16 |
net | MLPClassifier | Neural network |
img_te | array | 8x8 test images |
pred | array | Predicted digits |
# =====================================================================
# 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")
============================================================
HANDWRITTEN DIGIT RECOGNISER (Neural Network)
============================================================
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 3
Train the network first (option 2).
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 1
Images: 1797 | each (8, 8) = 64 inputs
Class counts: {0: 178, 1: 182, 2: 177, 3: 183, 4: 181, 5: 182, 6: 181, 7: 179, 8: 174, 9: 180}
Train: 1347 | Test: 450
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 2
Network: 64 inputs -> 64 -> 32 -> 10 outputs | weights: 6570
Iterations: 208 | loss first 2.328 -> final 0.0047
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 3
Test accuracy: 97.78 %
Wrong predictions: 10 of 450
Most confused (actual -> predicted): [((8, 1), 2), ((4, 8), 1), ((2, 1), 1)]
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 4
digit 0: 100.00 % ####################
digit 1: 97.83 % ###################
digit 2: 97.73 % ###################
digit 3: 97.83 % ###################
digit 4: 97.78 % ###################
digit 5: 100.00 % ####################
digit 6: 97.78 % ###################
digit 7: 100.00 % ####################
digit 8: 90.70 % ##################
digit 9: 97.78 % ###################
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 5
hidden (16,) accuracy 97.33 % iterations 400
hidden (64,) accuracy 97.78 % iterations 371
hidden (64, 32) accuracy 97.78 % iterations 208
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 6
Test image number (1-450): 4
....++##++......
....########....
....++##++##....
......######++..
........++####..
..........++##..
..........++##++
......########..
Actual 9 | Predicted 9 with confidence 100.0 %
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 6
Test image number (1-450): 999
Choose 1-450.
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 7
Charts saved: digits_pred.png, digits_loss.png, digits_confusion.png
1.Summary 2.Train 3.Evaluate 4.Per-digit 5.Experiment 6.Show Image 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Load and scale images
- Show menu and read choice
- Network trained? → No: train first
- Forward pass -> predicted digit
- Show accuracy / image
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Summary | 1797 images 8x8 | PASS |
| 2 | Train | Loss decreases | PASS |
| 3 | Evaluate | Accuracy ~ 97 % | PASS |
| 4 | Per-digit | 10 rows | PASS |
| 5 | Experiment | Bigger network better | PASS |
| 6 | Image 4 | ASCII digit | PASS |
| 7 | Image 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
- Imports (line 4):
numpy- fast arrays and maths,matplotlib.pyplot- drawing charts,Counter,load_digits,train_test_split,MLPClassifier,accuracy_score,confusion_matrixare loaded. - Global variables / constants are created:
digits,state. - 7 functions are defined (lines 18โ79) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 18โ21 | Summary | main program |
train() | 24โ28 | Train | main program |
evaluate() | 31โ36 | Evaluate | main program |
per_digit() | 39โ44 | Per digit | main program |
experiment() | 47โ50 | Experiment | main program |
show_image() | 53โ62 | Show image | main program |
charts() | 65โ79 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HANDWRITTEN DIGIT RECOGNISER (Neural Network) (+1 more lines)
- You type 3 at Enter choice:shows: Train the network first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
summary()shows: Images: 1797 | each (8, 8) = 64 inputs (+3 more lines) - You type 2 at Enter choice:runs:
train()shows: Network: 64 inputs -> 64 -> 32 -> 10 outputs | weights: 6570 (+2 more lines) - You type 3 at Enter choice:runs:
evaluate()shows: Test accuracy: 97.78 % (+3 more lines) - You type 4 at Enter choice:runs:
per_digit()shows: digit 0: 100.00 % #################### (+10 more lines) - You type 5 at Enter choice:runs:
experiment()shows: hidden (16,) accuracy 97.33 % iterations 400 (+3 more lines) - You type 6 at Enter choice:runs:
show_image() - You type 4 at Test image number (1-450):shows: ....++##++...... (+9 more lines)
- You type 6 at Enter choice:runs:
show_image() - You type 999 at Test image number (1-450):shows: Choose 1-450. (+1 more lines)
- You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
summary() - lines 18โ21
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Celsius to Fahrenheit Neural Network with TensorFlow-Keras
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
celsius, fahrenheit | arrays | Training pairs |
model | keras.Sequential | Dense(1) network |
history | History | Loss per epoch |
w, b | float | Learnt weight and bias |
# =====================================================================
# 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")
============================================================
CELSIUS -> FAHRENHEIT NEURAL NETWORK (TensorFlow-Keras)
============================================================
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 4
Train the model first (option 2).
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 1
Celsius Fahrenheit
-40.0 -40.0
-10.0 14.0
0.0 32.0
8.0 46.4
15.0 59.0
22.0 71.6
38.0 100.4
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 2
Loss epoch 1: 1535.69 | epoch 100: 498.80 | epoch 500: 7.14 | epoch 1000: 0.0005
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 3
Learnt formula: F = 1.8002 x C + 31.9766 (true: 1.8 x C + 32)
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 4
Temperature in Celsius: 100
Neural network: 212.00 F | Formula: 212.00 F | difference 0.004
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 4
Temperature in Celsius: -40
Neural network: -40.03 F | Formula: -40.00 F | difference 0.031
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 4
Temperature in Celsius: 36.6
Neural network: 97.86 F | Formula: 97.88 F | difference 0.016
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 4
Temperature in Celsius: abc
Enter a number.
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 5
learning rate 0.01 : loss after 200 epochs = 2658.5369
learning rate 0.1 : loss after 200 epochs = 235.4907
learning rate 1.0 : loss after 200 epochs = 0.0000
Lowest loss with learning rate 1.0; 0.01 is far too slow for this problem.
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 6
Layer: dense | type Dense | units 1 | params 2
Total trainable parameters: 2 (1 weight + 1 bias)
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 7
Charts saved: tf_loss.png, tf_fit.png, tf_lr.png
1.Data 2.Train 3.Formula 4.Convert 5.LR Experiment 6.Summary 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Show menu and read choice
- Model trained? → No: build and train
- model.fit(epochs=1000)
- Read weights
- Convert input temperature
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Train | Loss falls to near 0 | PASS |
| 2 | Formula | w ~ 1.8, b ~ 32 | PASS |
| 3 | 100 C | ~ 212 F | PASS |
| 4 | -40 C | ~ -40 F | PASS |
| 5 | 36.6 C | ~ 97.9 F | PASS |
| 6 | LR experiment | Higher rate converges faster here | PASS |
| 7 | Convert '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
- Imports (line 4):
numpy- fast arrays and maths,tensorflow- deep learning,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
celsius,fahrenheit,state. - 8 functions are defined (lines 14โ82) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
build(lr) | 14โ17 | Build | train(), lr_experiment() |
show_data() | 20โ23 | Show data | main program |
train() | 26โ31 | Train | main program |
formula() | 34โ37 | Formula | main program |
convert() | 40โ47 | Convert | main program |
lr_experiment() | 50โ58 | Lr experiment | charts(), main program |
summary() | 61โ65 | Summary | main program |
charts() | 68โ82 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
School Health Records - Data Cleaning & CSV Pipeline (SDG 3)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
raw / df | DataFrame | Original and working copy |
health_clean.csv | CSV file | Cleaned data |
health_summary.csv | CSV file | Diet-wise summary |
log | list | Pipeline steps done |
# =====================================================================
# 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")
============================================================
HEALTH DATA PIPELINE (SDG 3)
============================================================
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 4
Import the data first (option 1).
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 1
IMPORT -> rows: 12 columns: 6
Name Age Height_cm Weight_kg Sleep_hrs Diet
Aditi 16 158.0 50.0 7.5 Veg
Bharat 17 170.0 64.0 NaN Non-Veg
Chirag 16 NaN 58.0 6.5 Veg
Divya 17 162.0 52.0 8.0 NaN
Eshan 16 175.0 80.0 6.0 Non-Veg
Fatima 17 155.0 NaN 7.0 Veg
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 2
Data types:
Name object
Age int64
Height_cm float64
Weight_kg float64
Sleep_hrs float64
Diet object
Missing values per column:
Name 0
Age 0
Height_cm 2
Weight_kg 1
Sleep_hrs 2
Diet 1
Total missing cells: 6 | duplicate rows: 0
Impossible values: none
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 4
Clean the data first (option 3).
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 3
CLEAN -> Height: mean, Weight: median, Sleep: mean, Diet: mode
Missing cells now: 0
IQR check on weight: normal 28.2 to 90.2 kg | outliers: none
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 4
TRANSFORM -> new columns: BMI, BMI_Status, Sleep_OK, Age_group
Name Age_group BMI BMI_Status Sleep_hrs Sleep_OK
Aditi 15-16 20.0 Normal 7.5 True
Bharat 17-18 22.1 Normal 7.0 True
Chirag 15-16 21.2 Normal 6.5 False
Divya 17-18 19.8 Normal 8.0 True
Eshan 15-16 26.1 Over 6.0 False
Fatima 17-18 25.4 Over 7.0 True
Gaurav 15-16 21.6 Normal 7.5 True
Harsh 17-18 30.4 Obese 5.5 False
Ira 15-16 18.4 Under 8.0 True
Jatin 17-18 24.1 Normal 7.0 True
Kavya 15-16 18.3 Under 7.0 True
Lakshay 17-18 22.1 Normal 6.5 False
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 5
EXPORT -> health_clean.csv (12, 10) and health_summary.csv
Diet Students Avg_BMI Avg_sleep
Non-Veg 4 25.18 6.25
Veg 8 21.10 7.31
Students sleeping less than 7 hours: 4
BMI status count: {'Normal': 7, 'Under': 2, 'Over': 2, 'Obese': 1}
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 7
Charts saved: health_missing.png, health_bmi.png, health_sleep.png
1.Import 2.Audit 3.Clean 4.Transform 5.Export 6.Full Pipeline 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Show menu and read choice
- Data imported? → No: import first
- Audit missing values
- Impute: mean / median / mode
- Create BMI and flags
- Export CSV files
- Show summary
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Import | Rows and columns | PASS |
| 2 | Audit | Missing per column | PASS |
| 3 | Clean | Missing = 0 | PASS |
| 4 | Transform | BMI column added | PASS |
| 5 | Export | 2 files read back | PASS |
| 6 | Transform before clean | 'Clean first' | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - 7 functions are defined (lines 10โ87) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
imp() | 10โ16 | Imp | full() (menu), main program |
audit() | 19โ26 | Audit | full() (menu), main program |
clean() | 29โ41 | Clean | full() (menu), main program |
transform() | 44โ55 | Transform | full() (menu), main program |
export() | 58โ68 | Export | full() (menu), main program |
full() | 71โ76 | Full | main program |
charts() | 79โ87 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: HEALTH DATA PIPELINE (SDG 3) (+1 more lines)
- You type 4 at Enter choice:shows: Import the data first (option 1). (+1 more lines)
- You type 1 at Enter choice:runs:
imp()shows: IMPORT -> rows: 12 columns: 6 (+8 more lines) - You type 2 at Enter choice:runs:
audit()shows: Data types: (+16 more lines) - You type 4 at Enter choice:runs:
transform()shows: Clean the data first (option 3). (+1 more lines) - You type 3 at Enter choice:runs:
clean()shows: CLEAN -> Height: mean, Weight: median, Sleep: mean, Diet: mode (+3 more lines) - You type 4 at Enter choice:runs:
transform()shows: TRANSFORM -> new columns: BMI, BMI_Status, Sleep_OK, Age_group (+14 more lines) - You type 5 at Enter choice:runs:
export()shows: EXPORT -> health_clean.csv (12, 10) and health_summary.csv (+6 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
imp() - lines 10โ16
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Smart Object Counter & Shape Detector with OpenCV (Computer Vision)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
img / gray / thresh | arrays | Image at each stage |
contours | list | Outlines of objects |
objects | list of dict | shape, area, perimeter, corners, centre |
THRESH, MIN_AREA | int | Settings |
# =====================================================================
# 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"))()
============================================================
SMART OBJECT COUNTER (OpenCV)
============================================================
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 2
Settings: threshold 230, minimum area 300
No Shape Area Perimeter Corners
1 Rectangle 12442 445.7 4
2 Rectangle 11658 465.1 4
3 Circle 9766 370.7 8
4 Pentagon 8023 356.5 5
5 Triangle 5399 346.2 3
Total objects: 5 | Count by shape: {'Rectangle': 2, 'Circle': 1, 'Pentagon': 1, 'Triangle': 1}
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 1
Image size: 420 x 300 | channels: 3
Gray min / max / mean: 59 / 255 / 195.8
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 2
Settings: threshold 230, minimum area 300
No Shape Area Perimeter Corners
1 Rectangle 12442 445.7 4
2 Rectangle 11658 465.1 4
3 Circle 9766 370.7 8
4 Pentagon 8023 356.5 5
5 Triangle 5399 346.2 3
Total objects: 5 | Count by shape: {'Rectangle': 2, 'Circle': 1, 'Pentagon': 1, 'Triangle': 1}
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 3
No Shape Centre Circularity
1 Rectangle (90, 90) 0.787
2 Rectangle (140, 225) 0.677
3 Circle (250, 90) 0.893
4 Pentagon (330, 230) 0.793
5 Triangle (349, 106) 0.566
Largest object: Rectangle with area 12442 px
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 4
1. Rectangle colour: Blue
2. Rectangle colour: Orange
3. Circle colour: Red
4. Pentagon colour: Purple
5. Triangle colour: Green
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 5
Threshold (0-255): 200
Minimum area (pixels): 300
Settings changed. Run Detect again.
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 2
Settings: threshold 200, minimum area 300
No Shape Area Perimeter Corners
1 Rectangle 12436 443.3 4
2 Rectangle 11198 457.7 4
3 Circle 9590 365.0 8
4 Pentagon 7830 351.7 5
5 Triangle 5195 342.2 3
Total objects: 5 | Count by shape: {'Rectangle': 2, 'Circle': 1, 'Pentagon': 1, 'Triangle': 1}
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 5
Threshold (0-255): 230
Minimum area (pixels): 300
Settings changed. Run Detect again.
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 6
Charts saved: shapes_steps.png, shapes_detected.png, shapes_count.png
1.Info 2.Detect 3.Measurements 4.Colours 5.Settings 6.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Read image
- Gray -> blur -> threshold
- Find contours
- Area >= MIN_AREA? → No: ignore noise
- Approximate polygon, count corners
- Corners = 3 / 4 / 5? → No: circle
- Label and count shapes
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Image info | Width x height | PASS |
| 2 | Detect | Shapes listed with corners | PASS |
| 3 | Measurements | Circularity ~ 1 for circle | PASS |
| 4 | Colour | Dominant colour names | PASS |
| 5 | Threshold 200 | Count may change | PASS |
| 6 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
cv2- OpenCV image processing,numpy- fast arrays and maths,matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
img,objects. - 8 functions are defined (lines 13โ112) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
stages() | 13โ17 | Stages | info(), detect(), charts() |
info() | 20โ23 | Info | main program (menu) |
colour_name(bgr) | 26โ34 | Colour name | detect() |
detect(show) | 37โ65 | Detect | measurements(), colours(), charts(), main program (menu) |
measurements() | 68โ76 | Measurements | main program (menu) |
colours() | 79โ83 | Colours | main program (menu) |
settings() | 86โ90 | Settings | main program (menu) |
charts() | 93โ112 | Charts | main program (menu) |
โข Main program - line by line
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Traffic Sensor Data-Stream Analytics (Big Data, SDG 11)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
stream() | generator | Yields (minute, junction, cars) |
windows | dict of deque | Last 15 readings per junction |
reservoir | list | Random sample of K records |
df | DataFrame | All records for batch analysis |
# =====================================================================
# 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")
============================================================
TRAFFIC DATA-STREAM ANALYTICS (Big Data)
============================================================
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 2
Run the stream first (option 1).
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 1
Records streamed (4 per minute): 5760 | alerts: 1
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 2
Congestion alerts (15-min average > 95 vehicles/min):
ALERT 17:53 - Azadpur avg 95.3
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 3
Reservoir size: 200 | sample mean: 29.8 | true mean: 30.2
Error of estimate: 1.32 % using only 3.5 % of data
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 4
Peak hours: [18, 17, 9] | quietest: [1, 12, 13]
06:00 4699 ####
09:00 14989 ##############
12:00 4015 ####
15:00 5975 #####
18:00 17390 #################
21:00 4250 ####
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 5
sum mean max
junction
Azadpur 55148 38.3 110
Rohini 44812 31.1 93
Shalimar Bagh 39366 27.3 88
Pitampura 34644 24.1 76
Busiest junction: Azadpur | total vehicles counted: 173970
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 6
Volume : 5760 records in one day (2,102,400 per year)
Velocity: 4 new records every minute (real cities: thousands per second)
Variety : numbers here; real systems add camera video and GPS
Veracity: sensor noise -> we use 15-minute averages, not single readings
Value : alerts help traffic police divert vehicles in time
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 7
Charts saved: traffic_stream.png, traffic_window.png, traffic_reservoir.png
1.Run Stream 2.Alerts 3.Reservoir 4.Hourly 5.Junctions 6.Big Data V's 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Read next record from stream
- Add to junction window
- Window avg > LIMIT and no alert? → No: continue
- Raise congestion alert
- Reservoir sampling step
- Stream ended? → No: read next record
- Reports
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Run stream | 5760 records | PASS |
| 2 | Alerts | Evening rush alerts | PASS |
| 3 | Reservoir | Sample mean close to true mean | PASS |
| 4 | Hourly | Peaks at 9 and 18 h | PASS |
| 5 | Junction report | Azadpur busiest | PASS |
| 6 | Alerts before run | 'Run the stream first' | PASS |
| 7 | Charts | 3 PNG files | PASS |
โ 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
- Imports (line 4):
random- random number functions,deque,numpy- fast arrays and maths,pandas- data tables (Series & DataFrame),matplotlib.pyplot- drawing charts are loaded. - Global variables / constants are created:
junctions,base,state. - 8 functions are defined (lines 17โ98) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
stream() | 17โ22 | Stream | run() |
run() | 25โ49 | Run | main program |
alerts() | 52โ55 | Alerts | run() (menu), run() (menu), run() (menu), main program |
reservoir() | 58โ61 | Reservoir | run() (menu), run() (menu), run() (menu), run() (menu) |
hourly() | 64โ68 | Hourly | main program |
junction_report() | 71โ74 | Junction report | main program |
vs() | 77โ83 | Vs | main program |
charts() | 86โ98 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: TRAFFIC DATA-STREAM ANALYTICS (Big Data) (+1 more lines)
- You type 2 at Enter choice:shows: Run the stream first (option 1). (+1 more lines)
- You type 1 at Enter choice:runs:
run()โstream()ร5761shows: Records streamed (4 per minute): 5760 | alerts: 1 (+1 more lines) - You type 2 at Enter choice:runs:
alerts()shows: Congestion alerts (15-min average > 95 vehicles/min): (+2 more lines) - You type 3 at Enter choice:runs:
reservoir()shows: Reservoir size: 200 | sample mean: 29.8 | true mean: 30.2 (+2 more lines) - You type 4 at Enter choice:runs:
hourly()shows: Peak hours: [18, 17, 9] | quietest: [1, 12, 13] (+7 more lines) - You type 5 at Enter choice:runs:
junction_report()shows: sum mean max (+7 more lines) - You type 6 at Enter choice:runs:
vs()shows: Volume : 5760 records in one day (2,102,400 per year) (+5 more lines) - You type 7 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
stream() - lines 17โ22
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Product Review Sentiment Classifier - TF-IDF + Logistic Regression (SDG 12)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
texts, labels | lists | Reviews and 1/0 labels |
vec | TfidfVectorizer | ngram_range (1, 2) |
clf | LogisticRegression | Classifier |
words | array | Feature names |
# =====================================================================
# 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")
============================================================
REVIEW SENTIMENT CLASSIFIER (TF-IDF + Logistic Regression)
============================================================
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 1
Reviews: 84 | positive: 42 | negative: 42
Train: 63 | Test: 21
Example +: the jute bag is excellent quality and worth the price
Example -: the jute bag is not good, broke in a week
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 2
Features (words + word pairs): 159
Test accuracy: 1.0
precision recall f1-score support
negative 1.00 1.00 1.00 11
positive 1.00 1.00 1.00 10
accuracy 1.00 21
macro avg 1.00 1.00 1.00 21
weighted avg 1.00 1.00 1.00 21
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 3
Most negative: ['not', 'poor', 'cheap', 'cheap material', 'price cheap', 'not worth', 'leaks', 'happy low']
Most positive: ['quality worth', 'excellent', 'excellent quality', 'good durable', 'durable', 'very good', 'works', 'works perfectly']
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 4
Enter a review: The bamboo toothbrush is excellent and eco friendly
Sentiment: POSITIVE (positive probability 0.84)
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 4
Enter a review: Not good, the steel bottle leaks and broke in a week
Sentiment: NEGATIVE (positive probability 0.12)
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 4
Enter a review: Delivery was quick but the jute bag is poor quality
Sentiment: NEGATIVE (positive probability 0.36)
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 5
Logistic Regression accuracy: 1.0
Naive Bayes accuracy : 1.0
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 6
Sentence: the solar lamp is not worth the price
lamp tf-idf 0.291 coef +0.03
lamp not tf-idf 0.449 coef -0.63
not tf-idf 0.246 coef -2.29
not worth tf-idf 0.400 coef -1.10
price tf-idf 0.328 coef +0.09
solar tf-idf 0.291 coef +0.03
solar lamp tf-idf 0.291 coef +0.03
worth tf-idf 0.328 coef +0.09
worth price tf-idf 0.328 coef +0.09
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 7
Most negative: ['not', 'poor', 'cheap', 'cheap material', 'price cheap', 'not worth', 'leaks', 'happy low']
Most positive: ['quality worth', 'excellent', 'excellent quality', 'good durable', 'durable', 'very good', 'works', 'works perfectly']
Charts saved: review_words.png, review_cm.png, review_probs.png
1.Summary 2.Train 3.Top Words 4.Classify 5.Compare NB 6.TF-IDF Sentence 7.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Build review dataset
- Show menu and read choice
- Model trained? → No: train first
- TF-IDF transform review
- predict_proba
- p >= 0.5? → No: NEGATIVE
- POSITIVE
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Train | Accuracy ~ 1.0 | PASS |
| 2 | Top words | excellent / poor | PASS |
| 3 | 'bamboo toothbrush is excellent' | POSITIVE | PASS |
| 4 | 'not good, bottle leaks' | NEGATIVE | PASS |
| 5 | Compare | Both accuracies | PASS |
| 6 | TF-IDF sentence | Word weights | PASS |
| 7 | Classify 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
- Imports (line 4):
numpy- fast arrays and maths,matplotlib.pyplot- drawing charts,TfidfVectorizer,LogisticRegression,MultinomialNB,train_test_split,accuracy_score,classification_report,confusion_matrixare loaded. - Global variables / constants are created:
products,good,bad,pos,neg,vec,state. - 7 functions are defined (lines 25โ86) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
summary() | 25โ28 | Summary | main program |
train() | 31โ37 | Train | main program |
top_words() | 40โ45 | Top words | charts(), main program |
classify() | 48โ53 | Classify | main program |
compare() | 56โ59 | Compare | main program |
tfidf_sentence() | 62โ67 | Tfidf sentence | main program |
charts() | 70โ86 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: REVIEW SENTIMENT CLASSIFIER (TF-IDF + Logistic Regression) (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
summary()shows: Reviews: 84 | positive: 42 | negative: 42 (+4 more lines) - You type 2 at Enter choice:runs:
train()shows: Features (words + word pairs): 159 (+8 more lines) - 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) - You type 4 at Enter choice:runs:
classify() - You type The bamboo toothbrush is excellent and eco friendly at Enter a review:shows: Sentiment: POSITIVE (positive probability 0.84) (+1 more lines)
- You type 4 at Enter choice:runs:
classify() - 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)
- You type 4 at Enter choice:runs:
classify() - 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)
- You type 5 at Enter choice:runs:
compare()shows: Logistic Regression accuracy: 1.0 (+2 more lines) - You type 6 at Enter choice:runs:
tfidf_sentence() - You type the solar lamp is not worth the price at Sentence:shows: lamp tf-idf 0.291 coef +0.03 (+9 more lines)
- 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) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
summary() - lines 25โ28
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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).
Crop Yield Prediction using the Data Science Methodology (SDG 2)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Rain_mm, Temp_C, Fert_kg, Irrigated, Soil, Yield |
data | DataFrame | One-hot encoded data |
models | dict | LinearRegression, RandomForest |
model | estimator | Best model |
# =====================================================================
# 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")
============================================================
CROP YIELD PREDICTION - DATA SCIENCE METHODOLOGY (SDG 2)
============================================================
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 5
Build the model first (option 4).
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 1
STEP 1 Business understanding : predict wheat yield to plan seeds, credit and storage
STEP 2 Analytic approach : supervised REGRESSION (target = yield, quintal/ha)
STEP 3 Data requirements : rainfall, temperature, fertiliser, irrigation, soil type
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 2
STEP 4 Data collection : 300 plot records (simulated survey)
STEP 5 Data understanding
Rain_mm Temp_C Fert_kg Irrigated Yield
count 288.0 300.0 300.0 300.0 300.0
mean 586.5 21.3 112.2 0.6 37.0
std 109.3 2.5 39.6 0.5 8.0
min 247.0 14.8 40.0 0.0 8.0
25% 514.8 20.0 78.8 0.0 32.4
50% 586.5 21.5 113.0 1.0 37.4
75% 664.0 22.9 147.0 1.0 42.2
max 862.0 28.4 180.0 1.0 55.3
Missing values: {'Rain_mm': 12, 'Temp_C': 0, 'Fert_kg': 0, 'Irrigated': 0, 'Soil': 0, 'Yield': 0}
Correlation with yield: {'Rain_mm': 0.16, 'Temp_C': -0.34, 'Fert_kg': 0.25, 'Irrigated': 0.39}
Average yield by soil: {'average': 36.8, 'good': 41.6, 'poor': 30.9}
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 3
STEP 6 Data preparation: median imputation + one-hot soil
Missing now: 0 | features: ['Rain_mm', 'Temp_C', 'Fert_kg', 'Irrigated', 'Soil_average', 'Soil_good', 'Soil_poor']
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 4
STEP 7 Modeling (5-fold CV RMSE):
Linear Regression 4.932
Random Forest 3.106
STEP 8 Evaluation (hold-out): Random Forest | RMSE 3.344 | R2 0.865
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 5
Rainfall (mm) : 650
Temperature (C) : 22
Fertiliser (kg/ha) : 120
Irrigated (1/0) : 1
Soil (poor/average/good): good
STEP 9 Deployment: predicted yield 49.5 quintal/ha -> about 122 quintal per 2.47 acres
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 5
Rainfall (mm) : 600
Temperature (C) : 21
Fertiliser (kg/ha) : 100
Irrigated (1/0) : 0
Soil (poor/average/good): sandy
Soil must be poor/average/good.
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 6
fertiliser 40 kg/ha -> yield 37.9
fertiliser 60 kg/ha -> yield 38.1
fertiliser 80 kg/ha -> yield 41.2
fertiliser 100 kg/ha -> yield 42.4
fertiliser 120 kg/ha -> yield 41.9
fertiliser 140 kg/ha -> yield 42.6
fertiliser 160 kg/ha -> yield 42.5
fertiliser 180 kg/ha -> yield 42.5
Best fertiliser dose about 140 kg/ha; more than this does not help (diminishing returns).
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 7
STEP 10 Feedback: after harvest, record actual yield of each plot,
compare with prediction, add the new data and retrain every season.
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 8
fertiliser 40 kg/ha -> yield 37.9
fertiliser 60 kg/ha -> yield 38.1
fertiliser 80 kg/ha -> yield 41.2
fertiliser 100 kg/ha -> yield 42.4
fertiliser 120 kg/ha -> yield 41.9
fertiliser 140 kg/ha -> yield 42.6
fertiliser 160 kg/ha -> yield 42.5
fertiliser 180 kg/ha -> yield 42.5
Best fertiliser dose about 140 kg/ha; more than this does not help (diminishing returns).
Charts saved: yield_importance.png, yield_pred.png, yield_fert.png
1.Understand 2.Collect 3.Prepare 4.Model & Evaluate 5.Predict 6.What-if 7.Feedback 8.Charts 0.Exit
Enter choice: 0
Bye!
- Start
- Show methodology menu
- Collect and understand data
- Prepare (impute, encode)
- Cross-validate models
- Model ready? → No: run modeling step
- Predict yield for new plot
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Understanding | 10-step plan | PASS |
| 2 | Collect | 300 rows, 12 missing | PASS |
| 3 | Prepare | 0 missing, 7 features | PASS |
| 4 | Model | RF lower RMSE | PASS |
| 5 | Predict 650, 22, 120, 1, good | Yield in q/ha | PASS |
| 6 | Soil 'sandy' | 'Soil must be poor/average/good' | PASS |
| 7 | What-if | Best fertiliser amount | PASS |
| 8 | Charts | 3 PNG files | PASS |
โ 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
- 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_scoreare loaded. - Global variables / constants are created:
rng,n,df,soil_eff,state. - 8 functions are defined (lines 24โ107) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
understanding() | 24โ27 | Understanding | main program |
collect() | 30โ36 | Collect | main program |
prepare() | 39โ45 | Prepare | model_eval(), main program |
model_eval() | 48โ62 | Model eval | main program |
predict_plot() | 65โ74 | Predict plot | main program |
what_if() | 77โ87 | What if | charts(), main program |
feedback() | 90โ92 | Feedback | main program |
charts() | 95โ107 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: CROP YIELD PREDICTION - DATA SCIENCE METHODOLOGY (SDG 2) (+1 more lines)
- You type 5 at Enter choice:shows: Build the model first (option 4). (+1 more lines)
- 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) - You type 2 at Enter choice:runs:
collect()shows: STEP 4 Data collection : 300 plot records (simulated survey) (+14 more lines) - You type 3 at Enter choice:runs:
prepare()shows: STEP 6 Data preparation: median imputation + one-hot soil (+2 more lines) - You type 4 at Enter choice:runs:
model_eval()shows: STEP 7 Modeling (5-fold CV RMSE): (+4 more lines) - You type 5 at Enter choice:runs:
predict_plot() - You type 650 at Rainfall (mm) :
- You type 22 at Temperature (C) :
- You type 120 at Fertiliser (kg/ha) :
- You type 1 at Irrigated (1/0) :
- 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)
- You type 5 at Enter choice:runs:
predict_plot() - You type 600 at Rainfall (mm) :
- You type 21 at Temperature (C) :
- You type 100 at Fertiliser (kg/ha) :
- You type 0 at Irrigated (1/0) :
- You type sandy at Soil (poor/average/good):shows: Soil must be poor/average/good. (+1 more lines)
- You type 6 at Enter choice:runs:
what_if()shows: fertiliser 40 kg/ha -> yield 37.9 (+9 more lines) - You type 7 at Enter choice:runs:
feedback()shows: STEP 10 Feedback: after harvest, record actual yield of each plot, (+2 more lines) - You type 8 at Enter choice:runs:
charts()โwhat_if()shows: [chart is drawn] (+13 more lines) - You type 0 at Enter choice:shows: Bye!
โค Inside each function - line by line
understanding() - lines 24โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.
Student Dropout Early-Warning System with Data Story (SDG 4)
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
๐ฏ 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
| Name | Type | Purpose |
|---|---|---|
df | DataFrame | Attendance, Marks_change, Distance_km, MDM_meals, Income_k, Dropout |
tree | DecisionTreeClassifier | Early-warning model |
features | list | Model inputs |
rate | Series | Dropout % by attendance band |
# =====================================================================
# 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")
============================================================
DROPOUT EARLY-WARNING SYSTEM (SDG 4)
============================================================
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 3
Train the model first (option 2).
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 1
Students: 500 | at-risk share: 15.0 %
Attendance Marks_change Distance_km MDM_meals Income_k
Dropout
Not at risk 86.0 0.9 2.8 0.5 15.4
At risk 72.3 -4.1 4.3 0.4 13.9
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 2
Decision tree trained (depth 3, balanced classes) on 375 students.
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 3
Confusion matrix [[TN FP] [FN TP]]:
[[93 13]
[ 3 16]]
Recall (at-risk caught) : 0.842
Precision (alerts correct): 0.552
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 4
|--- Attendance <= 77.5
| |--- Income_k <= 19.3
| | |--- Attendance <= 74.5
| | | |--- class: 1
| | |--- Attendance > 74.5
| | | |--- class: 1
| |--- Income_k > 19.3
| | |--- Marks_change <= -4.3
| | | |--- class: 1
| | |--- Marks_change > -4.3
| | | |--- class: 0
|--- Attendance > 77.5
| |--- Distance_km <= 10.8
| | |--- Marks_change <= -1.4
| | | |--- class: 0
| | |--- Marks_change > -1.4
| | | |--- class: 0
| |--- Distance_km > 10.8
| | |--- Distance_km <= 13.2
| | | |--- class: 1
| | |--- Distance_km > 13.2
| | | |--- class: 0
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 5
Attendance % : 62
Change in marks : -10
Distance to school km: 8
Gets mid-day meal 1/0: 0
Family income (k/mo) : 6
Risk probability: 0.94 -> HIGH RISK
Warning signs: low attendance, falling marks, lives far from school, not taking mid-day meals, low family income
Action: call parents, remedial classes, check transport / scholarship support.
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 5
Attendance % : 95
Change in marks : 5
Distance to school km: 1
Gets mid-day meal 1/0: 1
Family income (k/mo) : 20
Risk probability: 0.03 -> LOW RISK
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 6
Student Attendance Marks_change Distance_km MDM_meals Income_k Risk_prob
S389 78.0 2.3 11.3 1 6.9 0.97
S147 81.0 -7.0 12.4 0 11.6 0.97
S214 81.0 -4.1 10.9 1 12.1 0.97
S119 83.0 0.6 13.1 0 14.5 0.97
S109 84.0 -0.7 11.7 0 13.4 0.97
S138 91.0 2.9 13.0 0 8.5 0.97
S361 54.0 -13.9 9.4 1 9.4 0.94
S365 57.0 -3.2 0.8 1 18.6 0.94
S178 60.0 -2.2 3.1 0 19.3 0.94
S327 60.0 0.7 0.9 0 8.9 0.94
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 7
SETUP : 1 in 7 students in our data is at risk of dropping out.
INSIGHT : risk is 71 % when attendance is below 70 %, but only 1 % above 90 %.
Mid-day meal takers: risk 13 % vs 17 % for others.
ACTION : weekly attendance follow-up, remedial classes when marks fall,
ensure every eligible child receives mid-day meals.
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 8
Charts saved: dropout_story.png, dropout_importance.png, dropout_meals.png
1.Overview 2.Train 3.Evaluate 4.Rules 5.Check Student 6.Top-10 7.Data Story 8.Charts 0.Exit
Enter choice: 0
Every child in school!
- Start
- Create student data
- Show menu and read choice
- Model trained? → No: train first
- Read student details
- Predict risk probability
- Probability >= 0.5? → No: LOW risk
- HIGH risk + reasons + action
- Choice is 0? → No: show menu
- Stop
| # | Test case / input | Expected result | Status |
|---|---|---|---|
| 1 | Overview | 500 students, 15 % at risk | PASS |
| 2 | Evaluate | Recall high | PASS |
| 3 | Rules | Attendance first split | PASS |
| 4 | Student 62 %, -10, 8 km, no meal, 6k | HIGH risk | PASS |
| 5 | Student 95 %, +5, 1 km, meal, 20k | LOW risk | PASS |
| 6 | Top-10 | List of students | PASS |
| 7 | Story | 3-part story | PASS |
โ 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
- 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_matrixare loaded. - Global variables / constants are created:
rng,n,df,risk,features,state. - 8 functions are defined (lines 25โ87) - Python stores them but does NOT run them yet.
- 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
| Function | Lines | What it does | Called from |
|---|---|---|---|
overview() | 25โ27 | Overview | main program |
train() | 30โ32 | Train | main program |
evaluate() | 35โ39 | Evaluate | main program |
rules() | 42โ43 | Rules | main program |
check() | 46โ60 | Check | main program |
top10() | 63โ65 | Top10 | main program |
story() | 68โ75 | Story | main program |
charts() | 78โ87 | Charts | main program |
โข Main program - line by line
| Line | Code | What 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.
- โถ Program startsshows: DROPOUT EARLY-WARNING SYSTEM (SDG 4) (+1 more lines)
- You type 3 at Enter choice:shows: Train the model first (option 2). (+1 more lines)
- You type 1 at Enter choice:runs:
overview()shows: Students: 500 | at-risk share: 15.0 % (+5 more lines) - You type 2 at Enter choice:runs:
train()shows: Decision tree trained (depth 3, balanced classes) on 375 students. (+1 more lines) - You type 3 at Enter choice:runs:
evaluate()shows: Confusion matrix [[TN FP] [FN TP]]: (+5 more lines) - You type 4 at Enter choice:runs:
rules()shows: |--- Attendance <= 77.5 (+22 more lines) - You type 5 at Enter choice:runs:
check() - You type 62 at Attendance % :
- You type -10 at Change in marks :
- You type 8 at Distance to school km:
- You type 0 at Gets mid-day meal 1/0:
- You type 6 at Family income (k/mo) :shows: Risk probability: 0.94 -> HIGH RISK (+3 more lines)
- You type 5 at Enter choice:runs:
check() - You type 95 at Attendance % :
- You type 5 at Change in marks :
- You type 1 at Distance to school km:
- You type 1 at Gets mid-day meal 1/0:
- You type 20 at Family income (k/mo) :shows: Risk probability: 0.03 -> LOW RISK (+1 more lines)
- You type 6 at Enter choice:runs:
top10()shows: Student Attendance Marks_change Distance_km MDM_meals Income_k Risk_prob (+11 more lines) - 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) - You type 8 at Enter choice:runs:
charts()shows: [chart is drawn] (+4 more lines) - You type 0 at Enter choice:shows: Every child in school!
โค Inside each function - line by line
overview() - lines 25โ27
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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
| Line | Code | What 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.