File Operations, Database Interaction, and Algorithm Efficiency

366 viewsG13-09 AL ICT Python Programming
0

  1. What are the basic file operations in Python?

  2. Write a Python program to write a string to a file and read it back.

  3. How can Python connect to a MySQL database to retrieve data?

  4. What is sequential search, and when is it used?

  5. Write a Python program to implement bubble sort on a list of numbers.

Ruwan Suraweera Changed status to publish
0

Answers and Descriptions:

  1. 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.

  2. 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”).

  3. 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.

  4. 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.

  5. 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.

Ruwan Suraweera Changed status to publish
🔴 Lesson List
SIDE BUTTON ON
Sign In Register
×

👋 Welcome Back!

🚀
Ready to Learn?Pick up where you left off.
🔑
Forgot Password?Click the link below to reset.
📢
New FeaturesCheck out the new AI Voice tool.

Sign In

👤
🔒
or continue with
Google Facebook

Already have an account? Register Now