KEMBAR78
B22EN0304 Sol Python | PDF | Anonymous Function | Bracket
0% found this document useful (0 votes)
19 views12 pages

B22EN0304 Sol Python

Uploaded by

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

B22EN0304 Sol Python

Uploaded by

chaya02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SCHEME AND SOLUTION

INSTRUCTIONS TO PAPER SETTER FOR THE PREPARATION OF SCHEME AND SOLUTION

1. The objective of preparation of scheme and solution is to ensure a uniform valuation among
the evaluators.
2. The solution should indicate the expected important points/ steps / graphs / drawings /
circuits / figures / calculations/ tables and final numerical answers along with the marks
allocation for each of these.
3. Lengthy attachments from books/textbooks/notes etc. shall NOT BE ACCEPTED as scheme &
solution.
4. Please bear in mind that the students have to complete answering the entire question paper in
the given answer booklet within 3hrs (no additional answer sheet will be provided)
5. Marks should be allocated for step-wise development of concepts / answers / figures /
circuits / graph / exactness / accuracy in numerical values / units / calculations.
6. Split marks to be given must be indicated.
7. A scheme & solution does not mean the splitting of final marks into its component parts
(example 2 + 2 + 4 + 2). It has to clearly show the expected answers / response for each
component. A scheme and solution which merely shows the component marks is liable to be
rejected.
8. The figures / drawings / circuit diagrams that are part of answers shall also be given in solution
to ensure that the same is being uniformly evaluated by all the examiners.
9. Answers shall not be in the form of references / citations where authors name / title of the
book / chapter numbers / page numbers / paragraphs / figures etc. are provided.
School of ECE Academic year: 2024-25
Course Name: Python Programming and applications
Course Code : : B23EP0405 Semester:4
Q No. Marks
1.a
Write the differences between List, Tuple and Set. 5

soln:
Feature List Tuple Set
Mutability Mutable Immutable Mutable
Ordering Ordered Ordered Unordered
Duplicates Allowed Allowed Not allowed
Comprehensiven Stores various data Stores various
ess types data types Stores unique data types
Creation Square brackets [] Parentheses () Curly braces {}
Append, remove, Add, remove, check
Common insert, sort, index, Cannot be membership, union, intersection,
Operations slicing modified difference

each difference -1M

1.b Make a list of python operators and explain arithmetic and comparison operators in detail.
7
Category Operators
Arithmetic +, -, *, /, //, %, **
Comparison #ERROR!
Logical and, or, not
Assignment #ERROR!
Membership in, not in
Identity is, is not
Bitwise &,
Special @, :, +, *

list of operators-3M
Arithmetic-2M
Comparision-2M

Write the syntax of looping statements. Write a program to display numbers from 1 to 10
except 6 and 8.

1.C PROGRAM:
for num in range(1, 11): 8
if num == 6 or num == 8:
continue
else:
print(num)

Synatx of while -2M


syntax of for-2m
Program-4M
Explain the following methods with an example for each.
a). format() -1M
b) range() -1M
1.D c) input() -1M 5
d) del -1M
e) len()-1M

Mention the different data types of Python programming language and explain any two
with an example for each?
Numeric Data Types:
2.a
Integers (int): Used to represent whole numbers, including positive, negative, and zero.
8
Floating-Point Numbers (float): Used to represent real numbers with decimal places.
Complex Numbers (complex): Represent numbers of the form a + bi, where a and b are real
numbers and i is the imaginary unit, defined as the square root of -1.
Lists (list)
Tuples (tuple)
Strings (str):
Dictionaries (dict)
Sets (set)

List of data types: 2M


Any two datatypes with explanation an examples: 6M

Write a python program to read two inputs from user, perform all arithmetic operation and
display the results.
2.b
num1 = float(input("Enter the first number: "))
6
num2 = float(input("Enter the second number: "))

# Add the two numbers


sum = num1 + num2

# Print the result


print("The sum of", num1, "and", num2, "is:", sum)

Reading-2M
All arithmetic operations-4M

x= [8, 6.5, 2, “xyz”], Demonstrate append, extend, remove, sort, reverse methods for the
given list. (Assume the values if necessary)

append-1M
2.c
extend-1M
5
remove-1M
sort-1M
reverse-1M

List out the features of python programming and explain briefly


Easy to Learn and Read
2.d Interpreted Language 6
Dynamically Typed
Object-Oriented Programming (OOP) Paradigm
Extensive Standard Library
Third-Party Libraries and Frameworks
Platform Independence
Versatility and Wide Applications
Free and Open-Source
Active Community and Support

Any 6 features with explanation-6M

Explain the syntax of lambda function and create a lambda function to perform
multiplication of two numbers.

3.a syntax of lambda function-2M 5M


lambda function to perform multiplication of two numbers. -3M

solution:
lambda arguments: expression

multiply = lambda x, y: x * y

result = multiply(5, 3)
print(result)

What are different types of function arguments? Explain each with an example.

Positional Arguments:
3.b Keyword Arguments: 6M
Default Arguments:
Arbitrary Positional Arguments (args)

each with example-2M

Write a program to create a class named student with attributes Name, and SRN
and member function show to display the data members of the object. Create two
objects of student class, read and display the contents of objects
3.c
class Student: 8M
def __init__(self, name, srn):
self.name = name
self.srn = srn
#2M

def show(self):
print("Name:", self.name)
print("SRN:", self.srn)
#2M
s1 = Student("Alice", 12345)
s2 = Student("Bob", 54321)
#2M

s1.show()
s2.show()

#1M

List out built-in class attributes and explain their functionality.

name: This attribute returns the name of the class as a string. It is equivalent to the
3.d class name itself.
5M
module: This attribute returns the name of the module where the class is defined. It
indicates the module that owns the class.

doc: This attribute returns the docstring associated with the class. It provides
documentation and explanation about the purpose and usage of the class.

bases: This attribute returns a tuple containing the base classes of the class. It
represents the inheritance hierarchy of the class.

dict: This attribute returns a dictionary containing the class's namespace, including
all its attributes and methods. It provides access to the class's internal data and
functions.

Define class and object. Explain the features of object-oriented programming.

4.a Definitions: 1M
Features: 4M 5

Explain
i) import-2M
ii) import as -2M
4.b
iii) from import-2M 6
statements with proper example program.

Write a program to create a class named person with attributes name, and age and
member function display to display the data members of the object. Create two
objects of person class, read and display the contents of objects
4.C

7
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

#2M
def display(self):
print("Name:", self.name)
print("Age:", self.age)

#2M

p1 = Person("Alice", 30)
p2 = Person("Bob", 25)

#2M

p1.display()
p2.display()

#2M

Implement a simple calculator to perform basic arithmetic operations using


functions. Create add(), sub(), mul(), div() functions , call these functions and display
the results.
4.D

10
def add(num1, num2):
result = num1 + num2
return result

#1M

def sub(num1, num2):


result = num1 - num2
return result

#1M

def mul(num1, num2):


result = num1 * num2
return result

#1M

def div(num1, num2):


result = num1 / num2
return result
#1M

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

#1M

print("Addition Result: ", add(num1, num2))


print("Subtraction Result: ", sub(num1, num2))
print("Multiplication Result: ", mul(num1, num2))
print("Division Result: ", div(num1, num2))

#1M

What is an exception? Demonstrate how to catch an exception using try and except
block for ZeroDivisionError.
5.a
try:
6M
result = 10 / 0
except ZeroDivisionError:
print("Division by zero error.")

Explanation-2M
Complete program-4M

Write a python program to create a file named “Myfilet.txt”, write the content
“Programming Language”, read first 10 characters from the file.
5.b
6M
# Create a file named "Myfilet.txt" and write the content "Programming Language"
file_object = open("Myfilet.txt", "w")
file_object.write("Programming Language")
file_object.close()

#3M

# Read the first 10 characters from the file


file_object = open("Myfilet.txt", "r")
first_ten_characters = file_object.read(10)
file_object.close()

# Print the first 10 characters


print(first_ten_characters)

#3M

Demonstrate multiple inheritance with programming example.

Base class1-1.5M
5.C Base class 2-1.5M
7M
erived class-2M
objects and method calling-2M

Perform the following operation on directories:


i) creating a new directory, -2M
ii) listing the contents of the directory, -2M
5.D iii) changing the current working directory.-2M
6M

Create a base class person with attributes: name, age, methods: showname( ) ,
show_age( ) and derived class student with data members name, age, SRN and
college. Write a program to demonstrate single inheritance
6.a
8M
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def show_name(self):
print("Name:", self.name)

def show_age(self):
print("Age:", self.age)

#3M

class Student(Person):
def __init__(self, name, age, srn, college):
person.__init__(name, age) # Call parent class constructor
self.srn = srn
self.college = college

def show_details(self):
person.show_name() # Access parent class method using super()
person.show_age() # Access parent class method using super()
print("SRN:", self.srn)
print("College:", self.college)

#3M

s1 = Student("Alice", 20, 12345, "MIT")


s1.show_details()

#2M
Describe the different modes of file operations in python programming.

r (Read Mode): This mode opens a file for reading purposes. The file must already
6.B
exist, and any attempt to write to the file will result in an error.
5M
w (Write Mode): This mode opens a file for writing purposes. If the file exists, it will
be truncated (emptied) before writing begins. If the file doesn't exist, it will be
created.

a (Append Mode): This mode opens a file for appending data to the end of the file.
The file must already exist, and any writing will add new content without
overwriting existing data.

r+ (Read and Write Mode): This mode allows both reading and writing to the file.
The file must already exist.

w+ (Write and Read Mode): This mode allows both writing and reading to the file. If
the file exists, it will be truncated (emptied) before writing begins. If the file doesn't
exist, it will be created.

a+ (Append and Read Mode): This mode allows both appending and reading to the
file. The file must already exist.

ANY 5 MODES-EACH 1M

Explain try, except, and finally keywords used for exception handling

6.c try block-2M 6M


except-2M
finally block-2M

Write a program for


creating, -1.5M
6.d changing the current working directory-1.5M
renaming -1.5M 6M
and
removing the directory in python. - 1.5M

Demonstrate
indexing,-2M
slicing, -2M
7.a shaping -2M 8M
and sort -2M
operations on NumPy arrays.

Write a python program to demonstrate pandas data structures: Series and


DataFrames
7.b
import pandas as pd
8M
# Create a Series from a list of data
data = [1, 2, 3, 4, 5]
s = pd.Series(data)
print(s)

#4M

# Create a DataFrame from a dictionary of data


data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [30, 25, 22]}
df = pd.DataFrame(data)
print(df)

#4M

Explain the different applications of Matplotlib and write a program to plot a scatter
graph using Matplotlib.

7.C
import matplotlib.pyplot as plt 9M

# Generate sample data


x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 2, 1]

# Create the scatter plot


plt.scatter(x, y)

# Add labels and title


plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Scatter Plot Example')

# Show the plot


plt.show()

Applications-3M

Program-6M
Explain the applications of Pandas, and write a program to filter and sort data in a
pandas DataFrames.

8.a Applications of Pandas-2M


Program-5M 7M

import pandas as pd

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'], 'Age': [30, 25, 22, 33, 27], 'City':
['New York', 'Chicago', 'Los Angeles', 'Houston', 'Philadelphia']}
df = pd.DataFrame(data)

# Filter data by age


filtered_df = df[df['Age'] > 25]

# Sort data by name


sorted_df = df.sort_values(by='Name', ascending=True)

# Print the filtered and sorted DataFrames


print("Filtered DataFrame:")
print(filtered_df)

print("\nSorted DataFrame:")
print(sorted_df)

Explain how NumPy arrays are different from python lists. Write a program to
create 1D, 2D, and 3D arrays using Numpy.
8.b
DIFFERENCES-2M 7M

1D ARRAY-1M
2D ARRAY-2M
3D ARRAY-2M

import numpy as np

data = [1, 2, 3, 4, 5]
array1d = np.array(data)
print("1D NumPy array:", array1d)

import numpy as np

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


array2d = np.array(data)
print("2D NumPy array:")
print(array2d)

import numpy as np
data = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
array3d = np.array(data)
print("3D NumPy array:")
print(array3d)

Write a python program to read a csv file using Pandas and display the contents.

8.C import pandas as pd

# Specify the CSV file path 6M


csv_file_path = "data.csv"

# Read the CSV file into a Pandas DataFrame


data = pd.read_csv(csv_file_path)

# Display the DataFrame contents


print(data)

Each step-1.5M

Write a python program to plot a line graph using Matplotlib.

import matplotlib.pyplot as plt


8.D 5M
# Generate sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 2]

# Create the line plot


plt.plot(x, y)

# Add labels and title


plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Line Graph Example')

# Show the plot


plt.show()

Each step-1M

Signature of the paper setter with Date: Madan H T

Signature of the scrutinizer

You might also like