Python Programs and MySQL Queries for Grade 12
Python Programs and MySQL Queries for Grade 12
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.