Python Question Paper 2
Python Question Paper 2
Python-2
1 Marks Question
a) What are the advantages of Python?
Python has several advantages, including:
Syntax: Lists are defined using square brackets [ ] , while tuples use
parentheses ( ) .
Methods: Lists have more built-in methods compared to tuples because of their
mutability.
Python-2 1
allow developers to write scripts to automate tasks or execute sequences of
commands. Python's simplicity, ease of use, and ability to run interactively make it
well-suited for scripting purposes.
pythonCopy code
# Creating a set
my_set = {1, 2, 3, 4, 5}
pythonCopy code
# Creating a dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}
# Modifying a value
my_dict["age"] = 31
Python-2 2
# Displaying the dictionary
print(my_dict)
Example:
pythonCopy code
import re
# Define a pattern
pattern = r'\b\d{3}-\d{2}-\d{4}\b' # Pattern for a social sec
# Test a string
text = "John's SSN is 123-45-6789."
match = re.search(pattern, text)
if match:
print("Social Security Number found:", match.group())
else:
print("No Social Security Number found.")
mymodule.py:
pythonCopy code
# Contents of mymodule.py
def greet(name):
return f"Hello, {name}!"
Python-2 3
def add_numbers(a, b):
return a + b
main_script.py:
pythonCopy code
# Contents of main_script.py
import mymodule
Example:
pythonCopy code
# Lambda function to calculate the square of a number
square = lambda x: x**2
Python-2 4
result = square(5)
print("
2 Marks Question
a) Write a Python program to calculate XY.
Python-2 5
else:
print(f"{number} is not a perfect number.")
Example:
tell( ) : The tell() function returns the current position of the file pointer within
a file. It is used to determine the current offset or position within the file.
Example:
Python-2 6
sliced_list = my_list[2:5]
4 Marks Question
a) Write a short note on datatypes in Python.
Python supports various data types that are used to represent different types of
values. Some common data types in Python include:
1. Numeric Types:
Example:
num_int = 5
num_float = 3.14
2. Sequence Types:
Example:
Python-2 7
3. Collection Types:
Example:
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_set = {1, 2, 3}
my_dict = {'name': 'John', 'age': 25}
4. Boolean Type:
bool: Boolean data type represents truth values, either True or False.
Example:
is_true = True
is_false = False
try: The code that might cause an exception is placed inside the try block.
except: If an exception occurs within the try block, it is caught and handled in
the except block. Multiple except blocks can be used to handle different types of
exceptions.
Example:
Python-2 8
try:
# Code that might cause an exception
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid integers.")
else:
# Code to be executed if no exception occurs
print(f"Result: {result}")
finally:
# Cleanup code (optional)
print("This block is executed regardless of exceptions.")
Example - math_operations.py :
# math_operations.py
def add(x, y):
return x + y
Python-2 9
return x - y
my_package/
│ __init__.py
│
├── math_operations.py
└── utils.py
# my_package/utils.py
def multiply(x, y):
return x * y
# main_script.py
from my_package import math_operations, utils
result_add = math_operations.add(10, 5)
result_multiply = utils.multiply(3, 4)
Python-2 10
4 Marks Question
a) Write a recursive function in Python to display the addition of
digits in a single digit.
def sum_of_digits(n):
# Base case: If n is a single digit, return n
if n < 10:
return n
# Recursive call
return sum_of_digits(digit_sum)
# Example usage
number = 9875
result = sum_of_digits(number)
print(f"The sum of digits of {number} is: {result}")
def sum_of_squares(nums):
return sum(x**2 for x in nums)
Python-2 11
result = sum_of_squares(user_numbers)
print(f"The sum of squares of entered integers is: {result}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return {}
# File path
file_path = "pledge.txt"
Python-2 12
This program reads the content of the file and counts the occurrences of specified
words ("India" and "Country"). The count is case-insensitive.
3 Marks Question
a) What is the output of the following code:
X = 5
def f1():
global X
X = 4
f1()
total = f2(1, 2)
print(total)
Output Explanation:
Output:
Python-2 13
def f(X):
def f1(a, b):
print("hello")
if b == 0:
print("NO")
return
return f(a, b)
return f1
@f
def f(a, b):
return a % b
f(4, 0)
Output Explanation:
Output:
hello
NO
Python-2 14
Note: The original function f(a, b) is never actually executed because the decorator
@f replaced it with f1 . The "NO" statement is printed from within f1 .
Python-2 15