Python Question Paper 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

🐍

Python-2
1 Marks Question
a) What are the advantages of Python?
Python has several advantages, including:

Readability: Python's syntax is clean and readable, making it easy for


developers to write and maintain code.

Versatility: Python can be used for various applications, including web


development, data science, machine learning, automation, and more.

Community Support: Python has a large and active community, providing


support, libraries, and frameworks.

Integration: Python can be easily integrated with other languages and


technologies.

Productivity: Python emphasizes code readability and efficiency, leading to


increased developer productivity.

b) List out main differences between lists & tuple.


Mutability: Lists are mutable, meaning their elements can be changed after
creation. Tuples are immutable, and their elements cannot be modified.

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.

Performance: Due to immutability, tuples generally have a smaller memory


footprint and can offer better performance in certain scenarios.

c) Python is a scripting language. Comment.


Python is often referred to as a scripting language because it is commonly used for
scripting and automation tasks. Scripting languages are interpreted languages that

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.

d) Demonstrate set with an example.

pythonCopy code
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Adding elements to the set


my_set.add(6)
my_set.add(3) # Adding a duplicate element; it won't be added

# Removing elements from the set


my_set.remove(2)

# Displaying the set


print(my_set)

e) What is a dictionary? Give an example.


A dictionary in Python is an unordered collection of key-value pairs. Each key must
be unique, and it is associated with a corresponding value. Here's an example:

pythonCopy code
# Creating a dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}

# Accessing values using keys


print("Name:", my_dict["name"])
print("Age:", my_dict["age"])

# Modifying a value
my_dict["age"] = 31

# Adding a new key-value pair


my_dict["occupation"] = "Engineer"

Python-2 2
# Displaying the dictionary
print(my_dict)

f) What is regEx? Give an example.


RegEx (Regular Expression): It is a sequence of characters that defines a search
pattern. It is used for pattern matching within strings.

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.")

g) What is a user-defined Module? Give an example.


A user-defined module in Python is a file containing Python code that can be
imported and used in other Python scripts. Here's an example:

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

# Using functions from the module


print(mymodule.greet("Alice"))
print(mymodule.add_numbers(3, 5))

h) Python is a case-sensitive language. Comment.


In Python, the distinction between uppercase and lowercase letters is significant.
This means that variables, function names, and other identifiers must be referenced
using the correct case. For example, variable and Variable would be treated as
different identifiers in Python.

i) What is dry run in Python?


A dry run in Python refers to the process of mentally or manually walking through
the code without executing it. Developers perform dry runs to understand how the
code works, identify potential errors, and trace the flow of execution. It helps in
debugging and gaining insights into the behavior of the code.

j) What is a lambda function? Give an example.


A lambda function is an anonymous function in Python defined using the lambda

keyword. It is a concise way to create small, one-line functions.

Example:

pythonCopy code
# Lambda function to calculate the square of a number
square = lambda x: x**2

# Using the lambda function

Python-2 4
result = square(5)
print("

2 Marks Question
a) Write a Python program to calculate XY.

# Python program to calculate XY


def power(base, exponent):
result = base ** exponent
return result

# Taking input from the user


base = float(input("Enter the base: "))
exponent = float(input("Enter the exponent: "))

# Calculating and displaying the result


result = power(base, exponent)
print(f"{base} raised to the power {exponent} is: {result}")

b) Write a Python program to accept a number and check


whether it is a perfect number or not.

# Python program to check if a number is a perfect number


def is_perfect_number(num):
divisors = [i for i in range(1, num) if num % i == 0]
sum_divisors = sum(divisors)
return sum_divisors == num

# Taking input from the user


number = int(input("Enter a number: "))

# Checking and displaying the result


if is_perfect_number(number):
print(f"{number} is a perfect number.")

Python-2 5
else:
print(f"{number} is not a perfect number.")

c) What is the use of seek( ) & tell( ) functions?


seek( ) : The seek() function in Python is used to change the current position of
the file pointer within a file. It is often used in file handling to move the pointer to
a specific position within the file.

Example:

with open("example.txt", "r") as file:


file.seek(10) # Move the pointer to the 10th byte
content = file.read()
print(content)

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:

with open("example.txt", "r") as file:


content = file.read(15)
print(content)
position = file.tell()
print(f"Current position: {position} bytes")

d) Demonstrate list slicing.

# List slicing in Python


my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slicing from index 2 to 5 (exclusive)

Python-2 6
sliced_list = my_list[2:5]

print("Original List:", my_list)


print("Sliced List:", sliced_list)

e) A tuple is an ordered collection of items. Comment.


A tuple in Python is an ordered collection of elements enclosed in parentheses ( () ).
It is similar to a list but immutable, meaning its elements cannot be modified once the
tuple is created. Tuples maintain the order of elements, and each element can be
accessed using its index. The immutability of tuples makes them suitable for
situations where the data should remain unchanged throughout the program
execution.

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:

int: Integer data type represents whole numbers.

float: Float data type represents floating-point numbers.

Example:

num_int = 5
num_float = 3.14

2. Sequence Types:

str: String data type represents sequences of characters.

Example:

my_string = "Hello, Python!"

Python-2 7
3. Collection Types:

list: List is a collection of items. It is mutable.

tuple: Tuple is a collection of items. It is immutable.

set: Set is an unordered collection of unique items.

dict: Dictionary is a collection of key-value pairs.

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

b) Write a short note on exception handling.


Exception handling in Python is a mechanism to deal with runtime errors and
abnormal situations. It helps prevent a program from crashing when unexpected
situations occur. The key components of exception handling are:

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.

finally: The finally block is optional and is executed regardless of whether an


exception occurred. It is often used for cleanup operations.

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.")

c) What is a module? What is a package? Explain with an


example.
Module: A module in Python is a file containing Python code. It can define
functions, classes, and variables. Modules allow code reusability by organizing
related code into separate files.

Example - math_operations.py :

# math_operations.py
def add(x, y):
return x + y

def subtract(x, y):

Python-2 9
return x - y

Package: A package is a way of organizing related modules into a directory


hierarchy. It includes an __init__.py file to indicate that the directory should be
treated as a package.

Example - Directory structure:

my_package/
│ __init__.py

├── math_operations.py
└── utils.py

Example - utils.py inside the package:

# my_package/utils.py
def multiply(x, y):
return x * y

To use the module and package in another script:

# main_script.py
from my_package import math_operations, utils

result_add = math_operations.add(10, 5)
result_multiply = utils.multiply(3, 4)

print("Addition Result:", result_add)


print("Multiplication Result:", result_multiply)

In this example, math_operations is a module, and my_package is a package containing


multiple modules.

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 case: Sum the digits of n


digit_sum = 0
while n > 0:
digit_sum += n % 10
n //= 10

# 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}")

b) Write a program in Python to accept 'n' integers in a list,


compute & display the addition of all squares of these integers.

def sum_of_squares(nums):
return sum(x**2 for x in nums)

# Accept 'n' integers from the user


n = int(input("Enter the number of integers: "))
user_numbers = [int(input(f"Enter integer #{i + 1}: ")) for i

# Calculate and display the sum of squares

Python-2 11
result = sum_of_squares(user_numbers)
print(f"The sum of squares of entered integers is: {result}")

c) Write a Python program to count all occurrences of "India"


and "Country" in a text file "pledge.txt".
Assuming the content of "pledge.txt" contains text:

I pledge allegiance to the flag of India and to the country fo


India is a beautiful country with diverse cultures. The count

def count_occurrences(file_path, words):


try:
with open(file_path, 'r') as file:
content = file.read()
count_result = {word: content.lower().count(word.l
return count_result

except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return {}

# List of words to count occurrences


words_to_count = ["India", "Country"]

# File path
file_path = "pledge.txt"

# Count occurrences and display the result


result = count_occurrences(file_path, words_to_count)
for word, count in result.items():
print(f"The word '{word}' appears {count} times in the fil

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

def f2(a, b):


global X
return a + b + X

f1()
total = f2(1, 2)
print(total)

Output Explanation:

1. Initially, X is assigned the value 5.

2. f1() is called, which changes the global value of X to 4.

3. f2(1, 2) is called, where a is 1, b is 2, and X is 4.

4. The total is calculated as 1 + 2 + 4 , resulting in 7 .

5. The print(total) statement prints the value of total , which is 7 .

Output:

b) What is the output of the following code:

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:

1. The @f decorator is applied to the function f(a, b) , effectively replacing f with


f1 in the current scope.

2. f(4, 0) is called, where a is 4, and b is 0.

3. Inside f1 , "hello" is printed.

4. Since b is 0, "NO" is printed, and the function returns.

5. The original f(a, b) is called with arguments 4 and 0, resulting in an attempt to


perform the operation 4 % 0 .

6. Since dividing by zero is not allowed, the program encounters a


ZeroDivisionError .

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

You might also like