What are the basic file operations in Python?
Write a Python program to write a string to a file and read it back.
How can Python connect to a MySQL database to retrieve data?
What is sequential search, and when is it used?
Write a Python program to implement bubble sort on a list of numbers.
Answers and Descriptions:
Answer: Open, close, read, write, append.
Description: These operations allow file handling in Python. open() accesses a file, read()/write()/append() manipulates content, and close() releases resources.Answer:
# Write to file with open("sample.txt", "w") as file: file.write("Hello, Grade 13!") # Read from file with open("sample.txt", "r") as file: content = file.read() print(content)Description: The program uses with to safely open a file, writes a string in write mode (“w”), and reads it back in read mode (“r”).
Answer: Use the mysql.connector module to connect, execute SQL queries, and fetch data.
Description: Example:import mysql.connector conn = mysql.connector.connect(host="localhost", user="root", password="pass", database="school") cursor = conn.cursor() cursor.execute("SELECT * FROM students") print(cursor.fetchall()) conn.close()This connects to a MySQL database, retrieves all records from the students table, and closes the connection.
Answer: Sequential search checks each element in a list until the target is found or the list ends.
Description: It’s simple but inefficient for large datasets, used when data is unsorted or small.Answer:
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr numbers = [64, 34, 25, 12, 22] print("Sorted:", bubble_sort(numbers))Description: Bubble sort compares adjacent elements and swaps them if out of order, repeating until sorted. It’s simple but inefficient for large lists.