Python ct2
Python ct2
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.
Syntax:
Example:
file.close()
Ans:len()
Returns length of an object.
len("Hello") → 5
max()
max([2, 3, 8, 5]) → 8
sorted()
type()
MORE functions:
print("Hello", name)
EX: print(abs(-10)) # 10
5.Illustrate with an example Method Overloading.
class Example:
print(f"Sum: {a + b}")
else:
print("No arguments")
obj = Example()
6. Write a Python program to check for zero division error exceptions.
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Result:", result)
Output:
Enter numerator: 1
Enter denominator: 0
4. Displaying histograms
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
5.'b' – Binary mode (used with other modes like 'rb', 'wb')
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)
import greetings
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):
def print_details(self):
print("Name:", self.name)
# Example usage
s = Student()
s.read_details()
s.print_details()
o/p:
Enter name: n
Name: n
Roll No: 32
try:
result = 10 / num
except ZeroDivisionError:
else:
finally:
print("Program ended.")
o/p
Enter a number: 0
Program ended.
class Person:
self.name = name
class Student(Person):
super().__init__(name)
self.roll = roll
class Student:
self.name = name
self.roll = roll
Example:
f = open("demo.txt", "w")
f.write("Hello Nishi!\n")
f.writelines(["Line1\n", "Line2\n"])
f.close()