Python programming
Python programming
class Student:
job=”study”
def __init__(self, rol_no, name):
self.rol_no = rol_no
self.name = name
● self refers to the current instance of the class. It is used to access attributes and
methods of the class.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says Woof!")
d = Dog("Buddy")
d.bark()
2. What is a class in Python? Create a Book class with attributes title, author, and
price. Add a method to display all details.
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def display(self):
print(f"Title: {self.title}, Author: {self.author}, Price: ${self.price}")
1. Create a class Student with methods to input marks and calculate grade.
● Class is a blueprint for creating objects. Class contains attributes and methods to
represent characteristics and behaviours of objects.
class Student:
def __init__(self, name):
self.name = name
self.marks = 0
def calculate_grade(self):
if self.marks >= 90:
return "A"
elif self.marks >= 75:
return "B"
elif self.marks >= 50:
return "C"
else:
return "F"
2. Create a class Employee with attributes name and salary, and a method to calculate
bonus.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def calculate_bonus(self):
return self.salary * 0.10 # 10% bonus
3. Create a class Book with attributes title, author, and price. Add a method to display
all details.
class Book:
def display(self):
print(f"Title: {self.title}, Author: {self.author}, Price: ${self.price}")
4. Create a class BankAccount with methods to deposit, withdraw, and show balance.
class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def show_balance(self):
print(f"Balance: ${self.balance}")
5. Create a class Library to manage books with methods to add and issue books.
class Library:
def __init__(self):
self.books = []
l1=Library()
book1={"id":1, "book name": "Learn Python", "author": "Dhan
Bahadur"}
book2={"id":2, "book name": "Learn GIS", "author": "Gyan
Bahadur"}
book3={"id":3, "book name": "Learn SDI", "author": "Dipu
Bahadur"}
l1.add_book(book1)
l1.add_book(book2)
l1.add_book(book3)
l1.add_book(book1)
l1.issue_book(book1)
1. What is OOP? How can you create a class in Python? Write a program to implement
a Student class which has a method to calculate CGPA.
class ClassName:
def __init__(self, parameters):
self.attribute1 = value1
self.attribute2 = value2
# more attributes if needed
def method1(self):
# code for method1
pass
def method2(self, parameters):
# code for method2
pass
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks # list of marks
def calculate_cgpa(self):
return sum(self.marks) / len(self.marks)
2. What is object-oriented programming? Create a class Car with properties like brand
and price and a method to display info.
class Car:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def display_info(self):
print(f"Brand: {self.brand}, Price: ${self.price}")
3. Define class and object in Python. Create a class Library to manage books with
methods to add and issue books.
Class is a blueprint for creating objects. Class contains attributes and methods to represent
characteristics and behaviours of objects.
An object is an instance of a class. Once a class is defined (like a blueprint), you can
create objects from it to store real data and use its methods.
class Library:
def __init__(self):
self.books = []
l1=Library()
book1={"id":1, "book name": "Learn Python", "author": "Dhan
Bahadur"}
book2={"id":2, "book name": "Learn GIS", "author": "Gyan
Bahadur"}
book3={"id":3, "book name": "Learn SDI", "author": "Dipu
Bahadur"}
l1.add_book(book1)
l1.add_book(book2)
l1.add_book(book3)
l1.add_book(book1)
l1.issue_book(book1)
4. Explain how class and object are implemented in Python with an example of a
BankAccount class.
Class is a blueprint for creating objects. Class contains attributes and methods to represent
characteristics and behaviours of objects.
An object is an instance of a class. Once a class is defined (like a blueprint), you can
create objects from it to store real data and use its methods.
acc = BankAccount("Alice")
acc.deposit(500)
acc.withdraw(100)
acc.show_balance()
5. What is a class in Python? Create a Book class with attributes title, author, and
price.
Already answered above.
An exception is an error that occurs during the execution of a program. When Python
encounters an error, it raises an exception, which interrupts the normal flow of the program.
Common examples include:
Python provides a mechanism called exception handling to manage runtime errors using
the following keywords:
1. try block
2. except block
This block catches and handles specific exceptions that occur in the try block.
3. else block
4. finally block
This block is always executed, whether or not an exception was raised. It's often used to
clean up resources like files or connections.
Example:
try:
except ZeroDivisionError:
except ValueError:
else:
finally:
print("Execution completed.")
Explanation:
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
2. What is the purpose of the finally block in exception handling? Explain with an
example.
The finally block is used to execute code after the try and except blocks, regardless
of whether an exception occurred. It's commonly used to release resources (like closing files
or database connections).
Example:
try:
print(file.read())
except FileNotFoundError:
finally:
3. Write a Python program to handle multiple exceptions using except and finally.
try:
print("Result:", x / y)
except ValueError:
except ZeroDivisionError:
finally:
print("Execution completed.")
Definition:
Exceptions are errors that occur during the execution of a program. Python provides a way
to handle these exceptions using try, except, else, and finally blocks.
Example:
try:
print("Result:", result)
except ValueError:
except ZeroDivisionError:
2. Write a Python program to handle try, except, else, and finally blocks together.
try:
result = a / b
except ZeroDivisionError:
except ValueError:
else:
print("Result:", result)
finally:
Absolutely! Here's an elaborated answer for Conceptual Question 1 from your chapter:
📘 Q1: Write short notes on data visualization using Python.
Answer:
Data visualization is the graphical representation of information and data. In Python, data
visualization is mainly done using libraries such as Matplotlib, Seaborn, and Pandas.
These libraries help in creating various types of charts and graphs that make it easier to
understand patterns, trends, and insights from data.
● Exploring datasets
For example, when analyzing a student’s marks in different subjects, instead of looking at
raw numbers, a bar chart or pie chart can show performance visually. Similarly, a line
graph can show sales growth over time.
Concept:
Data visualization helps convert numerical data into visual formats to quickly interpret
patterns and trends.
Example code:
# Histogram
data = np.random.randn(1000)
plt.hist(data, bins=20)
plt.title("Histogram")
plt.show()
# Scatter
x = [1, 2, 3, 4, 5]
y = [5, 4, 6, 7, 8]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.show()
# Line Chart
plt.plot(x, y)
plt.title("Line Chart")
plt.show()
Short Note:
Data visualization allows us to analyze large data sets quickly by presenting them visually.
Example (Histogram):
data = np.random.randn(500)
plt.hist(data, bins=15, color='green')
plt.title("Histogram Example")
plt.show()
💻 Programming Questions
Group B (Short)
plt.bar(countries, population)
plt.title("Population of 5 Countries")
plt.ylabel("Population (in millions)")
plt.show()
import numpy as np
Group C (Long)
import numpy as np
x = np.arange(1, 11)
y = np.random.randint(50, 100, 10)
# Histogram
plt.hist(y, bins=5)
plt.title("Histogram of Marks")
plt.show()
# Scatter
plt.scatter(x, y)
plt.title("Scatter Plot of Marks")
plt.show()
# Line plot
plt.plot(x, y, marker='o')
plt.title("Line Plot of Marks")
plt.show()
# Line plot
plt.plot(x, marks, label="Line", marker='o')
# Scatter plot
plt.scatter(x, marks, label="Scatter", color='red')
plt.xticks(x, students)
plt.title("Student Marks")
plt.legend()
plt.show()