Python 2024 (Reg/Rep) Solved Question Paper Python Programming
Time: 2 Hrs | Max. Marks: 60
Section - A
I. Answer any TEN questions. (10×2=20)
1. Mention any four features of python.
- Portable
Easy to Learn
Interpreted Language
Cross-Platform
Extensive Libraries
- High-Level Language
2. What are IOE's in python?
IOE stands for Input-Output Errors (or Input/Output Exceptions). These are exceptions that occur during file operations or data stream handling (e.g., reading/writing files, network communication)
Example:
try:
file = open("data.txt")
except IOError:
print("File not found.")
3. Define exception. Give example.
An Exception in Python is an error that occurs during the execution of a program, which disrupts the normal flow of the program. Instead of crashing the program, exceptions can be caught and handled using error handling mechanisms like try-except
Example:
try:
x = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
4. Define function. Mention types of function.
Function: A reusable block of code that performs a specific task.
Types:
- Built-in Functions: Predefined in Python (e.g.,
len()
,print()
). - User-defined Functions: Created by the programmer (e.g.,
def my_function():
)
5. What is command line argument? Give example.
A command line argument is an input value passed to a Python script when it is executed from the terminal/command prompt. These arguments allow users to customize the program’s behavior without modifying the code.
Example:
python script.py arg1 arg2
Here, arg1
and arg2
are command line arguments accessed via sys.argv
.
Code:
import sys
print(sys.argv[1]) # prints 'arg1'
6. Mention types of files in python.
Text Files – Store data in readable format (.txt, .csv).
Binary Files – Store data in binary format (.bin, .jpg).
7. What are lists? Give syntax.
list is a built-in data structure that is used to store multiple items in a single variable. Lists are ordered, mutable, and can contain elements of different data types, such as integers, strings, floats, or even other lists.
Example:
my_list = [1, 2, 3, 'hello']
8. What are pandas and series in python?
- Pandas is a powerful, open-source data analysis and data manipulation library in Python. It provides data structures and functions that are specifically designed for working with structured data such as tables, spreadsheets, and databases.
- A Series is one of the core data structures in Pandas. It is a one-dimensional labeled array, capable of holding data of any type (integers, strings, floats, etc.).
9. Define Numpy? Give syntaxх.
NumPy (Numerical Python) is a library for numerical computations and array processing.
Syntax:
import numpy as np
arr = np.array([1, 2, 3])
10. What is Escape sequence in python? Give example.
An escape sequence in Python is a combination of a backslash (\
) followed by a special character, used to represent non-printable or reserved characters in strings.
Example:
print("Hello\nWorld") # \n creates a new line
11. List any Two differences between Lists and Dictionaries.
List | Dictionary |
---|---|
Uses index numbers to access elements. | Uses keys to access values. |
Ordered collection (as of Python 3.7+). | Unordered collection (in older versions). |
Elements are stored as single values. | Data is stored as key-value pairs. |
Created using square brackets [ ] . | Created using curly braces { } . |
Supports duplicate elements. | Keys must be unique; values can be duplicated. |
12. Mention methods of Tkinter.
pack()
: Auto-arranges widgets.grid()
: Places widgets in a grid layout.place()
: Positions widgets at exact coordinates.mainloop()
: Starts the GUI event loop.
Section - B
II. Answer any FOUR of the following. (4×5=20)
13. Explain for Loop and While loop with program.
For Loop
- Used when the number of iterations is known.
- Iterates over sequences (lists, tuples, strings).
Example:
for i in range(5): # Prints 0 to 4 print(i)
While Loop
- Runs until a condition is False.
- Used when iterations are unknown.
Example:
count = 0 while count < 5: # Prints 0 to 4 print(count) count += 1
14. With an example explain try-except and finally blocks.
try
Block:
- The code that might raise an exception is placed inside the
try
block. - Python runs this code and checks for errors during execution.
except
Block:
- If an exception occurs in the
try
block, Python jumps to theexcept
block. - This block contains code that handles the error.
finally
Block:
- The
finally
block is always executed, whether an exception occurred or not. - It is often used to release resources, like closing files or database connections
Example:
try:
a = int(input("Enter a number: "))
b = 10 / a
print("Result:", b)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
15. Define Tuple. Give example for create update and delete operations.
For deadlock to occur in a system, four necessary conditions must hold simultaneously. These conditions are described by Coffman’s Conditions:
- Mutual Exclusion: Only one process can use a resource at a time. If a resource is allocated to one process, others must wait.
- Hold and Wait: A process is holding at least one resource and waiting to acquire additional resources that are currently being held by other processes.
- No Preemption: Resources cannot be forcibly taken away from a process. A resource can be released only voluntarily by the process holding it.
- Circular Wait: A set of processes are waiting for each other in a circular chain. Each process holds at least one resource and is waiting for a resource held by the next process in the chain.
16. Write a program to create parent class and child class using inheritance.
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Child Class
class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")
# Creating an object of Parent Class
animal1 = Animal("Generic Animal")
animal1.speak() # Output: Generic Animal makes a sound.
# Creating an object of Child Class
dog1 = Dog("Tommy")
dog1.speak() # Output: Tommy barks.
17. Write a short note on Numpy.
NumPy (Numerical Python) is a fundamental package for scientific computing in Python, providing support for multi-dimensional arrays and mathematical functions.
Features of NumPy:
Provides a high-performance array object called
ndarray
.Supports mathematical, logical, and statistical operations on arrays.
Offers broadcasting, which allows operations on arrays of different shapes.
Efficient in handling large datasets.
Used in data science, machine learning, image processing, and more.
Syntax and Example:
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Display array and perform operation
print("Array:", arr)
print("Array multiplied by 2:", arr * 2)
Section - C
Answer any TWO questions. (2×10=20)
18. Mention types of operators. Explain any four operators with example.
Types of Operators in Python
Arithmetic (
+
,-
,*
,/
,%
,**
,//
)Comparison (
==
,!=
,>
,<
,>=
,<=
)Logical (
and
,or
,not
)Assignment (
=
,+=
,-=
,*=
,/=
)Bitwise (
&
,|
,^
,~
,<<
,>>
)Identity (
is
,is not
)Membership (
in
,not in
)
Explained with Examples:
Arithmetic (
+
,**
)print(5 + 3) # Output: 8 (Addition) print(2 ** 3) # Output: 8 (Exponentiation)
Assignment (
+=
)x = 5 x += 2 # Equivalent to x = x + 2 print(x) # Output: 7
Logical (
and
)print(True and False) # Output: False
Membership (
in
)fruits = ["apple", "banana"] print("banana" in fruits) # Output: True
19. Explain operations on strings with program example.
String Operations:
Concatenation (
+
)Repetition (
*
)Slicing (
[start:end]
)Length (
len()
)Methods like
lower()
,upper()
,replace()
,find()
Example:
str1 = "Hello"
str2 = "World"
# Concatenation
print(str1 + " " + str2) # Hello World
# Repetition
print(str1 * 2) # HelloHello
# Slicing
print(str1[1:4]) # ell
# String methods
print(str1.lower()) # hello
print(str2.replace("World", "Python")) # Python
Output:
Hello World
HelloHello
ell
hello
Python
20. a) Write a short note on file.
A file is a named location on disk used to store related data permanently. Files allow programs to read input from and write output to persistent storage (e.g., HDD, SSD).
Types of Files
- Text Files: Human-readable (
.txt
,.csv
,.json
). - Binary Files: Machine-readable (
.jpg
,.dat
,.pickle
).
File Operations:
- Opening:
open("file.txt", mode="r")
- Modes:
r
(read),w
(write),a
(append),r+
(read/write). - Reading:
file.read()
,file.readlines()
. - Writing:
file.write("text")
. - Closing:
file.close()
(or usewith
for auto-close).
Example:
file = open("sample.txt", "w")
file.write("Hello, Python file handling!")
file.close()
b) Write a program for line chart.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 8, 6]
# Plotting the line chart
plt.plot(x, y, marker='o', color='blue', linestyle='--')
# Adding titles and labels
plt.title("Simple Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Show the chart
plt.show()