Assignment All Chapter Python(6thsem)
Assignment All Chapter Python(6thsem)
x is greater than 5
x equals 10
# It's essentially Python saying "do nothing here" while maintaining valid
syntax.
2. Explain loops in Python. Write a program using a while loop to print numbers from 10 to 1.
Loops in Python allow you to execute a block of code repeatedly. They are essential for
automating repetitive tasks and processing collections of data efficiently. for eg:
1. For loops
1. While loops
#coding part
#initializinf the counter
number = 10
#using while loop to print number fro 10 to 1
while number >=1:
print(number)
number -=1 #decrement the counter by 1
10
9
8
7
6
5
4
3
2
1
if n <= 1:
print("number is not prime number")
else:
for i in range(2,int(math.sqrt(n))+1):
if n % i == 0:
print(f"entered number{n} is not a prime number")
break
else:
print(f"entered number {n} is a prime number")
10
9
8
7
6
5
4
3
2
1
if condition:
do_something()
else:
pass # Deliberately do nothing
class EmptyClass:
pass
2. Write a program to demonstrate the use of if, elif, and else statements.
# Demonstrating the use of if, elif, and else statements
# Defining a number is whether negative or positive
n = int(input("enter any number"))
if n < 0:
print("you entered a negative number")
elif n == 0:
print("you entered Zero")
else:
print("you entered positive number")
#List
list_example = [1, 2, 3, "apple"]
mixed_list = [1, "Hello", 3.14, True, [1, 2, 3]] # Different data types
# operation in set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
4. Write a program to convert a list to a set and show the difference between both.
#program to convert the set from list
list = [1,2,3,4,5,1,3,5]
set = set(list) #this syntax will convert list to the set
print(set)
{1, 2, 3, 4, 5}
List : [1, 2, 3, 2, 3, 7]
Reverse list : [7, 3, 2, 3, 2, 1]
2. Write a Python program to accept name and age from user and store them in a dictionary.
#creating a user-defined dictionary of name and age
user_info = {
'name':input("enter your name"),
'age':input("enter your age")
}
print(user_info)
def greet(self):
print("Hello,", self.name)
s1 = Student("Ramesh")
s1.greet()
Hello, Ramesh
def display(self):
print("Name:", self.name)
print("Grade:", self.grade)
# Create objects
s1 = Student("Ramesh", "A")
s2 = Student("himesh", "B")
# Call method
s1.display()
s2.display()
Name: Ramesh
Grade: A
Name: himesh
Grade: B
2. What is a class in Python? Create a Book class with attributes title, author, and price. Add a
method to display all details.
In Python, a class is a blueprint for creating objects. A class defines a set of attributes
(properties) and methods (functions) that are shared by all instances (objects) of that class.
#creating a book class with attributes title, auther and price
class book:
def __init__(self,title,author,price):
self.title = title
self.author = author
self.price = price
def display(self):
print("Title:",self.title)
print("author:",self.author)
print("price:",self.price)
book1.display()
Title: Munamadan
author: Lakshmi Prasad Devkota
price: Rs.150
print(f"Grade: {grade}")
student1 = Student()
student1.input_marks()
print("student1 mark details")
student1.calculate_grade()
2. Create a class Employee with attributes name and salary, and a method to calculate bonus.
#creating the employee class
class Employee:
def __init__(self):
self.name = ""
self.salary = 0.0
self.bonus = 0.0
def input_name(self):
self.name = input("enter the name of employee")
def input_salary(self):
self.salary = float(input("enter the salary of the employee"))
def calculate_bonus(self):
bonus_percentage = float(input("enter the bonus percentage"))
self.bonus = self.salary* bonus_percentage/100
return self.bonus
def total_salary(self):
total_salary = (self.bonus + self.salary)
return total_salary
def display(self):
print ('**------monthly salary details----**')
print(f"Employee Name: {self.name}")
print(f"salary : {self.salary}")
print(f"Bonus : {self.bonus}")
print(f"Total month salary for employee {self.name} is
{self.total_salary()}")
employee1 = Employee()
employee1.input_name()
employee1.input_salary()
employee1.calculate_bonus()
employee1.display()
3. create a class Book with attributes title, author, and price. Add a method to display all
details.
class Book:
def __init__ (self):
self.title = ""
self.author = ""
self.price = 0
def display_info(self):
print(f"Title : {self.title}")
print(f"Author Name : {self.author}")
print(f"Price : Rs. {self.price}")
def enter_title(self):
self.title = input("enter title of the book")
def enter_author(self):
self.author = input("enter author name of the book")
def enter_price(self):
self.price = input("enter price of the book")
Book1 = Book()
Book1.enter_title()
Book1.enter_author()
Book1.enter_price()
Book1.display_info()
Title : Muna-madan
Author Name : Lakshmi Prasad Devkota
Price : Rs. 150
4. Create a class BankAccount with methods to deposit, withdraw, and show balance.
class BankAccount:
def __init__(self):
self.name = ""
self.accno = 0
self.balance = 0.0
def enter_name(self):
self.name = input("Enter the name of account holder")
def enter_accno(self):
self.accno = int(input("enter account number"))
def deposite(self):
amount = float(input("Enter the amount you want to deposit"))
self.balance += amount
print(f"deposited Rs. {amount} successfully")
def withdraw(self):
amount = float(input("Enter your amount you want to withdraw"))
if self.balance < amount:
print("insufficient balance")
else:
self.balance -= amount
print(f"withdrawn Rs. {amount} successfully")
def final_balance(self):
print("---Account details---")
print(f"Account Holder : {self.name}")
print(f"Account Number : {self.accno}")
print(f"Availabe Balance : {self.balance}")
ac1 = BankAccount()
ac1.enter_name()
ac1.enter_accno()
ac1.deposite()
ac1.withdraw()
ac1.final_balance()
5. Create a class Library to manage books with methods to add and issue books.
class Library:
def __init__(self):
self.books = []
# Example use:
lib = Library()
lib.add_book("Harry Potter")
lib.add_book("The Hobbit")
lib.issue_book("Harry Potter")
lib.issue_book("The Alchemist")
div = x/y
print(f"the division of number x by y is : {div}")
except ZeroDivisionError: # exception for
divide by zero error
print("you can't divide by zero.")
except ValueError: # exception for
invalid type
print("please enter a valid number")
2. What is the purpose of the finally block in exception handling? Explain with an example.
1. Always Executes Code -- Code inside finally runs whether or not an exception
occurs.
1. Resource Cleanup -- Used to close files, release memory, or disconnect from
databases/networks.
2. Maintain Program Stability -- Prevents resource leaks and ensures that cleanup
tasks are not skipped.
3. Write a Python program to handle multiple exceptions using except and finally.
# Example for try-except and finally block in Python
try:
x = int(input("enter 1st number: "))
y = int(input("enter 2nd number: "))
div = x/y
print(f"the division of number x by y is : {div}")
except ZeroDivisionError: # exception for
divide by zero error
print("you can't divide by zero.")
except ValueError: # exception for
invalid type
print("please enter a valid number only")
finally:
print("This block always run.")
div = x/y
print(f"the division of number x by y is : {div}")
except ZeroDivisionError: # exception for
divide by zero error
print("you can't divide by zero.")
except ValueError: # exception for
invalid type
print("please enter a valid number")
2. Write a Python program to handle try, except, else, and finally blocks together.
# Start of the block to catch try, expect, else, and finally together
try:
num1 = int(input("Enter the first number: "))
For I/O-bound tasks (like downloading files, reading files), GIL does not
block much, so multithreading works well.
man is happy
ok
# Start threads
t1.start()
t2.start()
Hello, Ramesh!
Hello, Sita!
Goodbye, Ramesh!
Goodbye, Sita!
Both threads are done!
def worker():
print("Worker running")
# Create thread
t = threading.Thread(target=worker)
# Start thread
t.start()
Worker running
Main thread finished
2. Write a Python program that starts 3 threads and prints thread names.
import threading
def print_name():
print("Running:", threading.current_thread().name)
Running: Thread-1
Running: Thread-2
Running: Thread-3
4. Write a Python program that simulates a bank account deposit/withdrawal with multiple
threads accessing the same balance.
import threading
balance = 1000
lock = threading.Lock()
def deposit():
global balance
with lock:
balance += 500
def withdraw():
global balance
with lock:
if balance >= 300:
balance -= 300
t1 = threading.Thread(target=deposit)
t2 = threading.Thread(target=withdraw)
t1.start(); t2.start()
t1.join(); t2.join()
print("Final Balance:", balance)
q = queue.PriorityQueue()
def worker():
while not q.empty():
priority, task = q.get()
print(f"Processing {task} with priority {priority}")
q.task_done()
# Add tasks
q.put((2, 'Low Priority'))
q.put((1, 'High Priority'))
q.put((3, 'Very Low Priority'))
for _ in range(2):
threading.Thread(target=worker).start()
q.join()
def greet(name):
print(f"Hello {name}")
t1 = threading.Thread(target=greet, args=("Alice",))
t2 = threading.Thread(target=greet, args=("Bob",))
t1.start()
t2.start()
Hello Alice
Hello Bob
4. What are the steps to execute a SELECT query in Python using MySQL?
steps involves
-Import connector
-Connect to database
-Create cursor
-Execute query
-Fetch and display result
-Close connection
#code
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='school'
)
cur = conn.cursor()
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
for r in rows:
print(r)
conn.close()
5. What are placeholders in SQL queries? Why are they used in Python programs?
Placeholder = %s
Used to safely pass values without writing directly in query.
Prevents SQL injection (hacking method).
name = input("Enter name: ")
cur.execute("SELECT * FROM students WHERE name = %s", (name,))
6. What are the possible exceptions you should handle when working with MySQL in Python?
mysql.connector.Error: General error
ProgrammingError: Wrong SQL syntax
DatabaseError: Database not found
InterfaceError: Connection problem
# You should use try-except block.
try:
conn = mysql.connector.connect(...)
cur = conn.cursor()
cur.execute("SELECT * FROM students")
except mysql.connector.Error as e:
print("Database error:", e)
7. Compare MySQLdb and mysql-connector-python. Which one are we using and why?
MySQLdb mysql-connector-python
Old, not pure Python Pure Python, official
Needs external compiler Easy to install
8. Explain how to connect a Python application with MySQL and insert a new record.
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='school'
)
cur = conn.cursor()
2. Write a Python program to read and display all rows from a students table.
import mysql.connector
# Connect to database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
# Create cursor
cur = conn.cursor()
# Close connection
conn.close()
3. Write a Python program to fetch and display only those records where marks > 80.
import mysql.connector
cur = conn.cursor()
rows = cur.fetchall()
conn.close()
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
cur = conn.cursor()
conn.commit() # Save to DB
print("Record inserted successfully.")
conn.close()
try:
# Try connecting and inserting data
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
cur = conn.cursor()
finally:
# Always close the connection
conn.close()
first operation
[[20 30]
[50 60]]
2nd operation
[70 80 90]
3rd operation
[10 40 70]
2. Explain how arrays are created in NumPy. Write a program to create and transpose a 2D
array.
• np.array() - Creates an array from a Python list or tuple.
• np.zeros() - Creates an array filled with zeros.
• np.ones() - Creates an array filled with ones.
• np.empty() - Creates an empty array, uninitialized.
• np.arange() - Creates an array with a range of values (similar to range()).
• np.linspace() - Creates an array with evenly spaced numbers over a specified
interval.
import numpy as np
a = np.array([[1,2],[3,4]])
a = np.transpose(a) # or can use a.T
print('transpose of array a is: \n',a)
a = np.array([[1, 2, 3],
[4, 5, 6]])
rowsum = np.sum(a, axis=1)
columnsum = np.sum(a,axis=0)
print("Row Sum:", rowsum)
print("Column Sum:", columnsum)
Group B (short)
1. Write a Python program to read a CSV file using pandas and display the top 5 rows.
import pandas as pd
2. Write a Python program to read data from a CSV file using pandas and display statistics.
import pandas as pd
3. Write a Python program using pandas to filter rows from a CSV where marks > 80.
import pandas as pd
Group C(long) $
1. Explain Series and DataFrame in pandas. Write a Python program to create a time series
and plot it.
import pandas as pd
import matplotlib.pyplot as plt
2. Write a Python program to create a Series and plot its cumulative sum.
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series([3, 5, 2, 8, 6])
s.cumsum().plot(title='Cumulative Sum')
plt.xlabel("index")
plt.ylabel("cumulative sum")
plt.show()
# Access a column
df['ColumnName']
# Filter rows
df[df['ColumnName'] > 50]
# Sort values
df.sort_values(by='ColumnName')
4. What is a Series in pandas? How is it different from DataFrame? Plot bar chart.
A Series is a one-dimensional labeled array that can hold any data type (int, float, string,
etc.).
| Feature | Series | DataFrame |
| Dimension | 1D | 2D (rows and columns) |
| Structure | Single column | Multiple columns |
| Usage | Simple data lists | Tabular data (like CSV/excel) |
# Bar chart
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('nepal_district_data.csv')
# Filter for specific province
karnali = df[df['Province'] == 'Karnali']
# Average population by district
avg_pop = df.groupby('District')['Population'].mean()
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Department': ['HR', 'IT', 'HR', 'IT'],
'Salary': [50000, 60000, 55000, 70000]
}
df = pd.DataFrame(data)
print(df)
# Filter employees in HR department
hr_employees = df[df['Department'] == 'HR']
print(hr_employees)
# Average salary by department
avg_salary = df.groupby('Department')['Salary'].mean()
print(avg_salary)
import rasterio
import numpy as np
4. Write short notes on chart types in matplotlib. Create histogram, scatter, line chart.
Matplotlib offers various chart types for different data visualization needs:
Common Chart Types
• Line charts: Show trends over time or continuous data
• Bar charts: Compare values across categories
• Histograms: Display distribution of a dataset
• Scatter plots: Show relationship between two variables
• Pie charts: Show proportional composition of a whole
• Box plots: Display statistical summaries of data distributions
• Heatmaps: Visualize matrix data using color intensity
# 1. Histogram
ax1.hist(data, bins=30, color='skyblue', edgecolor='black')
ax1.set_title('Histogram')
ax1.set_xlabel('Value')
ax1.set_ylabel('Frequency')
# 2. Scatter Plot
ax2.scatter(x, y, color='green', alpha=0.7)
ax2.set_title('Scatter Plot')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
# 3. Line Chart
ax3.plot(months, temperatures, marker='o', color='red')
ax3.set_title('Line Chart')
ax3.set_xlabel('Month')
ax3.set_ylabel('Temperature (°C)')
plt.tight_layout()
plt.savefig('matplotlib_charts.png', dpi=300)
plt.show()
data = [22, 55, 62, 45, 21, 38, 49, 60, 41, 30]
plt.hist(data, bins=5, color='skyblue', edgecolor='black')
plt.title("Histogram Example")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Group B(short)
1. Write a Python program to draw a bar chart showing population of 5 countries.
import matplotlib.pyplot as plt
# Data
countries = ['Nepal', 'India', 'China', 'USA', 'Brazil']
population = [30, 1400, 1440, 331, 213] # in millions
# Show chart
plt.show()
# Plot histogram
plt.hist(data, bins=20, color='green', edgecolor='black')
# Show plot
plt.show()
# Data
students = ['Alice', 'Bob', 'Charlie', 'David', 'Eva']
marks = [85, 90, 75, 80, 70]
# Add title
plt.title("Marks Distribution of 5 Students")
plt.axis('equal') # To make the pie chart a circle
# Show chart
plt.show()
4. Write a Python program to create a line plot showing increase of sales over 5 years.
import matplotlib.pyplot as plt
# Data
years = [2019, 2020, 2021, 2022, 2023]
sales = [150, 200, 250, 300, 400] # in thousands
# Data
cities = ['Kathmandu', 'Pokhara', 'Lalitpur', 'Biratnagar', 'Birgunj']
population = [1000000, 500000, 300000, 400000, 350000] # example data
# Show plot
plt.show()
Group C (long)
1. Write a Python program to create a pie chart representing marks distribution of 5 subjects.
import matplotlib.pyplot as plt
# Data
subjects = ['Math', 'Science', 'English', 'History', 'Computer']
marks = [90, 85, 80, 70, 95]
# Add title
plt.title("Marks Distribution of 5 Subjects")
plt.axis('equal') # Makes the pie chart circular
# Show chart
plt.show()
2. Write a Python program to create a histogram, scatter plot, and line plot from a dataset.
import matplotlib.pyplot as plt
# Sample dataset
data = [5, 7, 8, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11]
# Histogram
plt.figure(figsize=(10, 3))
plt.subplot(1, 3, 1)
plt.hist(data, bins=5, color='skyblue', edgecolor='black')
plt.title("Histogram")
# Scatter Plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 7, 6]
plt.subplot(1, 3, 2)
plt.scatter(x, y, color='red')
plt.title("Scatter Plot")
# Line Plot
plt.subplot(1, 3, 3)
plt.plot(x, y, marker='o', color='green')
plt.title("Line Plot")
3. Write a Python program to create both line and scatter plots for student marks.
plt.title("Student Marks")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.legend()
plt.show()