Python 2022 (Regular) Solved Question Paper
Section - A
1. Answer any Six question.
1. One Marks 10 Que
a) Define Python Who developed it?
- Python was created by Guido van Rossum, and first released on February 20, 1991.
- Python is a general-purpose programming language, It is a high-level, interpreted language that is known for its simplicity and readability.
- Python is used in a wide variety of applications, including web development, data science, machine learning, and artificial intelligence.
b) How to accept user input ? Give example.
To accept user input in Python, you can use the input() function. The input() function takes a prompt as an argument and returns the user’s input as a string.
# Prompt the user for their name.
name = input("What is your name? ")
# Print the user's name.
print("Hello, {}!".format(name))
c) How to declare single and multiline comments in python?
a) To declare single-line comments in Python, you use a hash symbol (#). Anything after the hash symbol on the same line is ignored by the Python interpreter.
# This is a single-line comment.
print("Hello, world!")
b) To declare multiline comments in Python, you use triple quotes (“”” or ”’). Anything between the triple quotes is ignored by the Python interpreter.
"""
This is a multiline comment.
It can span multiple lines.
"""
print("Hello, world!")
d) What is a list ? Give example.
A list is a mutable ordered sequence of elements. list is a data structure o collection of elements.
Example:
my_list = [1, 2, 3, 4, 5]
e) State any two differences between type and list.
Type | List |
---|---|
type: The type() function returns the type of an object. | list: The list() function creates a new list object. |
type: Types are immutable, meaning that they cannot be changed. | list: Lists are mutable, meaning that they can be changed. |
f) What is Assertion?
An assertion in Python is a statement that checks if a condition is true. If the condition is true, the assertion succeeds and the program continues. If the condition is false, the assertion fails and the program raises an assertionerror.
Assertions can be a helpful tool for debugging and testing Python code.
g) What is __init__()?
The __init__() method in Python is a special method that is called when a new object is created. It is also known as the constructor.
The __init__() method can be used to initialize the object’s attributes.
h) What is inheritance? Give syntax to derive a child class from a parent class.
Inheritance is a programming concept that allows you to create a new class based on an existing class. The new class is called the child class, and the existing class is called the parent class. The child class inherits all of the properties and methods of the parent class.
Example:
class Animal:
def eat(self):
print("I am eating.")
class Dog(Animal):
def bark(self):
print("Woof!")
# Create a new Dog object.
dog = Dog()
# Call the eat() method on the Dog object.
dog.eat()
# Call the bark() method on the Dog object.
dog.bark()
i) What is lambda function? Give example
A lambda function in Python is a small anonymous function. A lambda function can be defined using the lambda keyword, followed by a list of arguments and a single expression.
Example:1
# Define a lambda function to double a number.
double = lambda x: x * 2
# Call the lambda function and print the result.
print(double(10))
j) Write the use of any two functions used in GUI layout Management.
1. grid()
The grid() function is used to place widgets in a grid layout. The grid layout is a two-dimensional layout that divides the window into rows and columns. Widgets can then be placed in specific rows and columns using the grid() function.
– It is use to specify the row and column for the widget.
2. pack()
The pack() function is used to place widgets in a linear layout. The linear layout can be either horizontal or vertical, depending on the value of the side argument.
– It is used to place widgets in a linear layout. The linear layout can be either horizontal or vertical, depending on the value of the side argument.
k) What is cursor?
– A cursor in Python is an object that is used to execute SQL queries and fetch the results. It is created using the cursor method of a database connection object.
– Cursors are a powerful tool that can be used to interact with databases in Python
l) Write an example for mutable and immutable types.
Mutable types are those that can be changed after they are created.
- Lists
- Dictionaries
- Sets
- User-defined classes
Immutable types are those that cannot be changed after they are created.
- Strings
- Numbers
- Tuples
- Booleans
Section - B
Answer any Four questions. (4x5=20)
1. Explain features of python:
- Simple and easy-to-learn syntax: Python has a simple and readable syntax, making it easy to learn and use, especially for beginners.
- Interpreted language: Python is an interpreted language, which means that it does not require compilation before execution, making it faster and easier to
debug. - Object-oriented programming: Python supports object-oriented programming, allowing developers to create reusable and modular code.
- Dynamic typing: Python is dynamically typed, which means that variable types are determined at runtime, allowing for more flexible and adaptable code.
- Extensive standard library: Python comes with a large standard library that provides a wide range of tools and modules for various tasks, from handling regular expressions to network programming.
- Cross-platform: Python code can be run on multiple operating systems, including Windows, Linux, and macOS, making it a versatile language for developing applications.
- Large and active community: Python has a large and active community of developers who contribute to open-source projects and provide support to beginners.
- Third-party packages: Python has a vast collection of third-party packages available on the Python Package Index (PyPI) that can be easily installed using the pip package manager, making it easy to add functionality to your code.
- High-level language: Python is a high-level language, meaning it provides abstractions that simplify complex tasks and make it easier to write code.
- Integration capabilities: Python can easily integrate with other languages and technologies, including C/C++, Java, and .NET, making it a popular choice for developing applications with diverse technology stacks.
2. Describe various string operations.
1. Concatenation: In Python, the + operator is used for string concatenation. It allows you to join two or more strings into a single string. Here is an example:
Example:
str1= "Hello"
str2 = "World"
result =strl+""+str2
print(result) # Output: "Hello World"
2. Comparison: Python provides several operators for string comparison, including ==, !=, <, >, <=, and >=, These operators compare two strings lexicographically, character by character.
Example:
str1 = "apple"
str2 = "banana"
print(str1 == str2) # Output: False
print(str1 <str2) # Output: True
3. Slicing and Joining: You can extract a substring from a string by using the slicing operator : You can also join two or more strings into a single string using the join() method.
Example:
# Slicing
str1 = "Hello World"
substring = str1[0:5] # Extract the first five characters
print(substring) # Output: "Hello"
# Joining
list_of_strings = ["apple", "banana", "cherry"]
separator =", "
result = separator.join(list_of_strings)
print(result) # Output: "apple, banana, cherry"
4. Traversing: You can traverse a string using a loop or a list comprehension.
Example:
str1 = "Hello World"
for character in str1:
print(character)
5. Format Specifiers: You can use format specifiers to format a string in a specific way. The % operator is used to format a string.
Example:
name = John"
age = 30
print("My name is %s and | am %d years old." % (name, age))
6. Escape Sequences: Escape sequences are used to represent special characters in a string. They are preceded by a backslash (\). Here are some common escape sequences:
7. Raw and Unicode Strings: In Python, you can create raw strings by prefixing the string literal with an r. This means that escape sequences will be ignored. You can also create Unicode strings by prefixing the string literal with a u.
Example:
# Raw string
str1 = r"C:\Users\John\Documents"
print(str1) # Output: "C:\Users\John\Documents"
# Unicode string
str2 = u"\u03a3"
print(str2) # Output: "="
3. Explain various conditional statements with syntax & example.
1. if: The if statement is used to check if a condition is true, and execute a block of code if the condition is true.
Example:
x=5
ifx > 0:
print("x is positive") #output x is positive
2. if else: The if else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false.
Example:
x=10
if x> 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
3. if elif else: elif ladder: In Python, the elif ladder is a construct that allows you to chain multiple if and else statements together, The elif statement is short for “else if,” and it allows you to check for additional conditions after the initial if statement.
Using an elif ladder can be a more efficient way of testing multiple conditions than using separate if statements for each condition.
Example:
x=10
ifx > 20:
print("x is greater than 20")
elifx > 15:
print("x is greater than 15 but less than or equal to 20")
elifx > 10:
print("x is greater than 10 but less than or equal to 15")
else
print("x is less than or equal to 10")
Iterations/Looping: iterations or loops are used to execute a block of code repeatedly. There are two main types of loops in Python: for loops and while loops.
4.while loop: A while loop is used to execute a block of code repeatedly as long as a certain condition is true.
Syntax:
while condition:
# code block to be executed
count = 0
while count < 10:
print(count)
count += 1
5. for loop: The for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The basic
Syntax:
for variable in sequence/range():
# code block to be executed
on
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
4. Explain various functions used in regular expression.
Regular expressions, also known as regex or regexp, are a sequence of characters that define a search pattern. They can be used to search, edit, or manipulate text.
Regular expressions are used in a variety of programming languages, including Python. The Python re module provides a number of functions for working with regular expressions.
Most commonly used regular expression functions in Python:
- re.compile() – Compiles a regular expression pattern into a regular expression object.
- re.search() – Searches for the first occurrence of a regular expression pattern in a string.
- re.match() – Attempts to match the entire string against a regular expression pattern.
- re.findall() – Returns a list of all occurrences of a regular expression pattern in a string.
- re.sub() – Substitutes a string for all occurrences of a regular expression pattern in a string.
In addition to these basic functions, the re module also provides a number of more advanced functions, such as:
- re.split() – Splits a string into a list of substrings based on a regular expression pattern.
- re.finditer() – Returns an iterator over all occurrences of a regular expression pattern in a string.
- re.purge() – Clears the compiled regular expression cache.
- re.debug() – Prints debugging information about a regular expression.
Example:
# Compile a regular expression pattern
regex = re.compile('[a-z]+')
# Search for the first occurrence of the pattern in a string
match = regex.search("Hello, world!")
# If the pattern is found, print the match
if match:
print(match.group())
# Find all occurrences of the pattern in a string
matches = regex.findall("Hello, world!")
# Print all of the matches
for match in matches:
print(match)
# Substitute a string for all occurrences of the pattern in a string
string = re.sub('[a-z]+', 'X', "Hello, world!")
# Print the modified string
print(string)
5. Describe various operations performed on list.
Operations on Lists: there are several operations that you can perform on lists to manipulate them in various ways. Here are some common operations on lists:
1. Indexing: You can access an individual item in a list using its index, which starts at 0. For example, to access the first item in a list:
my_list = [1, 2, 3]
print(my_list[0]) # Output: 1
2. Slicing: You can create a new list that contains a subset of the items in the original list by using slicing. Slicing uses a colon to separate the start and end indices, and returns a new list containing the items from the start index up to, but not including, the end index. For example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
3. Concatenation: You can combine two or more lists into a single list using concatenation, which uses the + operator. For example:
list = (1, 2, 3]
list2 = [4, 5, 6]
concatenated _list = list1 + list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
4. Repetition: You can create a new list that contains multiple copies of the items in the original list using repetition, which uses the * operator. For example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
5. Length: You can determine the number of items in a list using the len() function. For example:
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
6. Membership: You can check if an item is in a list using the in keyword. For example:
my_list = [1, 2, 3]
print(2 in my_list) # Output: True
print(4 in my_list) # Output: False
7. Sorting: You can sort a list in ascending or descending order using the sort() method. For example:
my_list = [3, 1, 2]
my_list.sort() # sorts in ascending order
print(my_list) # Output: [1, 2, 3]
my_list.sort(reverse=True) # sorts in descending order
print(my_list) # Output: [3, 2, 1]
8. Reversing: You can reverse the order of items in a list using the reverse() method. For example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
6. Explain the functions used for reading single and multiple lines of query execution.- , ,
read_single_line_query(query): This function reads a single line query and returns the query string. The syntax for this function is as follows:
def read_single_line_query(query):
"""Reads a single line query and returns the query string."""
return query
read_multiple_lines_query(query): This function reads multiple lines query and returns the query string. The syntax for this function is as follows:
def read_multiple_lines_query(query):
"""Reads multiple lines query and returns the query string."""
query_string = ""
for line in query.splitlines():
query_string += line
return query_string
Section - C
Answer any four questions. (4x10=40)
7. a (5 marks) & b (5 marks)
a) What is a function? Demonstrate defining and calling user defined function with syntax and example.
Functions: A function is a block of reusable code that performs a specific task. It is defined using the def keyword, followed by the name of the function and a set of parentheses that may contain parameters or arguments.
The function block is indented and can contain any number of statements, including return statements.
Syntax:
def function_name(parameter1, parameter2, ...):
# function block
statementl
statement2
Example:
def add(num1, num2): # Function Definition
sum =num1 + num2
return sum
a=10
b=20
res = add(a,b) # Function Call & Passing arguments
print("Result from add = ",res)
b) Write a python program to calculate Factorial of a number using user defined function.
def factorial(n):
if n ==0:
return 1
else:
return n * factorial(n-1)
Or
def factorial(n):
"""Calculates the factorial of a number.
Args:
n: The number to calculate the factorial of.
Returns:
The factorial of n.
"""
if n < 0:
raise ValueError("n must be a non-negative integer.")
elif n == 0:
return 1
else:
return n * factorial(n - 1)
# Calculate the factorial of 5
factorial_of_5 = factorial(5)
# Print the result
print(factorial_of_5)
8. (a) 5 marks & (b) 5 marks
a) Write a python program to demonstrate any 5 operations performed on dictionary.
def dictionary_demo():
# Create a dictionary
dictionary = {"key1": 1, "key2": 2, "key3":3}
print("** Dictionay Opeartions **")
print("\n1.printing the dictionary : ",dictionary)
dictionary["key2"] = 5
print("\n2.Modified dictionary:", dictionary)
print("\n3.Add a new key-value pair to the dictionary ")
dictionary["key4"] = 4
print(dictionary)
print("\n4.Remove a key-value pair from the dictionary ")
del dictionary["key2"]
print(dictionary)
print("\n5.Check if a key is present in the dictionary :")
if "key1" in dictionary:
print("Key 'key1' is present in dictionary ")
print("\n6.Access a value in the dictionary : ",end="")
print(dictionary["key1"])
if __name__=="__main__":
dictionary_demo()
b) Explain the working of any five GUI widgets with example.
1. Button: A button is a widget that allows the user to perform an action when they click on it. Buttons can be used to start a program, open a file, or submit a form.
To create a button in Python, you can use thetkinter.Button()
Class. The tkinter.Button()
class takes several arguments, including the text to display on the button and the command to execute when the button is clicked.
For example, the following code creates a button that prints “Hello, world!” to the console when it is clicked:
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click me!", command=lambda: print("Hello, world!"))
button.pack()
root.mainloop()
2. Label: A label is a widget that displays text to the user. Labels can be used to display instructions, titles, or other information.
To create a label in Python, you can use the tkinter.Label()
class. The tkinter.Label()
class takes several arguments, including the text to display on the label.
For example, the following code creates a label that displays the text “Enter your name:” to the user:
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Enter your name:")
label.pack()
root.mainloop()
To create an entry field in Python, you can use the tkinter.Entry()
class. The tkinter.Entry()
class takes several arguments, including the default text to display in the entry field.
For example, the following code creates an entry field that allows the user to enter their name:
import tkinter as tk
root = tk.Tk()
entry_field = tk.Entry(root)
entry_field.pack()
root.mainloop()
To create a checkbox in Python, you can use the tkinter.Checkbutton()
class. The tkinter.Checkbutton()
class takes several arguments, including the text to display next to the checkbox and the variable to store the checkbox’s state.
For example, the following code creates a checkbox that allows the user to select whether they want to receive email notifications:
import tkinter as tk
root = tk.Tk()
email_notifications_checkbox = tk.Checkbutton(root, text="Receive email notifications?")
email_notifications_checkbox.pack()
root.mainloop()
To create a radio button in Python, you can use the tkinter.Radiobutton()
class. The tkinter.Radiobutton()
class takes several arguments, including the text to display next to the radio button and the variable to store the radio button’s state.
For example, the following code creates a group of radio buttons that allow the user to select their favorite color:
import tkinter as tk
root = tk.Tk()
red_radio_button = tk.Radiobutton(root, text="Red", variable=color_variable, value="red")
green_radio_button = tk.Radiobutton(root, text="Green", variable=color_variable, value="green")
blue_radio_button = tk.Radiobutton(root, text="Blue", variable=color_variable, value="blue")
red_radio_button.pack()
green_radio_button.pack()
blue_radio_button.pack()
root.mainloop()
9. Explain the keywords used in handling exceptions Demonstrate with an programming example.
- try block: This block contains the code that you want to execute. If an exception occurs within this block, the corresponding except block will be executed.
- except block: This block contains the code that you want to execute if an exception occurs within the try block. You can specify the type of exception that you want to catch using the except keyword followed by the exception type.
- else block: This block contains the code that you want to execute if no exceptions occur within the try block. It is optional and is executed after the try block and before the finally block.
- finally block: This block contains the code that you want to execute regardless of whether an exception occurred or not. It is executed after the try block and any except or else blocks.
Exception Handling using try, except, else and finally block:
a=10
=0
c=0
try:
e=a4)/'b
except ZeroDivisionError:
print("Cant Divide by Zero...")
else:
print("Result = ",c)
finally:
print("Clean the resources from try")
10. Explain in detail the steps of database connectivity with example.
- Install a database driver. A database driver is a Python package that allows Python to communicate with a specific database. For example, to connect to a MySQL database, you would need to install the
mysql.connector
Python package. - Create a connection object. To create a connection object, you can use the
connect()
function provided by the database driver. Theconnect()
function takes a number of arguments, including the hostname, username, password, and database name. - Create a cursor object. A cursor object is used to execute SQL queries on the database. To create a cursor object, you can call the
cursor()
method on the connection object. - Execute a SQL query. To execute a SQL query, you can call the
execute()
method on the cursor object. Theexecute()
method takes the SQL query as an argument. - Fetch the results. If the SQL query returns any results, you can fetch them using the
fetchone()
,fetchall()
, orfetchmany()
methods on the cursor object. - Close the cursor and connection objects. Once you have finished working with the database, you should close the cursor and connection objects to avoid wasting resources.
import mysql.connector
# Create a connection object.
conn = mysql.connector.connect(host="localhost", user="root", passwd="password", database="mydb")
# Create a cursor object.
cursor = conn.cursor()
# Execute a SQL query.
cursor.execute("SELECT * FROM users")
# Fetch the results.
results = cursor.fetchall()
# Close the cursor and connection objects.
cursor.close()
conn.close()
# Print the results.
for row in results:
print(row)
11. Write a short note on any two of the following
a) File operations
- open() – Opens a file for reading, writing, or appending.
- read() – Reads data from a file.
- write() – Writes data to a file.
- close() – Closes a file.
# Open the file for reading.
file = open("myfile.txt", "r")
# Read the entire contents of the file.
contents = file.read()
# Close the file.
file.close()
# Open the file for writing.
file = open("myfile.txt", "w")
# Write some data to the file.
file.write("This is some data to write to the file.")
# Close the file.
file.close()
b) Map () functions
The map() function in Python is a built-in function that allows you to apply a function to each element of an iterable and return a new iterable with the transformed results. The map() function takes two arguments: the function to apply and the iterable to apply it to.
the following code uses the map() function to double all of the elements in a list:
def double(x):
return x * 2
list_of_numbers = [1, 2, 3, 4, 5]
doubled_list = map(double, list_of_numbers)
for number in doubled_list:
print(number)
Output:
2
4
6
8
10
c) Meta characters.
Metacharacters in Python are characters that have a special meaning in regular expressions. They are used to control how regular expressions are matched and interpreted.
Metacharacters can be used to create complex and powerful regular expressions. Some common metacharacters in Python:
.
: Matches any character except the newline character (\n).^
: Matches the beginning of a string.$
: Matches the end of a string.*
: Matches zero or more occurrences of the preceding character or regular expression.+
: Matches one or more occurrences of the preceding character or regular expression.?
: Matches zero or one occurrence of the preceding character or regular expression.|
: Matches either of the preceding characters or regular expressions.