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:
1234567# Write to filewith open("sample.txt", "w") as file:file.write("Hello, Grade 13!")# Read from filewith 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:123456import mysql.connectorconn = 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:
123456789def 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 arrnumbers = [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.