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

Assignment All Chapter Python(6thsem)

This document is a comprehensive guide on Python programming, covering topics such as keywords, operators, data types, control statements, and loops. It includes explanations, examples, and programming exercises to demonstrate concepts like the use of the interpreter, functions, and data structures like lists and dictionaries. Additionally, it provides coding questions to encourage practical application of the material.

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 views69 pages

Assignment All Chapter Python(6thsem)

This document is a comprehensive guide on Python programming, covering topics such as keywords, operators, data types, control statements, and loops. It includes explanations, examples, and programming exercises to demonstrate concepts like the use of the interpreter, functions, and data structures like lists and dictionaries. Additionally, it provides coding questions to encourage practical application of the material.

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/ 69

Page |1

Advance Computer Program ( Python '6th sem' )

Chapter 1 : Introduction to python (2+4)


very short question
1. What is a keyword in Python? Give two examples.
A keyword in Python is a reserved word with a special meaning and purpose within the
Python language. These words cannot be used as variable names, function names, or any
other identifiers because they are part of Python's syntax.

# for example: if & else


# If and else are used for conditional statements
#Eg code ;
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is lesser than 5")

x is greater than 5

Ramesh Oli | GIT


Page |2

2. What is the difference between = and == in Python?


The single equals sign = is an assignment operator. It's used to assign a value to a variable.
The double equals sign == is a comparison operator. It checks if two values are equal and
returns a boolean result (True or False).
#Assignment operator example
x = 10 # Assigns the value 10 to variable x

# Comparison operator example


y = 5
z = 5
y == z # True because y and z have the same value
x == y # False because x and y have different values

# Common usage in conditional statements


if x == 10:
print("x equals 10")
else:
print("x does not equal 10")

x equals 10

Ramesh Oli | GIT


Page |3

3. What is the role of interpreter in Python?


Role of the Python Interpreter
1. The interpreter executes Python code line by line without prior compilation.

1. It detects and reports errors immediately during execution.

2. It automatically manages memory allocation and garbage collection.

3. It maintains the execution environment, including variable scopes and imported


modules.

4. Mention any two features of Python that make it popular.


1. extensive library Ecosystem
1. Readability and simple syntax

5. What is the purpose of input() function?


Accept user input from the standard input (usually the keyboard) during program
execution.
#basic uses of input()
name = input("enter your name")
print(f"your name is {name}")

enter your name haha

your name is haha

Ramesh Oli | GIT


Page |4

6. Define indentation in Python. Why is it important?


Indentation in Python refers to the whitespace (spaces or tabs) at the beginning of code
lines that defines The structure and grouping of statements.

Why It's Important


1. Syntax Requirement: Unlike languages using braces or keywords, Python uses
indentation to define code blocks
1. Code Structure: Determines which statements belong to which blocks (functions,
loops, conditionals)
2. Readability: Makes code structure visually clear
3. Error Prevention: Incorrect indentation causes syntax errors or logical bugs

7. List any four arithmetic operators in Python.


****Four Arithmetic Operators in Python****
1. Addition (+): Adds two numbers together
1. Subtraction (-): Subtracts the right operand from the left operand
2. Multiplication (*): Multiplies two numbers together
3. Division (/): Divides the left operand by the right operand (returns a float)

8. Define keyword with example.


Keywords are predefined, reserved words in Python that have fixed meanings and cannot
be used for any other purpose than what they are designed for. for examples:
1. if: Used for conditional execution
1. def:used to define a function
2. for Used to create Loop
3. import used to include modules
import keyword
print(keyword.kwlist)
#to count the total
print(f"Total Keyword available in python is:--{len(keyword.kwlist)}--")

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',


'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',

Ramesh Oli | GIT


Page |5

'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


Total Keyword available in python is:--35--

9. What is the purpose of the pass statement?


1. Serves as a placeholder in code blocks where Python syntax requires a statement
1. Does nothing when executed
2. Allows you to create empty function/class definitions or conditional blocks
3. Helps in creating code skeletons during development
#Empty class
class EmptyTemplate:
pass

# It's essentially Python saying "do nothing here" while maintaining valid
syntax.

10. Write syntax for declaring a dictionary in Python.


A dictionary in Python is a collection of key-value pairs. Here are the common ways to
declare dictionaries
#using curly braces {}
# Dictionary with initial key-value pairs
student = {"name": "John", "age": 21, "courses": ["Math", "Physics"]}

#Using thr dict() constructor:


# From key-value pairs
person = dict(name="Alice", age=25, country="USA")

11. What is a list in Python? Give an example.


A list in Python is an ordered, mutable collection of items that can store elements of
different data types. Lists are defined by enclosing elements in square brackets [] with
items separated by commas.
# Example of a Python list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

Ramesh Oli | GIT


Page |6

Short question (4 marks each – Theory)


1. What is interpreter? How does Python interpreter work?
An interpreter is a program that executes source code line by line, translating it into
machine-understandable instructions at runtime.
python interpreter works as folllows;
1. Write Python Code (.py file) ↓
1. Lexical Analysis (Break code into tokens) ↓
2. Parsing (Check syntax and build parse tree) ↓
3. Bytecode Generation (Compile to .pyc bytecode) ↓
4. Python Virtual Machine (PVM) (Execute bytecode line-by-line) ↓
5. Output on Screen

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

Ramesh Oli | GIT


Page |7

Programming Questions (4 marks each – Coding)


1. Write a program to demonstrate the use of if, elif, and else statements.
#simple program to catagorized a number
number = int(input("Enter any number:"))
if number < 0:
print("You entered a negative number.")
elif number > 0:
print("You entered a positive number.")
else:
print("You entred Zero")

Enter any number: -10

You entered a negative number.

2. Write a Python program to find the factorial of a number using loop.


num = int(input("Enter the number for factorial detremination-->"))
factorial = 1
if num < 0:
print("factorial doesn't exist for negative number")
elif num == 0:
print("The factorial of zero is --- 1")
else :
for i in range(1, num+1):
factorial *= i
print(f"the factorial of the number{num} is {factorial}")

Enter the number for factorial detremination--> 6

the factorial of the number6 is 720

Ramesh Oli | GIT


Page |8

3. Write a program to check whether a number is prime or not.


import math
n = int(input("enter any number"))

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

enter any number 7

entered number 7 is a prime number

#practice for determining the factorial of a number

n = int(input("enter number ==> "))


if n<= 1:
print("factorial doesn't exist for negative number")
elif n == 0:
print ("the factorial of zero is 1")
else:
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"the factorial of '{n}' is ==> {factorial}: ")

enter number ==> 8

the factorial of '8' is ==> 40320:

Ramesh Oli | GIT


Page |9

Chapter 2 : Control statements (4)


Short Answer Questions (4 marks each – Theory)
1. Explain loops in Python. Write a program using a while loop to print numbers from 10 to 1.
The loops in Python execute the block of code repeatedly over a range of values (for loops)
or until a condition is met (while loops). for example: for loops, while loops, do while loops
#code part :
n = 10
while n > 0:
print(n)
n -= 1

10
9
8
7
6
5
4
3
2
1

Ramesh Oli | GIT


P a g e | 10

2. What is the purpose of the pass statement?


The pass statement is a null operation or placeholder in Python. while it might seem like it
does nothing(which is technically ture), it serves several important purposes in python
programming.
• Creates syntactically valid empty code blocks
• Serves as a temporary placeholder during development
• Creates minimal implementations of functions and classes
• Explicitly indicates "do nothing" in conditional branches
• Allows for silent exception handling
# Examples
def not_implemented_yet():
pass

if condition:
do_something()
else:
pass # Deliberately do nothing

class EmptyClass:
pass

Ramesh Oli | GIT


P a g e | 11

Programming Questions (4 marks each – Coding)


1. Write a Python program to print all even numbers from 1 to 100 using for loop.
# Python program to print all even numbers from 1 to 100 using a for loop

print("---- Even numbers from 1 to 100 ----")


for i in range(1, 101):
if i % 2 == 0:
print(i, end=" ")

---- Even numbers from 1 to 100 ----


2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78
80 82 84 86 88 90 92 94 96 98 100

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

enter any number 2

you entered positive number

Ramesh Oli | GIT


P a g e | 12

3. Write a Python program to count vowels in a user-given string.


string = input("enter you want to count the vowels in a word")
vowels = ('a', 'e', 'i', 'o', 'u')
vowel_count = 0

#count vowels in the string


for char in string.lower():
if char in vowels:
vowel_count += 1
print(f"the word {string} has {vowel_count} vowels.")

enter you want to count the vowels in a word program

the word program has 2 vowels.

Ramesh Oli | GIT


P a g e | 13

Chapter 3: List, Ranges and Tuples in Python (2+4)


Very Short Answer Questions (2 marks each)
1. What is a tuple? How is it different from a list?
A tuple is a collection of ordered, immutable items. created using parentheses '()' syntax.
The items on the list are mutable and created using the square brackets '[]' syntax.
#for example
#Tuple
mixed_tuple = (1, "hello", 3.14, True)

#List
list_example = [1, 2, 3, "apple"]

2. Write syntax for declaring a dictionary in Python.


A dictionary is a collection of key-value pairs that is mutable, unordered, and indexed by
keys. Here's the syntax for declaring a dictionary:
# Basic dictionary syntax
my_dict = {} # Empty dictionary

another_dict = dict(name="Alice", age=25, city="New York")

3. What is a list in Python? Give an example.


A list in Python is an ordered, mutable collection of elements that can be of
different data types.
Lists are one of the most versatile and commonly used data structures in
Python.

mixed_list = [1, "Hello", 3.14, True, [1, 2, 3]] # Different data types

Ramesh Oli | GIT


P a g e | 14

Short Answer Questions (4 marks each – Theory)


1. What is dictionary in Python? Write a program to merge two dictionaries.
A dictionary in Python is an unordered, mutable (changeable), and indexed collection of
key-value pairs. Each key is unique, and it maps to a value. Dictionaries are defined using
curly braces {}, with the syntax:

# Define two dictionaries


dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Merge using the unpacking operator (Python 3.5+)


merged_dict = {**dict1, **dict2}

# Print the result


print("Merged Dictionary:", merged_dict)

Merged Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Ramesh Oli | GIT


P a g e | 15

2. Explain how to create and use sets in Python with examples.


A set is an unordered, mutable, and unindexed collection of unique elements in Python. It is
useful for storing items without duplicates and for performing mathematical set operations
like union, intersection, and difference.
# Creating a set with curly braces
my_set = {1, 2, 3, 4}

# Creating a set using the set() constructor


another_set = set([3, 4, 5, 6])

print(my_set) # Output: {1, 2, 3, 4}


print(another_set) # Output: {3, 4, 5, 6}

# operation in set
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union: all unique elements from both sets


print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

# Intersection: common elements


print(set1.intersection(set2)) # Output: {3}

# Difference: elements in set1 not in set2


print(set1.difference(set2)) # Output: {1, 2}

# Symmetric Difference: elements in either set, but not both


print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}

Ramesh Oli | GIT


P a g e | 16

3. What is the difference between a list and a tuple?


Feature List Tuple
Definition A mutable ordered collection An immutable ordered
collection
Syntax Defined using square brackets Defined using parentheses ()
[]
Mutability Mutable (can be changed) Immutable (cannot be
changed)
Methods Available More methods(e.g., append(), Fewer methods
remove())
Performance Slower than tuples Faster than lists (due to
immutability)
Use Case When data needs to be When data should not change
modified
Memory Usage Uses more memory Uses less memory
Can be used as No Yes
dictionary key?

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}

Feature List Set


Duplicates Allows duplicates Does not allow duplicates
Order Maintains insertion order Unordered (no guaranteed
order)
Mutability Mutable Mutable
Indexing/Slicing Supports indexing and slicing Does not support indexing
Syntax Square brackets [] Curly braces {}
Use Case Useful when order and Useful for unique items and set
duplicates matter operations

Ramesh Oli | GIT


P a g e | 17

Programming Questions (4 marks each – Coding)


1. Write a Python program to reverse a list using slicing.
# reversing a list using slicing
list = [1,2,3,2,3,7]
print(f"List : {list}")
reverse_list = list[::-1]
print(f"Reverse list : {reverse_list}")

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)

enter your name ramesh


enter your age 23

{'name': 'ramesh', 'age': '23'}

3. Write a Python program to count frequency of each word in a given sentence.


#counting of each word in a given sentence
sentence = ("creating a sentence to count the frequency of words")
word = sentence.split()
user_word = input("enter your word you want to know the requency")
user_count = word.count(user_word)
print(f"the count of the word '{user_word}' in the sentence is :",user_count)

enter your word you want to know the requency of

the count of the word 'of' in the sentence is : 1

Ramesh Oli | GIT


P a g e | 18

Chapter 4: Python Object Oriented (10)


very short answer questions *
1. Define a class and a object in a python.
A class is a blueprint or template for creating objects. It defines attributes (variables) and
methods (functions) the objects created from the class will have.
Syntax: class ClassName: # attributes and methods An object is an instance of a class. It
represents a specific example of the class with actual values.
#example of object
class Student:
def __init__(self, name):
self.name = name

def greet(self):
print("Hello,", self.name)

s1 = Student("Ramesh")
s1.greet()

Hello, Ramesh

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


In Python, self refers to the current object of the class. It is used inside class methods to:
Access instance variables (object's data like name, age, etc.).
Access other methods in the same object.
Differentiate between local variables and object variables with the same name.

Ramesh Oli | GIT


P a g e | 19

Short Answer Questions (4 marks each – Theory)


1. What is OOP in Python? Explain with an example.
OOP (Object-Oriented Programming) is a programming style that organizes code using
classes and objects. It helps you write reusable, organized, and modular code by modeling
real-world things (like a student, bank account, car) as objects.

Main Concepts of OOP: Class – Blueprint for creating objects.


Object – Instance of a class (a real example).
Encapsulation – Hiding internal details; keeping data safe.
Inheritance – One class can inherit features from another.
Polymorphism – One function/method behaves differently based on input or object.
Abstraction – Showing only essential features.
# Define a class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade

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

Ramesh Oli | GIT


P a g e | 20

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 = book("Munamadan","Lakshmi Prasad Devkota","Rs.150")

book1.display()

Title: Munamadan
author: Lakshmi Prasad Devkota
price: Rs.150

Ramesh Oli | GIT


P a g e | 21

Programming Questions (4 marks each – Coding)


1. Create a class Student with methods to input marks and calculate grade.
#creating the class student
class Student:
def __init__ (self): #defining a constructor
self.marks = [] #this will initialize an empty list to store marks

#creating user defined input


def input_marks(self):
num_subject = int(input("enter the number of subject: "))
for i in range(num_subject):
marks = float(input(f"enter the marks obtained for subject {i+1}:
"))
self.marks.append(marks)

#calculation for average


def calculate_grade(self):
if len(self.marks) == 0:
print("no marks entered")
return
total = sum(self.marks)
average = total/len(self.marks)

print(f"Average marks: {average:.2f}")

# Determine grade based on average


if average >= 90:
grade = 'A+'
elif average >= 80:
grade = 'A'
elif average >= 70:
grade = 'B+'
elif average >= 60:
grade = 'B'
elif average >= 50:
grade = 'C'
elif average >= 40:
grade = 'D'
else:
grade = 'F'

print(f"Grade: {grade}")

student1 = Student()
student1.input_marks()
print("student1 mark details")

Ramesh Oli | GIT


P a g e | 22

student1.calculate_grade()

enter the number of subject: 5


enter the marks obtained for subject 1: 68
enter the marks obtained for subject 2: 77
enter the marks obtained for subject 3: 79
enter the marks obtained for subject 4: 90
enter the marks obtained for subject 5: 65

student1 mark details


Average marks: 75.80
Grade: B+

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

Ramesh Oli | GIT


P a g e | 23

employee1.calculate_bonus()
employee1.display()

enter the name of employee Ramesh oli


enter the salary of the employee 45000
enter the bonus percentage 18

**------monthly salary details----**


Employee Name: Ramesh oli
salary : 45000.0
Bonus : 8100.0
Total month salary for employee Ramesh oli is 53100.0

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

enter title of the book Muna-madan


enter author name of the book Lakshmi Prasad Devkota
enter price of the book 150

Ramesh Oli | GIT


P a g e | 24

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

Ramesh Oli | GIT


P a g e | 25

Enter the name of account holder Ramesh oli


enter account number 139400
Enter the amount you want to deposit 1050000

deposited Rs. 1050000.0 successfully

Enter your amount you want to withdraw 300000

withdrawn Rs. 300000.0 successfully


---Account details---
Account Holder : Ramesh oli
Account Number : 139400
Availabe Balance : 750000.0

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)
print(f"Book '{book}' added.")

def issue_book(self, book):


if book in self.books:
self.books.remove(book)
print(f"Book '{book}' issued.")
else:
print(f"Book '{book}' is not available.")

# Example use:
lib = Library()
lib.add_book("Harry Potter")
lib.add_book("The Hobbit")
lib.issue_book("Harry Potter")
lib.issue_book("The Alchemist")

Ramesh Oli | GIT


P a g e | 26

Chapter 5: Exception Handling (2+4)


Very Short Answer Questions
1. What is the use of the try-except block in Python?
Uses:
1. Prevents the program from crashing due to runtime errors.

1. Allows handling different types of errors differently.

2. Useful in input validation, file handling, database operations, etc.


#example for try except 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")

enter 1st number: 10


enter 2nd number: e

please enter a valid number

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


Aspect except finally
Purpose Handle specific errors Always run cleanup code
Runs when? Only on matching exception Always, no matter what
Optional? Yes Yes
Common Error messages, recovery logic Closing files, releasing locks

Ramesh Oli | GIT


P a g e | 27

Aspect except finally


uses

Short Answer Questions


1. Write a Python program to handle division by zero.
# Program to handle division by zero error:
try:
x = int(input("enter 1st number"))
y = int(input("enter 2nd number"))
division = x/y
# When the value of y is zero, then it causes an error
print(f"The division of x by y is --> {division}")

except ZeroDivisionError: # this syntax excepts the divide by zero


error and executes the program
print("can't division by zero")

enter 1st number 20


enter 2nd number 0

can't division by zero

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. Works with or without Exception -- Runs even if there is no exception or if the


exception is not caught.
#for example
try:
x = 10 / 0 # This will cause an error
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This code always runs.")

Ramesh Oli | GIT


P a g e | 28

Cannot divide by zero.


This code always runs.

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

enter 1st number: 20


enter 2nd number: 0

you can't divide by zero.


This block always run.

Ramesh Oli | GIT


P a g e | 29

Group C: Long Answer Questions


1. What are exceptions? Write a Python program to handle ValueError and ZeroDivisionError.
Exceptions are unexpected events or errors that occur during program execution. Which
interrupt the normal flow of instructions and can be handled using special code blocks to
prevent the program from crashing.
#example for try except 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")

enter 1st number: 12


enter 2nd number: 5.4

please enter a valid number

Ramesh Oli | GIT


P a g e | 30

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

num2 = int(input("Enter the second number: "))

# Attempting division (this can raise ZeroDivisionError)


result = num1 / num2

# Handling the case where input is not an integer


except ValueError:
print("Invalid input! Please enter numbers only.")

# Handling the case where the user tries to divide by zero


except ZeroDivisionError:
print("You cannot divide by zero.")

# The else block runs only if no exceptions were raised


else:
print("Division successful. Result is:", result)

# The finally block always runs, no matter what happens above


finally:
print("Program execution complete. This block always runs.")

Ramesh Oli | GIT


P a g e | 31

Chapter 6: Python Multithreaded Programming


Conceptual Questions (Group B - Short)
1. What are the differences between a process and a thread?
Feature Process Thread
Definition Independent program Smallest unit of a process
Memory Has its own memory space Shares memory of parent process
Communic Inter-process communication (IPC) Shares data directly
ation needed
Overhead Heavy (takes more resources) Lightweight (less resource usage)
Speed Slower to create and switch Faster creation and switching
Crash One crash doesn't affect others A crashing thread may affect
Effect others

2. Explain the threading.Thread class constructor and its parameters.


Threading means running multiple tasks at the same time inside a single program.
Constructor Syntax:
thread = threading.Thread
( group=None, # Reserved for future use (always keep None)
target=None, # Function to run in the thread
name=None, # Optional thread name
args=(), # Positional arguments for the target function (in tuple)
kwargs=None, # Keyword arguments for the target function (in dict)
daemon=None # True if thread is a daemon (runs in background) )

Ramesh Oli | GIT


P a g e | 32

3. How does Python’s Global Interpreter Lock (GIL) affect multithreading?


Effect of GIL on Multithreading:
For CPU-bound tasks (like heavy math, image processing), GIL blocks other
threads and makes multithreading inefficient.

For I/O-bound tasks (like downloading files, reading files), GIL does not
block much, so multithreading works well.

4. What is the use of join() method in threading? Explain with an example.


join() makes the main program wait for a thread to finish.
Without join(), the main thread may finish before the other thread completes.
#for eg:
import threading
def happy():
print("man is happy")
t = threading.Thread(target = happy)
t.start()
t.join()
print("ok")

man is happy
ok

5. What is a daemon thread? How is it different from a user thread?


Daemon thread: Runs in background, ends when main thread ends.
User thread: Keeps running even after main thread exits.
t = threading.Thread(target=func)
t.daemon = True # Now it's a daemon thread

Ramesh Oli | GIT


P a g e | 33

6. Explain the role of Lock and RLock in thread synchronization.


When multiple threads access shared data, they can cause conflicts (called race conditions).
To prevent this, we use Lock or RLock to allow only one thread at a time to access that data.
1. Lock (Basic Lock)
Once a thread acquires the lock, other threads are blocked until it is released.
Non-reentrant: Same thread cannot acquire it again without releasing first.
1. RLock (Reentrant Lock)
Like Lock, but the same thread can acquire it multiple times.
Useful in recursive functions or when the same thread locks again within a locked block.

7. What are the advantages and disadvantages of multithreading?


Advantages:
Faster I/O-bound tasks
Efficient use of CPU
Shared memory space
Disadvantages:
Complex to debug
GIL restricts CPU-bound tasks

Ramesh Oli | GIT


P a g e | 34

8. What is multi-threading? Explain with a simple program.


Multithreading is a technique where multiple threads run concurrently in a single program.
Threads are lightweight sub-processes.
Useful for tasks like:
Downloading files
Checking multiple URLs
Running background tasks (like UI updates)
import threading
import time

# Define a function for the thread


def greet(name):
print(f"Hello, {name}!")
time.sleep(1)
print(f"Goodbye, {name}!")

# Create multiple threads


t1 = threading.Thread(target=greet, args=("Ramesh",))
t2 = threading.Thread(target=greet, args=("Sita",))

# Start threads
t1.start()
t2.start()

# Wait for both threads to finish


t1.join()
t2.join()

print("Both threads are done!")

Hello, Ramesh!
Hello, Sita!
Goodbye, Ramesh!
Goodbye, Sita!
Both threads are done!

9. What is the purpose of threading in Python?


Handle multiple tasks (like downloading, UI, etc.) simultaneously.

Best for I/O-bound operations (e.g., file/network).

Ramesh Oli | GIT


P a g e | 35

10. What is thread synchronization? Why is it necessary?


Ensures only one thread accesses shared data at a time.

Prevents race conditions and inconsistent results.

🔹 Programming Questions (Group B - Short)


1. Write a Python program to demonstrate use of join() in threads.
import threading

def worker():
print("Worker running")

# Create thread
t = threading.Thread(target=worker)

# Start thread
t.start()

# Wait for thread to complete


t.join()

print("Main thread finished")

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)

# Create and start 3 threads


for i in range(3):
t = threading.Thread(target=print_name, name=f"Thread-{i+1}")
t.start()

Ramesh Oli | GIT


P a g e | 36

Running: Thread-1
Running: Thread-2
Running: Thread-3

3. Write a Python program to demonstrate thread synchronization using Lock.


import threading # Import threading module

count = 0 # Shared variable


lock = threading.Lock() # Create a lock to prevent race condition

# Function to safely increase the count


def add():
global count
with lock: # Only one thread can enter this block at a time
for _ in range(1000):
count += 1

# Create two threads


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=add)

# Start both threads


t1.start()
t2.start()

# Wait for both threads to finish


t1.join()
t2.join()

# Print the final value of count


print("Final count:", count) # Expected output: 2000

Final count: 2000

Ramesh Oli | GIT


P a g e | 37

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)

Final Balance: 1200

Ramesh Oli | GIT


P a g e | 38

5. Write a Python program using queue.PriorityQueue to process tasks in a priority-based


multithreaded system.
import threading, queue, time

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

Processing High Priority with priority 1


Processing Low Priority with priority 2
Processing Very Low Priority with priority 3

6. Write a Python program to implement multi-threading using threading.Thread.


import threading

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

Ramesh Oli | GIT


P a g e | 39

Chapter 7: Using Database in Python


🔹 Conceptual Questions (Group B - Short)
1. What is a cursor in MySQL? How is it used in Python?
A cursor is like a pointer used to run SQL commands and get data from the database.
In Python, we get the cursor using .cursor() from the connection object.
python
import mysql.connector
conn = mysql.connector.connect(user='root', password='', host='localhost',
database='school')
cur = conn.cursor() # create cursor
cur.execute("SELECT * FROM students") # use it to execute query
rows = cur.fetchall()
for row in rows:
print(row)

2. Explain the role of commit() and rollback() in database operations.


commit(): Saves changes made by SQL statements.
rollback(): Undoes changes if an error occurs.
Example:
python code
connection.commit() # saves
conn.rollback() # Use this inside try-except when something goes wrong

Ramesh Oli | GIT


P a g e | 40

3. What is the difference between fetchone(), fetchall() and fetchmany()?


fetchone(): Returns one row.
fetchmany(n): Returns n rows.
fetchall(): Returns all rows

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

Ramesh Oli | GIT


P a g e | 41

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

We use mysql-connector-python because:


It is official.
Easy to install and run on Windows.

Ramesh Oli | GIT


P a g e | 42

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

# Insert a new record


cur.execute("INSERT INTO students (name, marks) VALUES (%s, %s)", ("Ramesh",
90))

conn.commit() # Save changes


conn.close() # Close connection

Ramesh Oli | GIT


P a g e | 43

🔹 Programming Questions (Group B - Short)


1. Write a Python program to create a MySQL table named students.
import mysql.connector # Import the connector module

# Step 1: Connect to MySQL database


conn = mysql.connector.connect(
host="localhost", # Your host (usually localhost)
user="root", # Your MySQL username
password="", # Your MySQL password
database="school" # Your existing database name
)

# Step 2: Create a cursor object to run SQL commands


cur = conn.cursor()

# Step 3: Write SQL to create a table named students


create_table_query = """
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY, # Auto ID
name VARCHAR(50), # Name of student
marks INT # Marks of student
)
"""

# Step 4: Execute the query


cur.execute(create_table_query)

# Step 5: Close the connection


conn.close()

Ramesh Oli | GIT


P a g e | 44

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

# Run SELECT query to get all students


cur.execute("SELECT * FROM students")

# Fetch all rows from result


rows = cur.fetchall()

# Display each row


for row in rows:
print("ID:", row[0], "Name:", row[1], "Marks:", row[2])

# Close connection
conn.close()

Ramesh Oli | GIT


P a g e | 45

3. Write a Python program to fetch and display only those records where marks > 80.
import mysql.connector

# Connect to the database


conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)

cur = conn.cursor()

# Run SELECT query with condition marks > 80


cur.execute("SELECT * FROM students WHERE marks > 80")

rows = cur.fetchall()

# Print students who scored more than 80


for row in rows:
print("ID:", row[0], "Name:", row[1], "Marks:", row[2])

conn.close()

Ramesh Oli | GIT


P a g e | 46

4. Write a Python program to use parameterized query to prevent SQL injection.


import mysql.connector

# Get input from user


student_name = input("Enter student name: ")
student_marks = int(input("Enter marks: "))

# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)

cur = conn.cursor()

# Use placeholders (%s) to safely insert user data


query = "INSERT INTO students (name, marks) VALUES (%s, %s)"
values = (student_name, student_marks)

cur.execute(query, values) # Safe query execution

conn.commit() # Save to DB
print("Record inserted successfully.")

conn.close()

Ramesh Oli | GIT


P a g e | 47

5. Write a Python program to handle exceptions during database operations.


import mysql.connector

try:
# Try connecting and inserting data
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)

cur = conn.cursor()

# Insert data safely


cur.execute("INSERT INTO students (name, marks) VALUES (%s, %s)",
("Rita", 95))

conn.commit() # Save changes


print("Data inserted successfully.")

except mysql.connector.Error as err:


# If any error occurs, print the error and rollback
print("Error occurred:", err)
conn.rollback() # Cancel changes if something goes wrong

finally:
# Always close the connection
conn.close()

Ramesh Oli | GIT


P a g e | 48

Chapter 8: Geospatial Data Analysis (NumPy & Pandas) [10]


Group A (Short):
1. Explain NumPy arrays. Write a program to create a 2D array and perform slicing.
NumPy arrays are fast, memory-efficient containers for numerical data. They support
multi-dimensional data, mathematical operations, and slicing.
import numpy as np

a = np.array([[10,20,30], [40,50,60],[70,80,90]]) #creating numpy array


print('first operation')
print(a[0:2,1:]) # Slice rows 0–1, columns 1–end
print('2nd operation')
print(a[2, :]) # Third row
print('3rd operation')
print(a[:, 0]) # First column

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)

Ramesh Oli | GIT


P a g e | 49

transpose of array a is:


[[1 3]
[2 4]]

4. What is NumPy? Create 2D array and compute row/column sums.


NumPy is a Python library used for fast mathematical operations on large data sets. It
provides support for arrays, matrices, and many useful functions.
import numpy as np

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)

Row Sum: [ 6 15]


Column Sum: [5 7 9]

5. Write a Python program to read a CSV file using pandas.


import pandas as pd
data = pd.read_csv('filenamecsv') # to read the csv file in same location of
python file

print(data.head()) #to display the first 5 row of the file

Ramesh Oli | GIT


P a g e | 50

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

# Read the CSV file (give correct file path)


data = pd.read_csv('filename.csv')

# Display top 5 rows


print(data.head())

2. Write a Python program to read data from a CSV file using pandas and display statistics.
import pandas as pd

# Read the CSV file


data = pd.read_csv('filename.csv')

# Display basic statistics


print(data.describe())

3. Write a Python program using pandas to filter rows from a CSV where marks > 80.
import pandas as pd

# Step 1: Read the CSV file


data = pd.read_csv('filename.csv')

# Step 2: Filter rows where marks > 80

filtered_data = data['marks'] > 80

# Step 3: Display the filtered rows


print(filtered_data)

Ramesh Oli | GIT


P a g e | 51

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

# Create a time series with dates and values


dates = pd.date_range('2023-01-01', periods=10, freq = 'D')
values = [5, 8, 12, 9, 15, 18, 20, 30, 25, 35]

# Create a DataFrame with time series data


time_series = pd.DataFrame({'Date': dates, 'Value': values})

# Set Date column as index


time_series.set_index('Date', inplace=True)

# Plot the time series


time_series.plot()
plt.title('Time Series Plot')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()

Ramesh Oli | GIT


P a g e | 52

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

Ramesh Oli | GIT


P a g e | 53

3. Explain pandas.Series and DataFrame. Analyze CSV using pandas.


pandas.Series:--- A Series is a one-dimensional array-like object with an index. It can hold
any data type (integers, strings, etc.).
pandas.DataFrame:--- A DataFrame is a two-dimensional table (rows and columns). It’s the
most common pandas object for structured data (like CSV files).
import pandas as pd

# Read CSV file


df = pd.read_csv('filename.csv')

# Show first 5 rows


df.head()

# Show last 5 rows


df.tail()

# Show shape (rows, columns)


df.shape

# Show column names


df.columns

# Show basic info


df.info()

# Show summary statistics


df.describe()

# Access a column
df['ColumnName']

# Filter rows
df[df['ColumnName'] > 50]

# Check for missing values


df.isnull().sum()

# Drop missing values


df.dropna()

# Fill missing values


df.fillna(0)

# Group by a column and get mean


df.groupby('ColumnName').mean()

# Sort values
df.sort_values(by='ColumnName')

Ramesh Oli | GIT


P a g e | 54

# Save to new CSV


df.to_csv('newfile.csv', index=False)

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

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


Populations = [10, 20, 15, 30, 25]
plt.bar(Countries, Populations)
plt.title("Population by Country")
plt.xlabel("Country")
plt.ylabel("Populations")
plt.show()

Ramesh Oli | GIT


P a g e | 55

5. Write a short note on geospatial data analysis using pandas.


pandas is a powerful Python library used in geospatial data analysis for managing and
analyzing attribute data (non-spatial) linked to geographic locations. Though it doesn't
directly handle geometry, it is highly effective when working with CSV, Excel, or database
tables containing location-related fields like latitude, longitude, city, or district names.

Key Uses in Geospatial Context:


-Reading and cleaning spatial datasets (e.g., coordinates, elevation, land use).
-Filtering and querying data based on location attributes.
-Grouping and summarizing (e.g., average rainfall by district).
-Joining tabular data with spatial files using common fields (e.g., District Name).
-Preparing data for mapping tools like GeoPandas, QGIS, or ArcGIS.

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

Ramesh Oli | GIT


P a g e | 56

6. Explain DataFrame in pandas. Filter and summarize employee data.


A DataFrame is a two-dimensional table-like data structure in pandas with rows and
columns Each column can have different data types (int, float, string).
DataFrames support powerful operations like filtering, grouping, and summarizing.
import pandas as pd

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)

Name Department Salary


0 Alice HR 50000
1 Bob IT 60000
2 Charlie HR 55000
3 David IT 70000
Name Department Salary
0 Alice HR 50000
2 Charlie HR 55000
Department
HR 52500.0
IT 65000.0
Name: Salary, dtype: float64

Ramesh Oli | GIT


P a g e | 57

7. What is geospatial raster and vector data? Read using

pandas and numpy.


Data
Type Description Format Examples Read using
Raster Pixel-based grid data .tif, .img rasterio → numpy
Vector Points, lines, polygons .shp, .geojson geopandas → pandas

import rasterio
import numpy as np

# Open the raster file


with rasterio.open('data/elevation.tif') as src:
raster_data = src.read(1) # Read the first band as a NumPy array

print(raster_data.shape) # Show rows and columns


print(np.max(raster_data)) # Max elevation
print(np.min(raster_data)) # Min elevation

Ramesh Oli | GIT


P a g e | 58

Chapter 9 : Data Visualization (2+4)


Group A: conceptual questions
1. Write short notes on data visualization using Python.
Data visualization is the graphical representation of data to help understand patterns,
trends, and relationships. Python offers several excellent libraries for creating effective
visualizations.

2. What are different chart types in matplotlib?


Matplotlib offers many chart types for different visualization needs:
Basic Charts
• Line plots: Show trends over time (plt.plot())
• Bar charts: Compare categories (plt.bar(), plt.barh())
• Scatter plots: Show relationships between variables (plt.scatter())
• Histograms: Display data distribution (plt.hist())
• Pie charts: Show proportions (plt.pie())

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


Data visualization is the process of translating raw data into visual formats like charts and
graphs

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

Ramesh Oli | GIT


P a g e | 59

import matplotlib.pyplot as plt


import numpy as np

# Create sample data


np.random.seed(42)
x = np.random.rand(50)
y = 2*x + np.random.normal(0, 0.3, 50)
data = np.random.normal(0, 1, 1000)
months = range(1, 13)
temperatures = [5, 7, 10, 15, 20, 25, 28, 27, 22, 16, 10, 6]

# Create figure with 3 subplots


fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))

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

Ramesh Oli | GIT


P a g e | 60

5. Write short notes on data visualization. Program to create a histogram/pie chart.


Data visualization is the graphical representation of information and data using visual
elements like charts, graphs, and maps. It helps to:
Understand large and complex data easily
Identify trends, patterns, and outliers
Communicate data clearly and effectively
Common visualization types: bar chart, pie chart, line graph, histogram, scatter plot, etc.
import matplotlib.pyplot as plt

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

Ramesh Oli | GIT


P a g e | 61

import matplotlib.pyplot as plt

labels = [‘A’, ‘B’, ‘C’, ‘D’]


sizes = [25, 35, 20, 20]
plt.pie(sizes, labels=labels, autopct=’%1.1f%%’, startangle=140)
plt.title(“Pie Chart Example”)
plt.axis(‘equal’)
plt.show()

Ramesh Oli | GIT


P a g e | 62

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

# Create bar chart


plt.bar(countries, population, color='orange')

# Add labels and title


plt.title("Population of 5 Countries")
plt.xlabel("Countries")
plt.ylabel("Population (in millions)")

# Show chart
plt.show()

Ramesh Oli | GIT


P a g e | 63

2. Write a Python program to plot a histogram of random numbers.


import matplotlib.pyplot as plt
import numpy as np

# Generate 1000 random numbers from a normal distribution


data = np.random.randn(1000)

# Plot histogram
plt.hist(data, bins=20, color='green', edgecolor='black')

# Add labels and title


plt.title("Histogram of Random Numbers")
plt.xlabel("Value")
plt.ylabel("Frequency")

# Show plot
plt.show()

Ramesh Oli | GIT


P a g e | 64

3. Write a program to visualize marks of 5 students using pie chart.


import matplotlib.pyplot as plt

# Data
students = ['Alice', 'Bob', 'Charlie', 'David', 'Eva']
marks = [85, 90, 75, 80, 70]

# Create pie chart


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

# Add title
plt.title("Marks Distribution of 5 Students")
plt.axis('equal') # To make the pie chart a circle

# Show chart
plt.show()

Ramesh Oli | GIT


P a g e | 65

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

# Create line plot


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

# Add labels and title


plt.title("Sales Growth Over 5 Years")
plt.xlabel("Year")
plt.ylabel("Sales (in thousands)")

# Show grid and plot


plt.grid(True)
plt.show()

Ramesh Oli | GIT


P a g e | 66

5. Draw a bar chart showing the population of 5 cities using matplotlib.


import matplotlib.pyplot as plt

# Data
cities = ['Kathmandu', 'Pokhara', 'Lalitpur', 'Biratnagar', 'Birgunj']
population = [1000000, 500000, 300000, 400000, 350000] # example data

# Create bar chart


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

# Add labels and title


plt.title("Population of 5 Cities")
plt.xlabel("Cities")
plt.ylabel("Population")

# Show plot
plt.show()

Ramesh Oli | GIT


P a g e | 67

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]

# Create pie chart


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

# Add title
plt.title("Marks Distribution of 5 Subjects")
plt.axis('equal') # Makes the pie chart circular

# Show chart
plt.show()

Ramesh Oli | GIT


P a g e | 68

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

# Display all plots


plt.tight_layout()
plt.show()

Ramesh Oli | GIT


P a g e | 69

3. Write a Python program to create both line and scatter plots for student marks.

import matplotlib.pyplot as plt

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


marks = [78, 85, 90, 72, 88]

plt.plot(students, marks, marker='o', label='Line')


plt.scatter(students, marks, color='red', label='Scatter')

plt.title("Student Marks")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.legend()
plt.show()

Ramesh Oli | GIT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy