0% found this document useful (0 votes)
3 views

Python ct2

The document provides a comprehensive overview of various Python programming concepts, including lambda functions, data hiding, file handling, built-in functions, method overloading, exception handling, and object-oriented features. It includes syntax examples, advantages, and practical applications of these concepts. Additionally, it covers the use of libraries like matplotlib and the os module, along with methods for file writing and class design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python ct2

The document provides a comprehensive overview of various Python programming concepts, including lambda functions, data hiding, file handling, built-in functions, method overloading, exception handling, and object-oriented features. It includes syntax examples, advantages, and practical applications of these concepts. Additionally, it covers the use of libraries like matplotlib and the os module, along with methods for file writing and class design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

2 marks

1.​ Write the use of lambda function in Python.

Ans: Use of lambda function:


A lambda function is a small anonymous function used to perform a simple operation in a single
line. It is commonly used for short, throwaway functions, especially with functions like map(),
filter(), and sorted().
Syntax:
lambda arguments: expression
Example:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8

2.​ Define Data Hiding concept. Write two advantages of Data Hiding.

Ans: Data Hiding is an OOP concept where data members of a class are declared as private to
prevent direct access. It is achieved using a double underscore __ before the attribute name.
Advantages of Data Hiding:
1. Protects sensitive data from unauthorized access.
2. Increases the security of the application.
3. Makes the code easier to maintain and update.

3.​ Write the syntax of fopen.

ans: In Python, file handling is done using open() instead of fopen().

Syntax:

file = open("filename", "mode")

Example:

file = open("data.txt", "r") # Opens a file in read mode

file.close()

4.​Explain any four Python built-in functions with examples.

Ans:len()
Returns length of an object.

len("Hello") → 5

max()

Returns the largest item.

max([2, 3, 8, 5]) → 8

sorted()

Returns sorted list.

sorted([3, 1, 4, 2]) → [1, 2, 3, 4]

type()

Returns type of an object.

type(10) → <class 'int'>

MORE functions:

print() – Show output

EX: print("Hello, Nishi!")

input() – Take user input

​ EX: name = input("Enter your name: ")

print("Hello", name)

abs() – Get absolute value (remove minus sign)

EX: print(abs(-10)) # 10
5.​Illustrate with an example Method Overloading.

Method Overloading allows multiple methods with the same name


but different numbers of parameters.Python does not support true
method overloading but can simulate it using default arguments.

class Example:

def show(self, a=None, b=None):

if a is not None and b is not None:

print(f"Sum: {a + b}")

elif a is not None:

print(f"Single argument: {a}")

else:

print("No arguments")

obj = Example()

obj.show(5, 3) # Output: Sum: 8

obj.show(5) # Output: Single argument: 5

obj.show() # Output: No arguments

6.​ Write a Python program to check for zero division error exceptions.
try:

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

b = int(input("Enter denominator: "))

result = a / b

except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

else:

print("Result:", result)

Output:

Enter numerator: 1

Enter denominator: 0

Error: Division by zero is not allowed.

7.​Write the use of matplotlib package in Python.

Ans: matplotlib is a popular Python library used to create


visualizations like graphs, charts, and plots.

Uses of matplotlib in Python:

1. Plotting line graphs

2. Creating bar charts

3. Drawing pie charts

4. Displaying histograms

5. Customizing graph appearance

8.​List different object-oriented features supported by


Python.

ans: Object-oriented features supported by Python:

1. Encapsulation
2. Inheritance

3. Polymorphism

4. Abstraction

5. Classes and Objects

9.​ List different modes of opening a file in Python.

Ans: Different modes of opening a file in Python:

1.​'r' – Read mode​

2.​'w' – Write mode​

3.​'a' – Append mode​

4.​'r+' – Read and write mode​

5.​'b' – Binary mode (used with other modes like 'rb', 'wb')​

10. Explain module. How to define a module?

A module is a Python file (.py) that contains functions,


classes, or variables you can reuse in other programs.It helps
keep your code organized, clean, and reusable.

Defining of module:

Just create a new .py file and write some functions, classes, or
variables in it.

# greetings.py

def hello(name):
print("Hello", name)

Then you can import and use it like this:

import greetings

greetings.hello("Nishi") # Output: Hello Nishi

11. Design a class Student with data members Name, Roll No.
Create suitable methods to read and print student details.

class Student:

def __init__(self):

self.name = ""

self.roll_no = 0

def read_details(self):

self.name = input("Enter name: ")

self.roll_no = int(input("Enter roll no: "))

def print_details(self):

print("Name:", self.name)

print("Roll No:", self.roll_no)

# Example usage

s = Student()

s.read_details()
s.print_details()

o/p:

nishi@Nishis-Laptop Downloads % python3 idk.py

Enter name: n

Enter roll no: 32

Name: n

Roll No: 32

12. Explain try-except-else-finally block used in exception


handling in Python with example.

try: Code that may cause an exception.

except: Code to handle exception.

else: Code that runs if no exception occurs.

finally: Code that runs no matter what.


Example:

try:

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

result = 10 / num

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print("Result is:", result)

finally:

print("Program ended.")

o/p

Enter a number: 0

Cannot divide by zero!

Program ended.

13. Write purpose of self keyword in method.

●​ Ans: Purpose of self keyword in a method:​


The self keyword refers to the current object of the class.
●​ It is used to access variables and methods of the same
object.
●​ It must be the first parameter in instance methods.
14. Write the use of super()

Ans: super() is used to call the parent class's methods or


constructor.It helps in code reuse and avoiding repetition when
using inheritance.

class Person:

def __init__(self, name):

self.name = name

class Student(Person):

def __init__(self, name, roll):

super().__init__(name)

self.roll = roll

15. Write use of __init__() method in Python

__init__() is the constructor method in Python.It is


automatically called when an object is created.Used to
initialize attributes of the object.

class Student:

def __init__(self, name, roll):

self.name = name

self.roll = roll

16. List any four methods of the os module.


Ans: methods of the os module:

1. `os.getcwd()` – Returns the current working directory

2. `os.mkdir()` – Creates a new directory

3. `os.remove()` – Deletes a file

4. `os.rename()` – Renames a file or directory

5. `os.listdir()` – Lists all files and directories in a given


path

17. List two functions to write data in a file

write() – Writes a string to the file

writelines() – Writes a list of strings to the file

Example:

f = open("demo.txt", "w")

f.write("Hello Nishi!\n")

f.writelines(["Line1\n", "Line2\n"])

f.close()

You might also like