0% found this document useful (0 votes)
8 views3 pages

Python Programming Exam Questions

The document outlines an examination paper for a Python programming course, detailing various programming tasks and questions to be answered by students. It includes tasks related to string manipulation, data structures, file handling, and mathematical operations using Python. Each question carries equal marks and requires the student to demonstrate their programming skills through practical coding exercises.

Uploaded by

sharmarachit885
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Python Programming Exam Questions

The document outlines an examination paper for a Python programming course, detailing various programming tasks and questions to be answered by students. It includes tasks related to string manipulation, data structures, file handling, and mathematical operations using Python. Each question carries equal marks and requires the student to demonstrate their programming skills through practical coding exercises.

Uploaded by

sharmarachit885
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Sub Code: CST005 ROLL NO……………..……………..

EVEN SEMESTER EXAMINATION, 2023 – 24


IInd yr [Link].
PYTHON PROGRAMMING

Duration: 2:00 hrs Max Marks: 50


Note: - Attempt all questions. All Questions carry equal marks. In case of any ambiguity or missing data,
the same may be assumed and state the assumption made in the answer.

Q1. Answer any two parts of the following. 5x2=10


a) Write a python program to enter the marks of five subjects, compute the
percentage, and display the grade.
b) Write a python program to check the number of prime numbers in a range of
numbers.
c) Write a python program to print the reverse of a string.
Q2. Answer any two parts of the following. 5x2=10
a) Write a python program to count the number of matching characters in the pair of
strings.
b) Given the string text = "PythonProgramming". Perform the following slicing
operations on given string:
1. Slice the string to obtain the first 6 characters.
2. Extract a substring that includes the characters from index 6 to index 13.
3. Slice the last 5 characters from the string.
4. Create a new string by slicing and concatenating the first 4 characters and the last
3 characters
c) Write the output of the following code:
1. tuple1 = (1, 2, 4, 3)
tuple1[2]=5
print(tuple1)
2. var1=("abc",34,True,40,"male")
out=[Link](0)
print(out)
3. test = {1: 'A', 2: 'B', 3: 'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test))
4. S1 = {"a","b","c"}
S2={1, “a”, 5, 3, “c” 6}
S3= S1. Symmetric_difference(S2)
[Link](“b”)
print(S3)
print(S1)
Q3. Answer any two parts of the following. 5x2=10
a) Write a python program to create a dictionary containing six elements that
represents a student's grades. The dictionary should contain the student's name as
the key and a set of their subject marks as the value. Perform the following
operations on dictionary:
1. Display all the elements in dictionary using loops.
2. Calculate the average grade for each student and display the student with the
highest average grade.
3. Update the marks of students with last three grades and show the updated
dictionary.
4. Display the keys and values in dictionary.
5. Display the common marks obtained by student1 and students 2.
b) Write a program to generate two sets, each containing 15 random numbers between
50 and 100. Then, perform the following operations:
1. Find and display the common numbers that appear in both the lists.
2. Identify and print the unique numbers present in both the lists.
3. Calculate and display the minimum value in both the lists.
4. Compute and print the sum of all the numbers in both the lists.
c) Write the output of the following programs:
1. sample = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
keys = ["name", "salary"]
sample_dict = {k: sample[k] for k in [Link]() - keys}
print(sample_dict)
2. import string
Line1 = "And Then There Were None"
Line2 = "Famous In Love"
Line3 = "Famous Were The Kol And Klaus"
Line4 = Line1 + Line2 + Line3
print("And" in Line4)
3. Create a 1D array of 9 elements using numpy module and reshape it into 2D array
of size 3×3.
Q4. Answer any two parts of the following. 5x2=10
a) Write a python program to Create a scientific calculator using a math module or
inbuilt math functions.
b) Write a python program using functions to simulate the tossing of a coin five times
and compute and display the probability of occurrences of the head.
c) Write a python program to create a 2D array of size 3 × 4 containing random values
and perform the following operations on arrays:
1. Compute sum of array along the rows, columns and overall sum of array.
2. Create a subset of the array of size 2 × 2 from the original array.
3. Insert the new columns in the original array and display the shape of the updated
array.
4. Convert the array into matrix and perform the multiplication of matrix with itself.
5. Permute the dimensions of the original array.
Q5. Answer any two parts of the following. 5x2=10
a) Write a Python program that:
1. Creates a file named "[Link]" inside a specific directory in both read and
write mode. ('E:\files\python\filehandling\').
2. Verify if the above created file is present in the specified directory or not.
3. Create a file with its name as ‘day-month-year-hours-minutes-seconds’
4. Write a code to add some content at the end of the file using proper access mode.
b) Write a python program that manages exceptions during file operations. The
program should perform the following tasks:

1. Prompt the user to input the name of a text file.


2. Read the contents of the specified file.
3. Convert the text to uppercase.
4. Write the modified content back to the same file.

c) Write a python program that:


1. Creates a text file named “demofile” in read mode.
2. Read first five characters of the file.
3. Read one line of the file.
4. Read the content of the whole file.
5. Rename the file after checking whether it exists and delete the file.

**********

Common questions

Powered by AI

Python can efficiently manipulate text data by reading, modifying, and saving new content using file I/O operations. Techniques include opening files in appropriate modes ('r', 'w', 'a'), reading data using read() or readline(), modifying content in memory (e.g., converting to uppercase), and writing changes back with write() or writelines(). Context managers (using 'with') ensure files are properly closed after operations, preventing resource leaks. Enhanced tasks include renaming files after checking existence with os.path exists() and renaming using os.rename().

Exception handling during file operations in Python is crucial for stabilizing programs against unforeseen errors such as file absence, permission issues, or incorrect data formats. It involves using try-except blocks to catch exceptions and execute alternative logic or notify the user of an error safely. To manage errors effectively, one can wrap file operations in a try block, use specific except clauses to catch and handle different exceptions like FileNotFoundError or IOError, and employ finally blocks to ensure cleanup operations (such as closing files) occur regardless of errors .

In Python, dictionaries can effectively manage and calculate student grades by storing the student’s name as keys and a set of subject marks as values. To manage grades, one can iterate through the dictionary to perform operations like calculating each student’s average grade and determining the highest average using aggregation and comparison techniques. Updating marks involves modifying existing entries by specifying the particular dictionary key and altering the values accordingly. Common grades can be identified by taking set intersections between the values of different student's entries .

To check the number of prime numbers in a range using Python, one would create a function that iterates over each number in the specified range, checks if each number is prime, and counts how many primes there are. A number is considered prime if it is greater than one and not divisible by any number other than one and itself, which can be checked by attempting to divide it by all integers between 2 and the square root of the number. A counter would keep track of prime numbers found during the iteration .

Using NumPy in Python to reshape arrays enhances computational capabilities by optimizing memory layout and facilitating operations such as matrix multiplication and data manipulation across different dimensions. To reshape an array, one typically uses the reshape() function, specifying the new dimensions, such as converting a 1D array into a 2D array. This operation necessitates that the total number of elements remains consistent before and after reshaping. Reshaping allows complex computations like matrix algebra and image processing to be conducted efficiently with fewer lines of code .

Simulating random events like coin tossing in Python involves generating random outcomes using libraries such as random. Each toss can be simulated using random.choice() to select either 'heads' or 'tails'. By repeating this in a loop for a specified number of trials (five, in this case) and counting occurrences of 'heads', one can compute probabilities as the count of 'heads' divided by the total number of tosses, offering a practical estimation of theoretical probabilities. This technique highlights practical probabilities through repetition and randomness .

String slicing in Python allows for extracting subsets of strings using the syntax string[start:stop:step]. Applications of string slicing include extracting specific parts of a text for analysis or modification. For example, slicing the first 6 characters of a string can be used to retrieve prefixes, and extracting characters from specific indices (e.g., index 6 to index 13) can be used to parse formatted data or separate meaningful components of a compound word. Concatenation of sliced parts, like combining the first 4 and last 3 characters, can help generate unique identifiers or URLs .

Tuples in Python are immutable, meaning their values cannot be changed after initialization. Attempting to modify an element within a tuple, such as by assignment, will raise a TypeError. To circumvent this, one can convert the tuple to a list, modify the list, and then convert it back to a tuple. This workaround allows for effective modification of immutable data structures while preserving their original purposes for immutability, such as ensuring data integrity .

Mathematical operations on 2D arrays in Python, provided by the NumPy module, include element-wise addition, subtraction, multiplication, and division, as well as matrix operations like dot product and determinant calculation. Users can sum elements across rows or columns using np.sum() along specified axes and perform matrix multiplication using np.dot(). Such operations support scientific computations by succinctly representing mathematical expressions and enabling large-scale data manipulation efficiently .

In Python, set operations like intersections and unions allow for efficient comparison between data sets to identify common and unique elements. When dealing with random data sets, as stated with two lists of random numbers, intersection methods can quickly identify common numbers, while union and difference operations help determine numbers unique to each data set. These methods are computationally efficient due to the properties of sets in Python and are useful in scenarios such as data analysis, pattern recognition, and database optimization where distinguishing common from unique information is valuable .

You might also like