2025 CBSE Class 12 Computer Science Question Paper with Detailed Solutions

As the CBSE board exams approach, students across the country are gearing up for one of the most important assessments of their academic journey. To help Class 12 Computer Science students prepare effectively, we have provided the 2025 CBSE Computer Science question paper along with detailed solutions. These solutions are designed to guide students through each question, offering clear explanations and insights to enhance their understanding and exam readiness.

Section A – Multiple Choice Questions (1 mark each)

  1. State True or False : “A Python List must always contain all its elements of same data type.”
    Answer
    Answer: False
    Explanation: Python lists are heterogeneous collections. A single list can hold elements of different data types such as integers, strings, floats, or even other lists. For example, L=[1,”abc”,3.5] is perfectly valid. Hence the statement that all elements must be of the same data type is false.
  2. What will be the output of the following statement ?
    print(14%3**2*4)
    (A) 16 (B) 64 (C) 20 (D) 256
    Answer
    Answer: 20
    Explanation: Operator precedence in Python:
    Exponentiation **
    Modulus % and Multiplication * (left to right among same level)Stepwise evaluation:
    3**2 = 9
    14 % 9 = 5 (remainder when 14 is divided by 9)
    5 * 4 = 20
    Therefore the final output is 20.
  3. Identify the correct output of the following code snippet :
    game="Olympic2024"
    print(game.index("C"))

    (A) 0 (B) 6 (C) -1 (D) ValueError

    Answer
    Answer: 6
    Explanation: String indexing starts from 0. The string “Olympic2024” has characters:
    O(0) l(1) y(2) m(3) p(4) i(5) c(6) 2(7) 0(8) 2(9) 4(10)
    The uppercase C appears at index 6. index() returns the position of the first occurrence. So the output is 6.
  4. Which of the following is the correct identifier ?
    (A) global (B) Break (C) def (D) with
    Answer
    Answer: Break
    Explanation: Python identifiers cannot be keywords. Options like global, def, and with are all Python keywords. However, the question asks which is a correct identifier name to be used by a programmer. Among given choices:
    global is a keyword.
    Break (with capital B) is not a keyword because Python keywords are lowercase. So Break is a valid identifier.
    def and with are keywords and cannot be used as identifiers.
    On careful inspection, the only name that is not a reserved word in the exact given case is Break (capital B). Hence the correct answer is Break.
  5. Identify the invalid Python statement out of the following options :
    (A) print(“A”,10,end=”*”)
    (B) print(“A”,sep=”*”,10)
    (C) print(“A”,10,sep=”*”)
    (D) print(“A”*10)
    Answer
    Answer: (B) print(“A”,sep=”*”,10)
    Explanation: The order of arguments in a print() function call must be positional arguments first, followed by keyword arguments.
    (A) Positional “A”,10 followed by keyword end=”*” → Valid.
    (B) Keyword sep=”*” comes first, followed by positional 10 → Invalid because positional argument cannot follow keyword argument.
    (C) Positional arguments first, then keyword sep=”*” → Valid.
    (D) Multiplying string → Valid.
    Hence (B) is invalid.
  6. Consider the statements given below and then choose the correct output from the given options :
    L=['TIC', 'TAC']
    print(L[::-1])

    (A) [‘CIT’, ‘CAT’] (B) [‘TIC’, ‘TAC’] (C) [‘CAT’, ‘CIT’] (D) [‘TAC’, ‘TIC’]

    Answer
    Answer: (D) [‘TAC’, ‘TIC’] Explanation: The slice [::-1] reverses the list. Original list is [‘TIC’,’TAC’]. Reversing it gives [‘TAC’,’TIC’].
  7. Which of the following operator evaluates to True if the variable on either side of the operator points towards the same memory location and False otherwise ?
    (A) is (B) is not (C) and (D) or
    Answer
    Answer: is
    Explanation: The is operator checks object identity, i.e., whether two references point to the same object in memory. Therefore the correct answer is is.
  8. Consider the statements given below and then choose the correct output from the given options :
    D={'S01':95, 'S02':96 }
    for I in D :
        print(I,end='#')

    (A) S01#S02# (B) 95#96# (C) S01,95#S02,96# (D) S01#95#S02#96#

    Answer
    Answer: (A) S01#S02#
    Explanation: Iterating over a dictionary directly yields its keys. So for I in D will give ‘S01’ and ‘S02′. Printing them with end=’#’ prints S01#S02# (order of keys is preserved as insertion order in modern Python versions).
  9. While creating a table, which constraint does not allow insertion of duplicate values in the table ?
    (A) UNIQUE (B) DISTINCT (C) NOT NULL (D) HAVING
    Answer
    Answer: UNIQUE
    Explanation: The UNIQUE constraint ensures that all values in a column are different. DISTINCT is used in SELECT queries, NOT NULL only prevents nulls, and HAVING is used with GROUP BY. So UNIQUE is correct.
  10. Consider the statements given below and then choose the correct output from the given options :
    def Change(N):
        N=N+10
        print(N,end='$$')
    N=15
    Change(N)
    print(N)

    (A) 25$$15 (B) 1525 (C) 25$$25 (D) 2525

    Answer
    Answer: 25$$15
    Explanation: Inside the function Change, N is a local variable.
    Steps:
    Initial N = 15
    Call Change(N): inside function N becomes 25 and prints 25$$.
    After function call, N outside remains 15 and is printed next.
    So the output is 25$$15.
  11. Consider the statements given below and then choose the correct output from the given options :
    N='5'
    try:
        print('WORD' + N, end='#')
    except:
        print('ERROR',end='#')
    finally:
        print('OVER')

    (A) ERROR# (B) WORD5#OVER (C) WORD5# (D) ERROR#OVER

    Answer
    Answer: WORD5#OVER
    Explanation: The try block concatenates string ‘WORD’ with string ‘5’, which is valid and prints WORD5#. No exception occurs. Then the finally block executes and prints OVER. Hence the combined output is WORD5#OVER.
  1. Which of the following built-in function/method returns a dictionary ?
    (A) dict() (B) keys() (C) values() (D) items()
    Answer
    Answer: (A) dict()
    Explanation: dict() is a built-in function that can create and return a dictionary object, e.g. dict(a=1,b=2) → {‘a’:1,’b’:2}.
    keys(), values(), and items() are dictionary methods that return view objects (keys view, values view, items view), not a new dictionary itself. Hence dict() is correct.
  2. Which of the following is a DML command in SQL ?
    (A) UPDATE (B) CREATE (C) ALTER (D) DROP
    Answer
    Answer: (A) UPDATE
    Explanation: Data Manipulation Language (DML) commands are used to modify data inside tables (INSERT, UPDATE, DELETE, SELECT).
    CREATE and ALTER are Data Definition Language (DDL) commands.
    DROP is also DDL. Therefore UPDATE is the only DML command here.
  3. Which aggregate function in SQL displays the number of values in the specified column ignoring the NULL values ?
    (A) len() (B) count() (C) number() (D) num()
    Answer
    Answer: (B) count()
    Explanation: The SQL COUNT(column_name) function returns the number of non-NULL entries in that column. Other options like len(), number(), or num() are not valid SQL aggregate functions.
  4. In MYSQL, which type of value should not be enclosed within quotation marks ?
    (A) DATE (B) VARCHAR (C) FLOAT (D) CHAR
    Answer
    Answer: (C) FLOAT
    Explanation: Numeric data types like INT, FLOAT, DECIMAL are stored without quotes.
    DATE values are enclosed in quotes (e.g. ‘2025-09-18’).
    VARCHAR and CHAR are character types and require quotes.
    FLOAT is a numeric type and must not be enclosed in quotes.
  5. State True or False :
    If table A has 6 rows and 3 columns, and table B has 5 rows and 2 columns, the Cartesian product of A and B will have 30 rows and 5 columns.
    Answer
    Answer: True
    Explanation: The Cartesian product multiplies the number of rows and adds the number of columns:
    Rows = 6 × 5 = 30
    Columns = 3 + 2 = 5
    Hence the statement is true.
  6. Which of the following networking devices is used to regenerate and transmit the weakened signal ahead ?
    (A) Hub (B) Ethernet Card (C) Repeater (D) Modem
    Answer
    Answer: (C) Repeater
    Explanation: A repeater regenerates and amplifies signals in a network to extend transmission distance. Hubs only distribute signals, Ethernet cards connect computers to networks, and modems modulate/demodulate signals for internet access.
  7. Which of the following options is the correct protocol used for phone calls over the internet ?
    (A) PPP (B) FTP (C) HTTP (D) VoIP
    Answer
    Answer: (D) VoIP
    Explanation: VoIP (Voice over Internet Protocol) is specifically designed for voice communication over IP networks (e.g. Skype, WhatsApp calls). PPP, FTP, and HTTP serve different purposes (point-to-point connection, file transfer, web pages respectively).
  8. Expand ARPANET.
    Answer
    Answer: Advanced Research Projects Agency Network
    Explanation: ARPANET was the pioneering packet-switching network developed by the U.S. Department of Defense’s Advanced Research Projects Agency (ARPA). It is regarded as the foundation of today’s internet.
  9. Assertion (A): For a binary file opened using ‘rb’ mode, the pickle.dump() method will display an error.
    Reason (R): The pickle.dump() method is used to read from a binary file.
    Options:
    (A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
    (B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
    (C) Assertion (A) is true but, Reason (R) is false.
    (D) Assertion (A) is false but, Reason (R) is true.
    Answer
    Answer: (C) Assertion (A) is true but, Reason (R) is false.
    Explanation: pickle.dump() writes Python objects to a binary file and requires the file to be opened in write-binary mode (‘wb’ or ‘ab’).
    If the file is opened in read-binary mode (‘rb’), attempting to dump will raise an error.
    But Reason (R) claims pickle.dump() is used to read, which is wrong (reading uses pickle.load()). Hence Assertion is true and Reason is false.
  10. Assertion (A): We can retrieve records from more than one table in MYSQL.
    Reason (R): Foreign key is used to establish a relationship between two tables.
    Options:
    (A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
    (B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
    (C) Assertion (A) is true but, Reason (R) is false.
    (D) Assertion (A) is false but, Reason (R) is true.
    Answer
    Answer: (A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
    Explanation: SQL allows retrieving records from multiple tables using JOIN operations.
    A foreign key establishes the relationship that enables these joins. So both the assertion and the reason are true, and the reason correctly explains the assertion.

Section B

  1. What does the return statement do in a function ? Explain with the help of an example.
    Answer
    Answer: The return statement sends a value from a function back to the point where the function was called and ends the function’s execution.

    Explanation: In Python, return is used when a function needs to give back a result. Without a return, the function produces no value (returns None by default).
    Example:

    def add(a,b):
        s = a + b
        return s
    
    result = add(5,3)
    print(result)   # Output: 8

    Here, return s sends the computed sum back to the caller. Execution stops after the return line.

  2. Write one example of each of the following in Python :
    (i) Syntax Error
    (ii) Implicit Type Conversion
    Answer
    Answer:
    (i) Syntax Error example:
    if True print("Hello")

    (missing colon after True causes a syntax error)

    (ii) Implicit Type Conversion example:

    x = 5        # int
    y = 2.5      # float
    z = x + y    # z becomes 7.5 (float)

    Explanation: A syntax error occurs when Python’s parser encounters code that breaks the language rules, such as missing colons, unmatched parentheses, or wrong indentation.
    Implicit type conversion (type coercion) is automatic data type conversion by Python. In the example, integer 5 is converted to float and the result 7.5 is of type float.

  3. Consider the following dictionaries, D and D1 :
    D={"Suman":40, "Raj":55, "Raman":60}
    D1={"Aditi":30, "Amit":90,"Raj":20}

    (Answer using built-in Python functions only)

    (i) (a) Write a statement to display/return the value corresponding to the key “Raj” in the dictionary D.
    OR
    (b) Write a statement to display the length of the dictionary D1.

    (ii) (a) Write a statement to append all the key-value pairs of the dictionary D to the dictionary D1.
    OR
    (b) Write a statement to delete the item with the given key “Amit” from the dictionary D1.

    Answer
    Answer:
    (i) (a) print(D.get("Raj"))
    Explanation: .get() returns the value for the given key safely (or None if not found).

    OR

    (i) (b) print(len(D1))
    Explanation: len() returns the number of key-value pairs in the dictionary.

    (ii) (a) D1.update(D)
    Explanation: .update() adds all key-value pairs from D to D1, replacing existing keys if needed.

    OR

    (ii) (b) D1.pop("Amit")
    Explanation: .pop() deletes the specified key and its value.

  4. What possible output from the given options is expected to be displayed when the following code is executed ?
    import random
    Cards=["Heart","Spade","Club","Diamond"]
    for i in range(2):
        print(Cards[random.randint(1,i+2)],end="#")

    (A) Spade#Diamond# (B) Spade#Heart# (C) Diamond#Club# (D) Heart#Spade#

    Answer
    Answer: (A) Spade#Diamond#
    Explanation: The for loop runs twice: i=0 and i=1.

    Iteration 1: random.randint(1,0+2) = randint(1,2). Possible indices = 1 or 2 → Card can be Spade or Club.
    Iteration 2: random.randint(1,1+2) = randint(1,3). Possible indices = 1, 2, or 3 → Card can be Spade, Club, or Diamond.
    Among the given options, only Spade#Diamond# fits one likely outcome consistent with index ranges. Other listed combinations either start with Heart (index 0, not possible in first iteration) or violate index ranges.

  5. The code given below accepts N as an integer argument and returns the sum of all integers from 1 to N. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
    def Sum(N)
        for I in range(N):
            S=S+I
        return S
    print(Sum(10))
    Answer
    Answer (corrected code):
    def Sum(N):
        S = 0
        for I in range(1, N+1):
            S = S + I
        return S
    
    print(Sum(10))

    Explanation:
    Corrections:
    1. Added colon : after def Sum(N) (syntax fix).
    2. Initialized S=0 before using it.
    3. Changed range(N) to range(1, N+1) to include N in the sum.
    Now the function correctly returns 55 for N=10.

  6. Nisha is assigned the task of maintaining the staff data of an organization. She has to store the details of the staff in the SQL table named EMPLOYEES with attributes as EMPNO, NAME, DEPARTMENT, BASICSAL to store Employee’s Identification Number, Name, Department, and Basic Salary respectively. There can be two or more Employees with the same name in the organization.

    (i) (a) Help Nisha to identify the attribute which should be designated as the PRIMARY KEY. Justify your answer.
    OR
    (b) Help Nisha to identify the constraint which should be applied to the attribute NAME such that the Employees’ Names cannot be left empty or NULL while entering the records but can have duplicate values.

    (ii) (a) Write the SQL command to change the size of the attribute BASICSAL in the table EMPLOYEES to allow the maximum value of 99999.99 to be stored in it.
    OR
    (b) Write the SQL command to delete the table EMPLOYEES.

    Answer
    Answer:
    (i) (a) Attribute: EMPNO
    Justification: EMPNO uniquely identifies each employee and is the natural primary key.

    OR

    (i) (b) Constraint: NOT NULL
    Explanation: Applying NOT NULL on NAME ensures no record can have an empty name while allowing duplicates.

    (ii) (a) ALTER TABLE EMPLOYEES MODIFY BASICSAL DECIMAL(7,2);
    Explanation: This allows up to 5 digits before decimal and 2 after, covering 99999.99.

    OR

    (ii) (b) DROP TABLE EMPLOYEES;
    Explanation: Completely deletes the table structure and data.

  7. (a) Expand and explain the term URL.
    OR
    (b) Expand the term PPP. What is the use of PPP ?
    Answer
    Answer:
    (a) URL stands for Uniform Resource Locator. It is the complete web address used to locate a resource on the Internet, consisting of protocol, domain name, and path (for example, https://www.example.com/page).

    OR

    (b) PPP stands for Point to Point Protocol. PPP is used to establish a direct connection between two nodes over serial links such as telephone lines, enabling transmission of data packets including IP packets.

Section C

  1. (a) Write a Python function that displays all the lines containing the word ‘vote’ from a text file “Elections.txt”. For example, if the file contains :
    In an election many people vote to choose their representative.
    The candidate getting the maximum share of votes stands elected.
    Normally, one person has to vote once.
    The process of voting may vary with time and region.
    Then the output should be :
    In an election many people vote to choose their representative.
    Normally, one person has to vote once.

    OR

    (b) Write a Python function that displays all the words starting and ending with a vowel from a text file “Report.txt”. The consecutive words should be separated by a space in the output. For example, if the file contains :
    Once there was a wise man in a village.
    He was an awesome story-teller.
    He was able to keep people anchored while listening to him.
    Then the output should be :
    Once a a awesome able

    Answer
    Answer:
    (a) See function below.
    import re
    
    def show_vote_lines():
        pat = re.compile(r'\bvote\b', re.IGNORECASE)   # whole word vote
        with open("Elections.txt", "r", encoding="utf-8") as f:
            for line in f:
                if pat.search(line):
                    print(line.rstrip())

    Explanation:
    i) The requirement is to print only those lines that contain the whole word vote, not votes or voting.
    ii) We can scan each line and test using a word boundary check. A simple way is a regular expression with pattern r’\bvote\b’ and case-insensitive matching.
    iii) For each matching line, print it as is. This prints exactly the two lines shown in the example and skips the lines with votes and voting.

    OR

    (b) See function below.

    import re
    
    def start_end_vowel_words():
        pat = re.compile(r'\b[aeiouAEIOU][A-Za-z]*[aeiouAEIOU]\b')
        out = []
        with open("Report.txt", "r", encoding="utf-8") as f:
            for line in f:
                out.extend(pat.findall(line))
        print(" ".join(out))

    Explanation:
    i) We must pick words whose first and last characters are vowels.
    ii) Use a regex r’\b[aeiouAEIOU][A-Za-z]*[aeiouAEIOU]\b’ to capture such words.
    iii) Collect all matches in order and print them joined with a single space. This yields the sample output: Once a a awesome able.

  2. (a) A stack, named ClrStack, contains records of some colors. Each record is represented as a tuple containing four elements – ColorName, RED, GREEN, BLUE. ColorName is a string, and RED, GREEN, BLUE are integers. For example, a record in the stack may be (‘Yellow’, 237, 250, 68). Write the following user-defined functions in Python to perform the specified operations on ClrStack:
    (i) push_Clr(ClrStack, new_Clr) : This function takes the stack ClrStack and a new record new_Clr as arguments and pushes this new record onto the stack.
    (ii) pop_Clr(ClrStack) : This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display the message “Underflow”.
    (iii) isEmpty(ClrStack) : This function checks whether the stack is empty. If the stack is empty, the function should return True, otherwise the function should return False.

    OR

    (b) Write the following user-defined functions in Python :
    (i) push_trail(N,myStack) : Here N and myStack are lists, and myStack represents a stack. The function should push the last 5 elements from the list N onto the stack myStack. For example, if the list N is [1,2,3,4,5,6,7], then the function push_trail() should push the elements 3,4,5,6,7 onto the stack. Therefore the value of stack will be [3,4,5,6,7]. Assume that N contains at least 5 elements.
    (ii) pop_one(myStack) : The function should pop an element from the stack myStack, and return this element. If the stack is empty, then the function should display the message ‘Stack Underflow’, and return None.
    (iii) display_all(myStack) : The function should display all the elements of the stack myStack, without deleting them. If the stack is empty, the function should display the message ‘Empty Stack’.

    Answer
    Answer:
    (a) See functions below.
    def push_Clr(ClrStack, new_Clr):
        ClrStack.append(new_Clr)
    
    def pop_Clr(ClrStack):
        if len(ClrStack) == 0:
            print("Underflow")
            return None
        return ClrStack.pop()
    
    def isEmpty(ClrStack):
        return len(ClrStack) == 0

    Explanation:
    i) Represent the stack as a Python list with the top at the right end.
    ii) Pushing uses append.
    iii) Popping uses pop with an empty check.
    iv) Emptiness is tested by length or truth value.

    OR

    (b) See functions below.

    def push_trail(N, myStack):
        myStack.extend(N[-5:])     # adds [3,4,5,6,7] to top in order
    
    def pop_one(myStack):
        if not myStack:
            print("Stack Underflow")
            return None
        return myStack.pop()
    
    def display_all(myStack):
        if not myStack:
            print("Empty Stack")
        else:
            print(*myStack)

    Explanation:
    i) The last five elements of N are N[-5:]. Pushing them in order onto the stack means appending that slice.
    ii) Popping and displaying follow the usual stack rules.

  3. (a) Predict the output of the following code :
    def ExamOn(mystr) :
        newstr = ""
        count = 0
        for i in mystr:
            if count%2 != 0:
                newstr = newstr + str(count-1)
            else:
                newstr = newstr + i.lower()
            count += 1
        newstr = newstr + mystr[:2]
        print("The new string is:", newstr)
    ExamOn("GenX")

    OR

    (b) Write the output on execution of the following Python code:

    def Change(X):
        for K,V in X.items():
            L1.append(K)
            L2.append(V)
    
    D={1:"ONE",2:"TWO",3:"THREE"}
    L1=[]
    L2=[]
    Change(D)
    print(L1)
    print(L2)
    print(D)
    Answer
    Answer:
    (a) The new string is: g0n2Ge

    Explanation:
    i) mystr is “GenX”. Characters processed with count starting at 0.
    ii) When count is even, append the lowercase character. When count is odd, append the string of count−1.
    iii) Stepwise:
    a) count 0, char ‘G’ → add ‘g’ → “g”
    b) count 1, char ‘e’ → add “0” → “g0”
    c) count 2, char ‘n’ → add ‘n’ → “g0n”
    d) count 3, char ‘X’ → add “2” → “g0n2”
    iv) After loop, append mystr[:2] which is “Ge” → “g0n2Ge”.
    v) The print statement with a comma inserts a space, so the exact line printed is:
    The new string is: g0n2Ge

    OR

    (b) Output:
    [1, 2, 3] [‘ONE’, ‘TWO’, ‘THREE’] {1: ‘ONE’, 2: ‘TWO’, 3: ‘THREE’}

    Explanation:
    i) Iterating a dictionary yields its items in insertion order.
    ii) Keys 1, 2, 3 are appended to L1. Values “ONE”, “TWO”, “THREE” are appended to L2.
    iii) The dictionary D remains unchanged.
    iv) Printing the lists and dictionary gives their literal representations as shown.

Section D

  1. Suman has created a table named WORKER with a set of records to maintain the data of the construction sites, which consists of WID, WNAME, WAGE, HOURS, TYPE, and SITEID. After creating the table, she entered data in it, which is as follows :

    WID  WNAME  WAGE  HOURS  TYPE  SITEID
    W01  Ahmed J  1500  200  Unskilled  103
    W11  Naveen S  520  100  Skilled  101
    W02  Jacob B  780  95  Unskilled  101
    W15  Nihal K  560  110  Semiskilled  NULL
    W10  Anju S  1200  130  Skilled  103

    (a) Based on the data given above, answer the following questions :

    Answer
    Answer and Detailed Solution:

    (i) SQL to display the names and wages of those workers whose wages are between 800 and 1500:

    SELECT WNAME, WAGE FROM WORKER
    WHERE WAGE BETWEEN 800 AND 1500;

    BETWEEN selects rows where wage lies between the lower and upper limits (inclusive). It will display WNAME and WAGE of Ahmed J, Jacob B, and Anju S.

    (ii) SQL to display the record of workers whose SITEID is not known:

    SELECT * FROM WORKER
    WHERE SITEID IS NULL;

    IS NULL checks for missing or unknown values. This will return the full record of Nihal K.

    (iii) SQL to display WNAME, WAGE and HOURS of all those workers whose TYPE is ‘Skilled’:

    SELECT WNAME, WAGE, HOURS FROM WORKER
    WHERE TYPE='Skilled';

    The condition TYPE=’Skilled’ filters only skilled workers and displays the specified columns.

    (iv) SQL to change the WAGE to 1200 of the workers where the TYPE is ‘Semiskilled’:

    UPDATE WORKER
    SET WAGE = 1200
    WHERE TYPE = 'Semiskilled';

    UPDATE modifies existing records. This will update Nihal K’s wage to 1200.

    (b) If instead you are to write the output of given SQL commands (alternative question), you would use the above data to compute the actual query results.

  2. A csv file “P_record.csv” contains the records of patients in a hospital. Each record of the file contains the following data :
    • Name of a patient
    • Disease
    • Number of days patient is admitted
    • Amount
    For example, a sample record of the file may be : [“Gunjan”,”Jaundice”,4,15000] Write the following Python functions to perform the specified operations on this file :
    Answer
    Answer and Detailed Solution:

    (i) Function to read all data and display the details of all the ‘Cancer’ patients:

    import csv
    
    def read_data():
        with open("P_record.csv", newline='', encoding="utf-8") as f:
            reader = csv.reader(f)
            for rec in reader:
                if rec[1].strip().lower() == 'cancer':
                    print(rec)

    This function opens the CSV file, checks the second field (Disease), and prints records with disease as ‘Cancer’.

    (ii) Function to count and return the number of records in the file:

    def count_rec():
        count = 0
        with open("P_record.csv", newline='', encoding="utf-8") as f:
            for _ in csv.reader(f):
                count += 1
        return count

    This function counts all rows and returns the total number of patient records.

  3. Assume that you are working in the IT Department of a Creative Art Gallery (CAG), which sells different forms of art creations like Paintings, Sculptures etc. The data of Art Creations and Artists are kept in tables Articles and Artists respectively. Following are few records from these two tables :

    Table : Articles

    Code  A_Code  Article  DOC  Price
    PL001  A0001  Painting  2018-10-19  20000
    SC028  A0004  Sculpture  2021-01-15  16000
    QL005  A0003  Quilling  2024-04-24  3000

    Table : Artists

    A_Code  Name  Phone  Email  DOB
    A0001  Roy  595923  r@CrAG.com  1986-10-12
    A0002  Ghosh  1122334  ghosh@CrAG.com  1972-02-05
    A0003  Gargi  121212  Gargi@CrAG.com  1996-03-22
    A0004  Mustafa  33333333  Mf@CrAg.com  2000-01-01

    Note : • The tables contain many more records than shown here.
    • DOC is Date of Creation of an Article.

    As an employee of CAG, you are required to write the SQL queries for the following :

    Answer
    Answer and Detailed Solution:

    (i) Display all the records from the Articles table in descending order of price:

    SELECT * FROM Articles
    ORDER BY Price DESC;

    ORDER BY Price DESC sorts rows so the costliest article is listed first.

    (ii) Display the details of Articles which were created in the year 2020:

    SELECT * FROM Articles
    WHERE YEAR(DOC) = 2020;

    The YEAR() function extracts the year from the date. This will display all records from 2020.

    (iii) Display the structure of Artists table:

    DESCRIBE Artists;

    or

    DESC Artists;

    DESCRIBE or DESC command lists column names, data types, and constraints.

    (iv) (a) Display the name of all artists whose Article is Painting through Equi Join:

    SELECT Artists.Name
    FROM Artists, Articles
    WHERE Artists.A_Code = Articles.A_Code
    AND Articles.Article = 'Painting';

    OR
    (b) Display the name of all Artists whose Article is ‘Painting’ through Natural Join:

    SELECT Name
    FROM Artists
    NATURAL JOIN Articles
    WHERE Article = 'Painting';

    Equi Join uses an explicit join condition, while Natural Join automatically matches columns with the same name.

  1. A table, named THEATRE, in CINEMA database, has the following structure :

    Field  Type
    Th_ID  char(5)
    Name  varchar(15)
    City  varchar(15)
    Location  varchar(15)
    Seats  int

    Write a function Delete_Theatre(), to input the value of Th_ID from the user and permanently delete the corresponding record from the table.

    Assume the following for Python-Database connectivity :
    Host : localhost, User : root, Password : Ex2025

    Answer
    Answer and Solution:

    To delete a record securely using Python-MySQL connectivity:

    import mysql.connector
    
    def Delete_Theatre():
        try:
            con = mysql.connector.connect(
                host="localhost",
                user="root",
                password="Ex2025",
                database="CINEMA"
            )
            cur = con.cursor()
            thid = input("Enter Theatre ID to delete : ").strip()
            q = "DELETE FROM THEATRE WHERE Th_ID = %s"
            cur.execute(q, (thid,))
            con.commit()
            if cur.rowcount > 0:
                print("Record deleted successfully.")
            else:
                print("No record found with Th_ID =", thid)
        except mysql.connector.Error as e:
            print("Error:", e)
        finally:
            if con.is_connected():
                cur.close()
                con.close()

    Explanation:
    i) Establishes a connection to CINEMA database.
    ii) Takes the Theatre ID from the user.
    iii) Executes a parameterized DELETE query to avoid SQL injection.
    iv) Uses commit() to make the deletion permanent.

  2. Section E

  3. A file, PASSENGERS.DAT, stores the records of passengers using the following structure : [PNR, PName, BRDSTN, DESTN, FARE]

    where
    PNR – Passenger Number (string type)
    PName – Passenger Name (string type)
    BRDSTN – Boarding Station Name (string type)
    DESTN – Destination Station Name (string type)
    FARE – Fare amount for the journey (float type)

    Write user defined functions in Python for the following tasks :

    (i) Create() – to input data for passengers and write it in the binary file PASSENGERS.DAT.
    (ii) SearchDestn(D) – to read contents from the file PASSENGERS.DAT and display the details of those Passengers whose DESTN matches with the value of D.
    (iii) UpdateFare() – to increase the fare of all passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.

    Answer
    Answer and Solution:

    (i) Create()

    import pickle
    
    def Create():
        with open("PASSENGERS.DAT", "wb") as f:
            n = int(input("Enter number of passenger records : "))
            for _ in range(n):
                pnr = input("PNR : ")
                name = input("Passenger Name : ")
                brd = input("Boarding Station : ")
                dest = input("Destination : ")
                fare = float(input("Fare : "))
                rec = [pnr, name, brd, dest, fare]
                pickle.dump(rec, f)
        print("Data written successfully.")

    This function writes user-entered passenger details as pickled binary records.

    (ii) SearchDestn(D)

    def SearchDestn(D):
        found = False
        with open("PASSENGERS.DAT", "rb") as f:
            try:
                while True:
                    rec = pickle.load(f)
                    if rec[3].strip().lower() == D.strip().lower():
                        print(rec)
                        found = True
            except EOFError:
                pass
        if not found:
            print("No passenger found with destination", D)

    The function loops until end-of-file and prints all records whose destination matches D.

    (iii) UpdateFare()

    def UpdateFare():
        records = []
        with open("PASSENGERS.DAT", "rb") as f:
            try:
                while True:
                    rec = pickle.load(f)
                    rec[4] = round(rec[4] * 1.05, 2)
                    records.append(rec)
            except EOFError:
                pass
    
        with open("PASSENGERS.DAT", "wb") as f:
            for rec in records:
                pickle.dump(rec, f)
        print("Fare updated successfully for all passengers.")

    This function reads all records, increases the fare by 5 %, and rewrites the file with updated data.

    1. ‘Swabhaav’ is a big NGO working in the field of Psychological Treatment and Counselling, having its Head Office in Nagpur. It is planning to set up a center in Vijayawada. The Vijayawada Center will have four blocks – ADMIN, PSYCHIATRY, PSYCHOLOGY, and ICU. You, as a Network Expert, need to suggest the best network-related solutions for them to resolve the issues/problems mentioned in questions (i) to (v), keeping the following parameters in mind :

      Block to Block distances (in metres) :
      ADMIN–PSYCHIATRY  65 m
      ADMIN–PSYCHOLOGY  65 m
      ADMIN–ICU  65 m
      PSYCHIATRY–PSYCHOLOGY  100 m
      PSYCHIATRY–ICU  50 m
      PSYCHOLOGY–ICU  50 m

      Distance of Nagpur Head Office from Vijayawada Center = 700 km

      Number of Computers in each block is as follows :
      ADMIN  16
      PSYCHIATRY  40
      PSYCHOLOGY  19
      ICU  20

      (i) Suggest the most appropriate location of the server inside the Vijayawada Center. Justify your choice.
      (ii) Which hardware device will you suggest to connect all the computers within each block of Vijayawada Center ?
      (iii) Draw a cable layout to efficiently connect various blocks within the Vijayawada Center.
      (iv) Where should the router be placed to provide internet to all the computers in the Vijayawada Center ?
      (v) (a) The Manager at Nagpur wants to remotely access the computer in Admin block in Vijayawada. Which protocol will be used for this ?
      OR
      (b) Which type of Network (PAN, LAN, MAN or WAN) will be set up among the computers connected with Vijayawada Center ?

      Answer

      Answer and Detailed Solution:

      (i) Server Location:
      Place the server in the PSYCHIATRY block. This block houses the maximum number of computers (40) and lies centrally with respect to other blocks (distances 50–100 m). Installing the server here ensures balanced load handling and reduces overall cabling.

      (ii) Device to connect computers within each block:
      Use a Switch for each block. Switches provide high-speed, collision-free connectivity within a LAN segment and are more efficient than hubs.

      (iii) Cable Layout:
      Adopt a Star Topology with PSYCHIATRY as the central hub. Connect ADMIN, PSYCHOLOGY, and ICU blocks directly to PSYCHIATRY using fibre-optic or Cat6 Ethernet cables. This design minimizes cable length and ensures high bandwidth and reliability.

      (iv) Router Placement:
      Install the router in the PSYCHIATRY block alongside the main server. This allows direct distribution of internet access to all switches and ensures efficient network management.

      (v) Remote Access / Network Type:
      (a) For secure remote access from Nagpur to Vijayawada’s Admin block, use Remote Desktop Protocol (RDP) or SSH, depending on the operating system.
      OR
      (b) The network connecting all computers within Vijayawada Center is a LAN (Local Area Network), as it is confined to a single campus.

Disclaimer

The question bank provided on this website is meant to be a supplementary resource for final term exam preparation. While we strive to offer accurate and relevant content, students should not rely solely on these answers. It is essential to conduct further research and consult teachers, school authorities, or subject experts to ensure thorough understanding and preparation. The solutions here are based on general interpretations and may not reflect the exact responses expected by examination boards. We are not responsible for any discrepancies or outcomes in exams resulting from the use of this material. By using this resource, you acknowledge that your academic success depends on comprehensive preparation, including active engagement with school materials and guidance from educators.

Was this resource helpful?
Yes1No0

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More