[go: up one dir, main page]

0% found this document useful (0 votes)
2 views17 pages

Python programming

The document provides an overview of Python programming concepts, particularly focusing on Object-Oriented Programming (OOP), class and object definitions, and exception handling. It includes examples of various classes such as Student, Employee, Book, and BankAccount, along with their methods and attributes. Additionally, it covers data visualization techniques using libraries like Matplotlib, including different chart types and their applications.

Uploaded by

Usha Banzzara
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)
2 views17 pages

Python programming

The document provides an overview of Python programming concepts, particularly focusing on Object-Oriented Programming (OOP), class and object definitions, and exception handling. It includes examples of various classes such as Student, Employee, Book, and BankAccount, along with their methods and attributes. Additionally, it covers data visualization techniques using libraries like Matplotlib, including different chart types and their applications.

Uploaded by

Usha Banzzara
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/ 17

Very Short Answer Questions

1. Define a class and an object in Python.

●​ Class is a blueprint for creating objects.


○​ It defines the structure of objects with member variables and methods.
○​ Member variables represent attributes or characteristics of objects.
○​ Methods represent the behavior or capabilities of the objects. ​

●​ Object is an instance of a class. ​

class Student:
​ job=”study”
def __init__(self, rol_no, name):
​ ​ self.rol_no = rol_no
self.name = name

s1 = Student("46, Dhana") # s1 is an object

2. What is the purpose of self in Python classes?

●​ self refers to the current instance of the class. It is used to access attributes and
methods of the class.​

Short Answer Questions (4 marks each – Theory)

1. What is OOP in Python? Explain with an example.

●​ OOP (Object-Oriented Programming) is a paradigm based on the concept of


"objects" that contain data and methods. Python implements concepts of abstraction,
polymorphism, encapsulation, Inheritance using features like self, _init_, super(),
pass etc.​

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}")

Programming Questions (4 marks each – Coding)

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 input_marks(self, marks):


self.marks = marks

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 __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}")

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 deposit(self, amount):


self.balance += amount

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient balance")

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 = []

def add_book(self, book):


self.books.append(book)

def issue_book(self, book):


if book in self.books:
self.books.remove(book)
print(book["book name"], "book is issued.")
else:
print("Book not available.")

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)

Long Answer Questions (10 marks each)

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.

●​ OOP (Object-Oriented Programming) is a paradigm based on the concept of


"objects" that contain data and methods. Python implements concepts of abstraction,
polymorphism, encapsulation, Inheritance using features like self, _init_, super(),
pass etc.
●​ Class in python contain class attributes, _init method to initialize(construct) objects,
attributes, and other methods.
●​ Syntax for defining class

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)

s = Student("John", [85, 90, 78])


print("CGPA:", s.calculate_cgpa())

2. What is object-oriented programming? Create a class Car with properties like brand
and price and a method to display info.

●​ OOP (Object-Oriented Programming) is a paradigm based on the concept of


"objects" that contain data and methods.
●​ OOP is a programming paradigm in which everything is represented in the form of
objects. Objects are entities in a program with attributes and methods.

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 = []

def add_book(self, book):


self.books.append(book)

def issue_book(self, book):


if book in self.books:
self.books.remove(book)
print(book["book name"], "book is issued.")
else:
print("Book not available.")

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.

Chapter 5: Exception Handling

What is an Exception in Python?

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:

●​ ZeroDivisionError: dividing by zero​

●​ ValueError: using the wrong value type​

●​ FileNotFoundError: accessing a file that doesn't exist​

How is Exception Managed in Python?

Python provides a mechanism called exception handling to manage runtime errors using
the following keywords:

1. try block

Code that might cause an exception is placed inside a try block.

2. except block

This block catches and handles specific exceptions that occur in the try block.

3. else block

If no exception occurs, the code in the else block is executed.

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:

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

num2 = int(input("Enter another number: "))

result = num1 / num2

except ZeroDivisionError:

print("You cannot divide by zero.")

except ValueError:

print("Invalid input. Please enter only numbers.")

else:

print("The result is:", result)

finally:

print("Execution completed.")

Explanation:

●​ If you divide by zero, it goes to ZeroDivisionError.​

●​ If you enter a non-integer, it goes to ValueError.​

●​ If there’s no error, it prints the result in else.​

●​ finally runs no matter what.​

1. What is the use of the try-except block in Python?​


The try-except block in Python is used to catch and handle exceptions (errors) during
runtime. It prevents the program from crashing and allows for graceful error handling.

2. What is the difference between except and finally in Python?


●​ except handles specific exceptions that occur in the try block.​

●​ finally executes code regardless of whether an exception was raised or not.​

Short Answer Questions

1. Write a Python program to handle division by zero.

try:

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

b = int(input("Enter another number: "))

result = a / b

print("Result:", result)

except ZeroDivisionError:

print("Cannot divide by zero!")

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:

file = open("data.txt", "r")

print(file.read())

except FileNotFoundError:

print("File not found.")

finally:

print("Closing the file.")


file.close()

3. Write a Python program to handle multiple exceptions using except and finally.

try:

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

y = int(input("Enter another number: "))

print("Result:", x / y)

except ValueError:

print("Invalid input. Please enter a number.")

except ZeroDivisionError:

print("Cannot divide by zero.")

finally:

print("Execution completed.")

Group C: Long Answer Questions

1. What are exceptions? Write a Python program to handle ValueError and


ZeroDivisionError.

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:

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

num2 = int(input("Enter another number: "))

result = num1 / num2

print("Result:", result)
except ValueError:

print("Input must be an integer.")

except ZeroDivisionError:

print("Cannot divide by zero.")

2. Write a Python program to handle try, except, else, and finally blocks together.

try:

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

b = int(input("Enter another number: "))

result = a / b

except ZeroDivisionError:

print("Division by zero error.")

except ValueError:

print("Invalid input. Enter only integers.")

else:

print("Result:", result)

finally:

print("Program has finished executing.")

Chapter 9: Data Visualization

1. Write short notes on data visualization using Python.

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.

Python’s visualization tools are especially useful for:

●​ Exploring datasets​

●​ Identifying trends and outliers​

●​ Presenting findings in a clear and understandable format​

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.

Common Python Libraries for Data Visualization:

1.​ Matplotlib – Basic plotting (line, bar, pie, histogram, etc.)​

2.​ Seaborn – Statistical plots and better styling (built on Matplotlib)​

3.​ Pandas Plotting – Quick plotting from DataFrame​

Benefits of Data Visualization:

●​ Makes complex data easy to understand​

●​ Helps identify patterns and relationships​

●​ Makes data more engaging and interactive

2. What are different chart types in matplotlib?

Common chart types in matplotlib:

●​ Line Chart – Shows trends over time.​

●​ Bar Chart – Compares values across categories.​


●​ Histogram – Shows distribution of data.​

●​ Pie Chart – Represents data as proportions.​

●​ Scatter Plot – Shows relationships between two numeric variables.​

3. Explain concept of data visualization. Line chart of city temperature.

Concept:​
Data visualization helps convert numerical data into visual formats to quickly interpret
patterns and trends.

Example (Line chart of city temperature):

import matplotlib.pyplot as plt

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']


temperature = [22, 24, 23, 26, 25]

plt.plot(days, temperature, marker='o')


plt.title("City Temperature Over a Week")
plt.xlabel("Days")
plt.ylabel("Temperature (°C)")
plt.grid(True)
plt.show()

4. Write short notes on chart types in matplotlib. Create histogram,


scatter, line chart.

Chart Types in matplotlib:

●​ Line chart: To show trends over time.​

●​ Histogram: To show frequency distribution of numeric data.​

●​ Scatter plot: To show correlation between two variables.​

Example code:

import matplotlib.pyplot as plt


import numpy as np

# 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()

5. Write short notes on data visualization. Program to create a


histogram/pie chart.

Short Note:​
Data visualization allows us to analyze large data sets quickly by presenting them visually.

Example (Histogram):

import matplotlib.pyplot as plt


import numpy as np

data = np.random.randn(500)
plt.hist(data, bins=15, color='green')
plt.title("Histogram Example")
plt.show()

Example (Pie Chart):

labels = ['Math', 'Science', 'English', 'Nepali', 'Social']


marks = [80, 70, 60, 50, 40]

plt.pie(marks, labels=labels, autopct='%1.1f%%')


plt.title("Marks Distribution")
plt.show()

💻 Programming Questions
Group B (Short)

1.​ Bar chart – Population of 5 countries:​

countries = ['Nepal', 'India', 'USA', 'China', 'Japan']


population = [30, 1400, 331, 1440, 125]

plt.bar(countries, population)
plt.title("Population of 5 Countries")
plt.ylabel("Population (in millions)")
plt.show()

2.​ Histogram of random numbers:​

import numpy as np

data = np.random.randint(1, 100, 100)


plt.hist(data, bins=10)
plt.title("Histogram of Random Numbers")
plt.show()

3.​ Pie chart – Marks of 5 students:​

students = ['A', 'B', 'C', 'D', 'E']


marks = [85, 90, 75, 60, 95]

plt.pie(marks, labels=students, autopct='%1.1f%%')


plt.title("Marks of 5 Students")
plt.show()

4.​ Line plot – Sales over 5 years:​

years = ['2018', '2019', '2020', '2021', '2022']


sales = [200, 250, 300, 280, 350]

plt.plot(years, sales, marker='o')


plt.title("Sales Over 5 Years")
plt.ylabel("Sales (in thousands)")
plt.show()
5.​ Bar chart – Population of 5 cities using matplotlib:​

cities = ['Kathmandu', 'Pokhara', 'Biratnagar', 'Lalitpur', 'Butwal']


population = [1200, 600, 750, 500, 400]

plt.bar(cities, population, color='skyblue')


plt.title("Population of 5 Cities")
plt.ylabel("Population (in thousands)")
plt.xticks(rotation=45)
plt.show()

Group C (Long)

1.​ Pie chart – Marks distribution of 5 subjects:​

subjects = ['Math', 'Science', 'English', 'Nepali', 'Social']


marks = [85, 90, 70, 65, 80]

plt.pie(marks, labels=subjects, autopct='%1.1f%%')


plt.title("Marks Distribution")
plt.show()

2.​ Histogram, scatter plot, and line plot from dataset:​

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()

3.​ Line and scatter plots for student marks:​

students = ['A', 'B', 'C', 'D', 'E']


marks = [78, 85, 90, 70, 95]
x = list(range(len(students)))

# 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()

You might also like