0% found this document useful (0 votes)
42 views3 pages

Python Programs and MySQL Queries for Grade 12

Uploaded by

arnavb0902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views3 pages

Python Programs and MySQL Queries for Grade 12

Uploaded by

arnavb0902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

List of Python file programs Grade 12

Part A – Python Programs

For separate programs follow the list and given links:

1. Write a program to find the sum and average of list in python.

2. Write a program to remove duplicates from the dictionary.

3. Write a program to define a function to accept two integers m and n respectively as


argument and display prime numbers between them.

4. Write a program to compute interest based on different arguments given in the function.

5. Write a program to largest element in a list using a function. Pass list object as argument.

6. Write a program to count the number of vowels in passed string to the function.

7. Write a program to take two integers and perform addition of two numbers handle exception
when non-integers entered by user.

8. Write a program to find the square root of a positive number, raise a custom exception when
user enters a non-integer number.

9. Write a program to replace entered word from a text file [Link].

10. Write a menu driven program to store and manipulate data in binary file to insert, update,
delete and display records. The data has following structure:
Data Represents – Patient Information
Dictionary – {‘P_ID’:101,’P_Name’:’Shiv’,’Charges’:25000}
File Name – [Link]
Menu:
1 – Add Patient
2 – Display Patient
3 – Search Patient
4 – Update Patient
5 – Delete Patient
6 – Exit

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

12. Write a program to create a binary file [Link] which stores the following information
in list as follows:
Structure of Data:
Candidate_id – Integer
Candidate_Name – String
Designation – String
Experience – Float
(i) Write a function append() to write data into binary file.
(ii) Write a function display() to display data from binary file for all candidates whose
experience is more than 10.
13. Write a program to generate a CSV file named [Link]. Each record of CSV contains
these data:
Name of the country -String
Population of country – Integer
No. people participated in survey – Integer
No. of people who are Happy – Integer
Write user defined functions to do the following:
1 – Insert records into CSV
2 – Display records from CSV
3 – Update record
4 – Delete record

14. Write a menu drive program for stack operations.

15. Write a program to Push an item into stack where a dictionary contains the details of
stationary items as follows: stn = {“Shirt”:700,”T-Shirt”:750,”Jeans”:1150,”Trouser”:400}

(a) Write a function to push an element into stack for those items names whose price is more than
850.

Part B – MySQL Queries

As per CBSE syllabus of Computer Science 5 sets of MySQL queries are required in your practical file.
I have taken these 5 sets:

1. Set 1 – Based on Database basic commands

o Create a database named practical_2025

o Check the database is created or not

o Open a database

o Create a database emp

o Delete Database emp

2. Set 2 – Based on DDL commands

o Create a table and insert data

o Show the structure of table

o Add a column

o Modify a column

o Rename a column

o Delete a column

3. Set 3 – Select SQL Queries including SQL query

o Artihmatic operator

o In operator
o Between Operator

o Like operator

o null operator

o order by

4. Set 4 – Group by, having aggregate functions

o Group by Query

o Distinct Keyword

o Aggregate function max()

o Aggregate function avg()

o Group by and Having

5. Set 5 – Join Queries

o Display cartesian product

o Equijoin

o Natural Join

o Where condition in join

o Using alias names

Part C – MySQL & Python Connectivity Programs

Part C of Practical file contains MySQL & Python Connectivity Programs. These programs are as
follows:

1. Write a program to connect with mysql database and insert a record into database.

2. Write a program to connect with mysql database and update a record into database.

3. Write a program to connect with mysql database and delete a record into database.

4. Write a program to connect with mysql database display record of particular label under the
artist is working.

Common questions

Powered by AI

In SQL, joins are used to combine rows from two or more tables based on a related column between them. Common types of joins include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN. An INNER JOIN returns records that have matching values in both tables. Example: ```sql SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2 ON table1.id = table2.id; ``` LEFT JOIN returns all records from the left table, and the matched records from the right. RIGHT JOIN does the opposite, and FULL JOIN returns all records when there is a match on either side of the join condition. Joins are important for querying data spanning multiple tables and can be customized with conditions to filter results.

CSV files in Python are managed using the csv module, which facilitates reading from and writing to CSV files conveniently. To generate and manipulate these files, typical operations include creating a CSV writer or reader object with open(filename, 'mode') as file, configuring a csv.writer() or csv.reader(), and iteratively writing rows or reading data. Example to write records: ```python import csv def write_to_csv(file_name, records): with open(file_name, mode='w', newline='') as file: writer = csv.writer(file) for record in records: writer.writerow(record) ``` This approach allows recording insertions, updates, and deletions by modifying the list of records and re-writing the whole file. Reading with csv.reader() iterates over rows for suitable manipulations.

To remove duplicate entries in a Python dictionary, you can use a dictionary comprehension along with the fromkeys() method of dictionaries. This works because dictionaries cannot store duplicate keys; when fromkeys() encounters duplicate entries, it overwrites the existing value with the new one. Example code: ```python dict_with_duplicates = {'a': 1, 'b': 2, 'a': 1, 'c': 2} dict_without_duplicates = dict.fromkeys(dict_with_duplicates) print(dict_without_duplicates) ``` This results in {'a': 1, 'b': 2, 'c': 2}, effectively removing duplicates by unique keys.

To write a Python program for calculating the sum and average of a list, you can use the built-in functions sum() and len(). First, calculate the sum using sum(), then divide by the number of elements in the list using len() to get the average. Example: ```python my_list = [10, 20, 30, 40, 50] sum_of_list = sum(my_list) average = sum_of_list / len(my_list) print(f'Sum: {sum_of_list}, Average: {average}') ```

The Group By clause in SQL allows aggregation of rows with the same values in specified columns into summary rows, typically using aggregate functions like SUM(), AVG(), COUNT(), etc. It organizes similar data into groups, making analysis more manageable by summarizing information. The Having clause is similar to WHERE but used with aggregate functions to filter aggregated data. For example: ```sql SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 10; ``` This query groups employees by department and displays only those departments with more than ten employees. Group By and Having thus enable complex data grouping and conditional filtering of grouped results pivotal in data-driven decision-making.

To create a binary file in Python for managing patient information, you can use the pickle module to serialize the dictionary data representing patients into a binary form. You can implement functions to add, update, delete, and display records using a menu-driven program. Example functions could include reading and writing patient dictionaries to/from a file, checking for the existence of a record based on 'P_ID', and updating dictionary keys and values accordingly. Here's a basic structure: ```python import pickle def load_patients(file): try: with open(file, 'rb') as f: return pickle.load(f) except FileNotFoundError: return {} def save_patients(file, patients): with open(file, 'wb') as f: pickle.dump(patients, f) patients = load_patients('patient.dat') # Functions to add, display, update, and delete patients as needed # Use save_patients to write back data to the file after any change ``` This approach allows the use of menus to call respective functions for CRUD operations.

A menu-driven Python program for stack operations can efficiently manage pushing and popping elements, especially those stored in dictionaries. For this, define a dictionary stack and functions to perform push, pop, and display operations. Users can select operations via a menu displayed in a loop. Here is a simple implementation: ```python def push(stack, item): stack.append(item) def pop(stack): if stack: return stack.pop() else: print("Stack is empty.") stack = [] items = {"Shirt":700, "T-Shirt":750, "Jeans":1150, "Trouser":400} while True: choice = input("Enter 1 to Push, 2 to Pop, 3 to Display, 4 to Exit: ") if choice == '1': for item, cost in items.items(): if cost > 850: push(stack, (item, cost)) elif choice == '2': pop(stack) elif choice == '3': print(stack) elif choice == '4': break else: print("Invalid choice.") ``` This allows users to interactively perform and verify operations on the stack according to the given conditions.

To write a Python function that returns all prime numbers between two integers m and n, you can use a loop to iterate between m and n and check each number's primality. A number is prime if it's greater than 1 and not divisible by any number other than 1 and itself. Example code: ```python def find_primes(m, n): primes = [] for num in range(m, n + 1): if num > 1: for i in range(2, int(num**0.5) + 1): if (num % i) == 0: break else: primes.append(num) return primes primes = find_primes(10, 50) print(primes) ``` This example will return prime numbers between m and n, optimizing by checking divisibility up to the square root of num.

Exception handling in Python for user inputs can be implemented using try-except blocks. When performing operations like addition, you can catch specific exceptions like ValueError to handle cases where a non-integer input is provided. Example code: ```python def add_two_numbers(): try: a = int(input("Enter first integer: ")) b = int(input("Enter second integer: ")) print(f"Sum is: {a + b}") except ValueError: print("Invalid input. Please enter integers only.") add_two_numbers() ``` In this function, if the user enters a non-integer, ValueError is caught, and a message is displayed, allowing the program to continue running instead of crashing.

MySQL and Python connectivity is commonly accomplished using the mysql-connector-python library, which allows Python scripts to interact with MySQL databases. To insert and update records, you establish a connection to the MySQL server using this library, then execute SQL commands through a cursor object. Upon execution, changes are committed using the commit() method. Example: ```python import mysql.connector def connect_to_database(): connection = mysql.connector.connect( host="localhost", user="username", password="password", database="database_name" ) return connection # For insertion connection = connect_to_database() cursor = connection.cursor() cursor.execute("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')") connection.commit() # For updating cursor.execute("UPDATE table_name SET column1 = 'value1' WHERE condition") connection.commit() connection.close() ``` This example demonstrates opening a connection, performing operations, and closing the connection securely.

You might also like