0% found this document useful (0 votes)
51 views38 pages

Python Programming Lab Report

This document is a lab report submitted by Jeewan Bhatta for the Programming With Python course at SPA College, affiliated with Tribhuvan University. It includes a series of Python programming exercises with code snippets and outputs, covering various topics such as conditionals, loops, lists, dictionaries, and functions. The report is supervised by Mr. Prakash Saud and is intended for partial fulfillment of the Bachelor of Information Management degree.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views38 pages

Python Programming Lab Report

This document is a lab report submitted by Jeewan Bhatta for the Programming With Python course at SPA College, affiliated with Tribhuvan University. It includes a series of Python programming exercises with code snippets and outputs, covering various topics such as conditionals, loops, lists, dictionaries, and functions. The report is supervised by Mr. Prakash Saud and is intended for partial fulfillment of the Bachelor of Information Management degree.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SPA College

(Affiliated to Tribhuvan University)


Dhangadh-2, Kailali, Nepal

Lab Report
On
Programming With Python
For the partial fulfilment of requirements for the degree of Bachelor of
Information Management under Tribhuvan University

Submitted to:
Department of Bachelor of Information Management
SPA College
Under the Supervision of:
Mr. Prakash Saud
Lecturer, BIM Department

Submitted By:
Jeewan Bhatta
BIM 5th Semester

December,2024

LETTER OF RECOMMENDATION
Date: 01 / 29 /2081
This is to certify that the “Programming With Python” has been carried out by
Mr. Jeewan Bhatta in partial fulfilment of the degree of Bachelor of
Information Management for Tribhuvan University, during the academic year
2081. We further declare that the work reported in this lab report has not been
submitted and will not be submitted, either in part or in full, for the award of
any other degree or diploma in this institute or any other institute or university.

To the best of our knowledge and belief, this work embodies the work of the
candidate himself/herself, has duly been completed, fulfils the requirement of
the ordinance relating to the bachelor’s degree of the university, and is up to the
standard in respect of content, presentation, and language for being referred to
the examiner.

………………………….. ……………………………
Prakash Saud Dharma Raj Bhatta
(Lecturer, Lab tutor) (Program Director, BIM)

[Link].1: Write a program to print hello world.


Code :-
print("Hello World")
Output :-

[Link].2 : Write a program to check if you are eligible to be enlisted in


political party or not.
Code :-
age=int(input('Enter your age'))
if age>=60 :
print("You are eligible to be enlisted in political parties")
else:
print("You are not eligible to be enlisted in political parties")

Output:-

[Link].3 : Write a program to check if the number is odd or even.


Code:-
User_input=int(input('Enter number:'))
if User_input%2==0:
print("Even Number")
else:
print("Odd Number")
Output:-

[Link].4 : Write a program to find greater number between two numbers


Code:-
a=int(input('Enter first number'))
b=int(input('Enter second number'))
if b>a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Output:-

[Link].5 :Write a program to input a side of a Square and print its area.
Code:-
side=int(input("Enter a side of a square:"))
area=side**2
print ("area of square of side",side,"is",area)
Output:-

[Link].6:Write a program to input 2 floating point numbers &print their


average.
Code:-
num1=float(input("Enter first number:"))
num2=float(input("Enter second number:"))
avg=num1+num2
print ("Average of",num1,"and",num2,"is",avg)
Output:-

[Link] a program to input 2 int numbers a and b print true if a is


greater than or equal to b .if not print false.
Code:-
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print(a>=b)
Output:-

[Link] a program to input users first name and print its length.
Code:-
fname=input("Enter first name:")
print(len(fname))
Output:-

[Link] a program to find the occurrence of ‘$’ in a string.


Code:-
string=input("Enter a string:")
count=[Link]("$")
print(f"the number of $ in the string are:{count}")
Output:-

[Link] a program to find greatest of 3 numbers entered by the


user.
Code:-
num1=int(input("Enter first number:"))
num2=int(input("Enter second number:"))
num3=int(input("Enter third number:"))
if num1>=num2 and num1>=num3:
print(num1,"is the greatest number")
elif num2>=num1 and num2>=num3:
print(num2,"is the greatest number")
else:
print(num3,"is the greatest number")
Output:-

[Link] a program to check if a number is a multiple of 7 or not.


Code:-
num1=int(input("Enter number:"))
if num1%7==0:
print(num1,"is multiple of 7")
else:
print(num1,"is not multiple of 7")
Output:-

[Link].12. Write a program to check whether the year is leap year or not.
Code:-
year=int(input("Enter a random year:"))
if(year %4 ==0 and year%100!=0) or(year%400==0):
print(year,"is a leap year")

else:
print(year ,"is not a leap year")

Output:-

[Link] a program to ask the user to enter name of their 3 favourite


movies and store them in a list.
Code:-
list=[]
movie=input("Enter first movie")
[Link](movie)
movie=input("Enter second movie")
[Link](movie)
movie=input("Enter third movie")
[Link](movie)
print(list)
Output:-

[Link] a program to find smallest number in the list.


Code:-
list=[1,4,9,16,25,36,49,64,81,100]
i=0
small=list[0]
while i<=len(list)-1:
if list[0]>=list[i]:
small=list[i]
i+=1
print("Smallest no:",small)
Output:-

[Link] a program to find largest number in the list.


Code:-
list=[1,4,9,16,25,36,49,64,81,100]
i=0
largest=list[0]
while i<=len(list)-1:
if list[0]<=list[i]:
largest=list[i]
i+=1
print("Largest no:",largest)
Output:-

[Link] a program to print Fibonacci series up to 10th term.


Code:-
a,b=1,1
print("Fibonacci series:",end=" ")
for i in range(10):
print(a,end=" ")
a,b=b,a+b
Output:-

[Link] a program to add and remove item from list and display
the updated item.
Code:-
list=[1,4,9,16,25,36,49,64,81,100,"Jeewan"]
print("before removing item:",list)
[Link]("Jeewan")
print("after removing and before adding item:",list)
[Link](10,112)
print("after adding and before updating item:",list)
list[10]=121
print("after updating item of index 10 to 121:",list)

Output:-

[Link] a program to check if a list contains a palindrome of


elements or not.
Code:-
list=[1,2,3,2,1]
copy=[Link]()
if(copy==list):
print("list has palindrome element")
else:
print("List does not have palindrome element ")

Output:-

[Link] given list create separate lists of strings and numbers. Use
list comprehension gadgets = "Mobile","Laptop",100, "Camera", 310.28,
"Speakers", 27.00, "Television", 1000, "Laptop Case", "Camera Lens"
Code:-
gadget=["Mpbile","laptop",100,"Camera",310.28,"speakers",
27.00,"Television",1000,"Laptop case”, “Camera Lens"]
String_list=[item for item in gadget if isinstance(item,str)]
Number_list=[item for item in gadget if isinstance(item,(int,float))]
print("String inth list gadget:",String_list)
print("Numbers in the list gadget:",Number_list)

Output:-

[Link].20. delete the last column from the given 4*4 matrix are = [[1, 2, 3, 4],
[4, 5, 6, 7], [8, 9, 10, 11], [12,13, 14, 15]].
Code:-
import numpy as np
matrix_array=[[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12,13, 14, 15]]
new_array=[Link](matrix_array,-1,axis=1)
print(new_array)

Output:-

[Link].21. create a tuple with (1,2) 5 times.


Code:-
tuples=(1,2)
repeated_tuple=((tuples),)*5
print(repeated_tuple)

Output:-

[Link].22. get the list of value of dict in sorted way dict =


{‘c’:97,’a’:96,’b’:98}
Code:-
given_dictionary = {'c':97,'a':97,'b':98}
sorted_values=sorted(given_dictionary.values())
print(sorted_values)
Output:-

[Link].23. Creating a Dictionary with Integer Keys and print it


Code:-
my_dict={1:'BIM',
2:'Jeewan',
3:'TU'}
print(my_dict)
Output:-

[Link] given dict{1:`a`, 2:`b`, 3:`c`} change the key into item and
vice versa.
Code:-
my_dict={1:'a',2:'b',3:'c'}
new_dict={value: key for key , value in my_dict.items()}
print("before changin key to value and versa is",my_dict)
print("after changin key to value and versa is",new_dict)
Output:-

[Link].25. Write a Python script to add a key to a dictionary.


Code:-
my_Dict={'a':1,'b':2,'c':3}
print("Before adding key to the dictionary")
print(my_Dict)
my_Dict['d']=4
print(f"\n After adding key d:{my_Dict['d']} to the dictionary")
print(my_Dict)

Output:-

[Link].26. Write a Python script to concatenate the following dictionaries to


create a new one.
Code:-
dict1={'a':1,'b':2,'c':3}
dict2={'j':10,'k':11,'l':12}
print(f"first dictionary:\n{dict1}")
print(f"second dictionary:\n{dict2}")
dict=[Link]()
[Link](dict2)
print(f"dictionary after concating {dict1} and {dict2}:\n{dict}")

Output:-

[Link] a python script to generate and print a dictionary that


contains a number (between 1 and n)in the form (x,x*x).
Code:-
def get_square(n):
square_dict={x:x*x for x in range(1,n+1)}
return square_dict
print(f"Dictionary with Square: \n{get_square(5)}")
Output:-

[Link].28. Write a python script to print the dictionary where the keys are
numbers between 1 and 15(both included)and the values are the square of
the keys.
Code:-
square_dict={x:x**2 for x in range(1,16)}
print("dictionary with squares:")
print("Key:Values")
for key, values in square_dict.items():
print(f" {key}:{values}")

Output:-

[Link].29. Write a python program to iterate over dictionaries using for


loop.
Code:-
student = {
'Name': 'Jeewan BHatta',
'Age': 22,
'City': 'Dhangadhi ',
'Occupation': 'Student'
}
print("Iterating over dictionary keys:")
for key in student:
print(key)
print("\nIterating over dictionary values:")
for value in [Link]():
print(value)
print("\nIterating over dictionary items (key-value pairs):")
for key, value in [Link]():
print(f"{key}: {value}")
Output:-

[Link].30. Write a python program to multiply all the items in a dictionary.


Code:-
def get_multiplied_value(data):
result=1
for value in [Link]():
if isinstance(value,(int,float)):
result*=value
else :
raise ValueError("Value of dictionary must be integer or
float")
return result
data={'a':22,'b':11,'c':5}
print(f"Multiplication of all dictionary item i.e{data} is:\n
{get_multiplied_value(data)}")

Output:-

[Link].31. Write a python program to map two list into a dictionary.


Code:-
list1=[1,2,3,4,5,6]
list2=['a','b','c','d','e','f']
my_dict=dict(zip(list2,list1))
print(f"Dictionary after mapping list as keys{list2}and values{list1}
is:\n{my_dict}")
Output:-

[Link].32. Write a python program to get maximum and minimum values of


a dictionary.
Code:-
my_dict={'a':2,'b':34,'c':44,'d':4,'e':10,'f':14 }
max=max(my_dict.values())
min=min(my_dict.values())
print(f"maximum Value among{my_dict}is: {max}")
print(f"maximum Value among{my_dict}is: {min}")
Output:-

[Link].33. Write a python program to map two list into a dictionary.


Code:-
list1=[1,2,3,4,5,6]
list2=['a','b','c','d','e','f']
my_dict=dict(zip(list2,list1))
print(f"Dictionary after mapping list as keys{list2}and values{list1}
is:\n{my_dict}")
Output:-

[Link].34. Write a python program to get maximum and minimum values of


a dictionary.
Code:-
my_dict={'a':2,'b':34,'c':44,'d':4,'e':10,'f':14}
max_value=max(my_dict.values())
min_value=min(my_dict.values())
print(f"maximum value among{my_dict}is: {max_value}")
print(f"minimum value among{my_dict}is: {min_value}")

Output:-

[Link].35. Write a python program to combine two dictionaries by adding


values for common keys.
Code:-
dict1={'a':10,'b':15,'c':20,'d':25}
dict2={'a':15,'b':20,'c':25,'d':30}
dict=[Link]()
for key,value in [Link]():
if key in dict:
dict[key]+=value
else:
dict[key]=value
print(f"dictionary after comining{dict1}and{dict2}is\n{dict}")
Output:-

[Link].36. Write a python program to find highest 3 values of a


corresponding key in adictionary.
Code:-
dict_list=[{"name":"Jeewan","score":99},
{"name":"Rohan","score":98},
{"name":"Hemant","score":90},
{"name":"Kishor","score":95},
{"name":"Hem","score":93}
]
score=[dict["score"]for dict in dict_list]
[Link](reverse=True)
print(f"Heighest 3 values among\n{dict_list}are:{score[:3]}")

Output:-

[Link] a python program to count the values associated with a key


in a dictionary.
Code:-
dict_list=[{"name":"Jeewan","score":99},
{"name":"Rohan","score":98},
{"name":"Hemant","score":90},
{"name":"Kishor","score":95},
{"name":"Hem","score":93},
{'name': 'Rakesh', 'score': 90},
{'name': 'Prakash', 'score': 80},
{'name': 'Bibek', 'score': 95},
{'name': 'Karan', 'score':85},
{'name': 'David', 'score': 92},
{'name': 'Dipen', 'score': 88},
{'name': 'Khem', 'score': 90},
{'name': 'Sameer', 'score': 80},
{'name': 'Tank', 'score': 95},
]
score_count= {}
for dict in dict_list:
score=dict['score']
if score in score_count:
score_count[score]+=1
else:
score_count[score]=1
for score,count in score_count.items():
print(f"score {score}:{count}")
Output:

[Link].38. Write a python program to convert list into nested dictionary of


keys.
Code:-
list = ['apple', 'banana', 'cherry']
keys = ['fruit', 'type', 'name']
result = {}
temp=result
for key in keys:
if key not in temp:
temp[key] = {}
temp = temp[key]
temp[keys[-1]]= []
for item in list:
temp[keys[-1]].append(item)

print(result)
Output:

[Link].39. Write a python program to store dictionary data in a JSON file.


Code:-
import json
data={
'name':'Jeewan Bhatta',
'Age':22,
'City':'Dhangadhi'
}
filename='[Link]'
with open(filename,'w')as f:
[Link](data,f)
print(f"Data stored in {filename} successfully!")

Output:-

[Link].40. Write a python program to drop empty items from dictionary.


Code:-
my_dict={'a':2,'b':'','c':44,'d':None,'e':[],'f':'python','g':
{},'h':'program'}
my_dict={key: value for key, value in my_dict.items() if value}
print("Dictionary after dropping empty items:")
print(my_dict)
Output:-

[Link].41. Write a python program to find the length of dictionary of


values.
Code:-
my_dict={
'b':(1,2,3,4,5),
'c':'Hello',
'e':[1,2,3,4,5],
'g':{'a':1,'b':3}}
for key, value in my_dict.items():
print(f"length of value '{key}':{len(value)}")
Output:-

[Link].42. Write a python program to create a flat list of all the keys ina
dictionary.
Code:-
my_dict={
'b':(1,2,3,4,5),
'c':'Hello',
'e':[1,2,3,4,5],
'g':{'a':1,'b':3}}
list=list(my_dict.keys())
print(f"List of all the keys in dictionary{my_dict}is:\n{list}")

Output:-

[Link].43. Write a python program to find the key of the maximum value in
a dictionary.
Code:-
my_dict={
'a':22,
'b':20,
'c':32,
'd':25,
'e':14
}
max_key=max(my_dict,key=my_dict.get)
min_key=min(my_dict,key=my_dict.get)
print(f"The key of maximum value in {my_dict}is: '{max_key}'")
print(f"The key of minimum value in {my_dict}is: '{min_key}'")
Output:-

[Link].44. Write a python program to create a set.


Code:-
my_set={1,2,3,4,5,6}
print(f"The set is{my_set}")
print(type(my_set))
Output:-

[Link].45. Write a python program to remove item(s) from a given set.


Code:-
my_set={1,2,3,4,5,6}
print(f"The set before removing item :{my_set}")
my_set.remove(5)
print(f"The set after removing item :{my_set}")
Output:-

[Link].46. Write a python program to create an intersection of sets.


Code:-
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
intersected_set=[Link](set2)
print(f"ste1:{set1}")
print(f"set2:{set2}")
print(f"the intersection of {set1}and{set2} is:{intersected_set}")
Output:-

[Link] a python program to find the maximum and minimum


values in a set.
Code:-
my_set={1,2,3,4,5,6}
max_value=max(my_set)
min_value=min(my_set)
print(f"Set:{my_set}")
print(f"Maximum Value:{max_value}")
print(f"Minimum Value:{min_value}")
Output:-

[Link] a python program to check if a given number is a superset


of itself and superset of another given set.
Code:-
set1={1,2,3,4,5,6}
set2={4,5,6}
print(f"set1:{set1}")
print(f"set2:{set2}")
if [Link](set1) and [Link](set2):
print(f"set1 is a superset of itself and set2")
else:
print(f"set1 is not a superset of itself and set2")
Output:-

[Link].49. Write a python program that finds all pairs of elements in a list
whose sum is equal to a given value.
Code:-
nums=[0,1,2,3,4,5,6,7,8]
target_sum=8
pairs=[]
for i in range (len(nums)):
for j in range (i+1,len(nums)):
if nums[i]+nums[j]==target_sum:
[Link]((nums[i],nums[j]))
print(f"Given number:{target_sum}")
print(f"Th pairs whose sum is equal to the given number are:{pairs}")
Output:-

[Link].50. Write a python program to find a third largest number from


given list of numbers. Use the python set data types.
Code:-
nums=[0,1,2,3,6,9,10,5,6,7,8]
my_list=list(set(nums))
my_list.sort(reverse=True)
if len(my_list)<3:
print(None)
print(f"The third heighest number in the list{nums}is:{my_list[2]}")
Output:-

[Link].51. Write a python program to remove all duplicates from a given list
of string and return a list of unique string. Use the python set data types.
Code:-
my_list=["banana","apple","mango","pineapple","mango","pineapple","bana
na","apple","mango","pineapple"]
unique_set=set(my_list)
unique_list=list(unique_set)
print(f"List before removing duplicates:\n{my_list}")
print(f"List after removing duplicates:{unique_list}")
Output:-

[Link].52. Write a python program to create a tuple of numbers and print


one item.
Code:-
my_tuple=(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
data=my_tuple[-1]
print(f"last element of tuple :{data}")
Output:-

[Link] a python program to get the 4th element from the last
element of a tuple.
Code:-
my_tuple=(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
data=my_tuple[-4]
print(f"tuple:{my_tuple}")
print(f"4th element from last in a tuple:{data}")
Output:-

[Link].54. Write a python program to find the index of an item in tuple.


Code:-
my_tuple=(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
item=int(input("enter any number:"))
if item in my_tuple:
ind=my_tuple.index(item)
print(f"the index of{item} is:{ind}")
else:
print (f"{item} is not found in th tuple")
Output:-

[Link].55. Write a python program to reverse a tuple.


Code:-
my_tuple=(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
reverse=my_tuple [::-1 ]
print(f"original tuple:{my_tuple}")
print(f"Reversed tuple:{reverse}")
Output:-

[Link].56. Write a python program to remove an entity tuple(s) from a list


of tuples .sample data[0,0,(“,),(‘a’,’b’),(‘a’,’b’,’c’),(‘d’)]
Code:-
my_tuple=[0,0,("a"),('a','b'),('a','b','c'),('d')]
removed_item=my_tuple[2]
my_tuple.remove(removed_item)
print(f"Original Tuple:{my_tuple}")
print(f"Tuple after removing '{removed_item}' is: {my_tuple}")
Output:-

[Link].57. Write a python program to convert a given string list to a tuple.


Original string: "python3.0"
<class ‘str’>
Convert the string to a tuple:
(‘p’,’y’,’t’,’h’,’o’,’n’,’3’,’.’,’0’)
<class ‘tuple’>
Code:-
String="python3.0"
print(f"original String:{String}")
my_tuple=tuple(String)
print(f"After converting string into tuple:{my_tuple}")

Output:

[Link].58. Write a python program to compute the element-wise sum of


given tuple.
Original list:
(1,2,3,4)
(3,,5,2,1)
(2,2,3,1)
Code:-
tup1=(1,2,3,4)
tup2=(3,5,2,1)
tup3=(2,2,3,1)
print("Original tuple")
print(f"tuple1:{tup1}")
print(f"tuple2:{tup2}")
print(f"tuple3:{tup3}")
result=tuple(map(sum,zip(tup1,tup2,tup3)))
print(f"Element Wise sum:\n{result}")

Output:-

[Link] a python program to convert a given list of tuples to a list of


lists.
Original list of tuples: [(1,2),(2,3),(3,4)]
Convert the said list of tuples to list of list:[[1,2],[2,3],[3,4]]
Original list of tuples: [(1, 2), (2, 3, 5), (3, 4), (2, 3, 4, 2)]
Convert the said list of tuples to a list of lists: [[1, 2], [2, 3, 5], [3, 4], [2, 3, 4, 2]]
Code:-
list_of_tuple1= [(1,2),(2,3),(3,4)]
list_of_tuple2=[(1, 2), (2, 3, 5), (3, 4), (2, 3, 4, 2)]
list_of_list1=list(map(list,list_of_tuple1))
list_of_list2=list(map(list,list_of_tuple2))
print(f"original list of tuple1:{list_of_tuple1}")
print(f"converted list of tuple1 to list1:{list_of_list1}")
print(f"original list of tuple2:{list_of_tuple2}")
print(f"converted list of tuple2 to list2:{list_of_list2}")

Output:-

[Link].60. Write a python function to find maximum of three numbers.


Code:-
def get_maximum(num1,num2,num3):
print(f"Maximum number among{num1},{num2},{num3} is:
{max(num1,num2,num3)}")
get_maximum(22,32,14)
Output:-

[Link].61. Write a python function to revere a string.


Code:-
def reverse_string(string):
print(f"Reverse of '{string}' is:{string[::-1]}")
s=input("enter any string:")
reverse_string(s)

Output:-

[Link].62. Write a python function to calculate the factorial of a number(a


non negative integer).The function accepts the number as an argument.
Code:-
def fact(num):
if num==0 or num==1:
return 1
else:
return num*fact(num-1)
num=int(input("enter any number"))
print(f"factorial of {num} is:{fact(num)}")
Output:-

[Link].63. Write a python function to check whether number falls in a given


range.
Code:-
import random
num=[Link](1,200)
def check_number(min_num,max_num):
if num >=min_num and num <=max_num:
print(f"{num} fall between the range of{min_num}and{max_num}")
else:
print(f"{num} does not fall between the range
of{min_num}and{max_num}")
check_number(1,100)
Output:-

[Link].64. Write a python function to check whether a string is pangram or


not .
Note: Pangrams are words or sentences containing every letter of the alphabet at least once.
For example: ”The quick brown fox jumps over the lazy dog”
Code:-
def is_pangram(s):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in [Link]():
return (f"'{s}' is Not panagram")
return (f"'{s}' is panagram")
print(is_pangram("The quick brown fox jumps over the lazy dog"))
print(is_pangram("Pack my box with five dozen liquor jugs"))
print(is_pangram("Hello World"))
print(is_pangram("Hello world this is a test"))
Output:-

[Link].65. Write a python function to create and print a list where the
values are the square of numbers between 1 and 30 (both included).
Code:-
def list_of_squares():
list=[i*i for i in range(1,31)]
print(f"List of squares from 1 to 30 is:\n{list}")
list_of_squares()
Output:-

[Link].66. Write a python program that invoke a function after a specified


period of time
Sample Output:
Square root after specific milliseconds:
4.0
10.0
158.42979517754858
Code:-
import time
import math
def calculate_square_root(number):
return [Link](number)

def invoke_after_delay(delay_milliseconds, function, number):


[Link](delay_milliseconds / 1000.0)
result = function(number)
print(f"Square root after {delay_milliseconds} milliseconds:
{result}")
invoke_after_delay(2000, calculate_square_root, 16)
invoke_after_delay(2000, calculate_square_root, 100)
invoke_after_delay(2000, calculate_square_root, 25000)
Output:-

[Link].67. Write a python function to sum all the numbers in a list.


Code:-
def sum_item(numbers):
total=0
for num in numbers:
total+=num
return total
numbers=[1,2,3,4,5,6,7]
total_sum=sum_item(numbers)
print(f"Sum of numbers in the list {numbers} is:{total_sum}")
Output:-

[Link].68. Write a Program to create a class representing a circle include


methods to calculate its area perimeter.
Code:-
class circle:
def __init__(self,radious):
[Link]=radious
[Link]=3.14
def calc_area(self):
area= [Link]*([Link]**2)
return area
def calc_perimeter(self):
perimeter=2*[Link]*[Link]
return perimeter
radious=int(input("enter radious of circle"))
c=circle(radious)
print("area of circle of",radious,"radious is",c.calc_area())
print("perimeter of circle of",radious,"radious is",c.calc_perimeter())
Output:-

[Link].69. Write a Program to create a person class include attributes like


name, country and the date of birth implement a method determine the
person age.
Code:-
from datetime import datetime
class person:
def __init__(self,name,country,date_of_birth):
[Link]=name
[Link]=country
self.date_of_birth=date_of_birth
def calc_age(self):
today= [Link]()
birth_year= self.date_of_birth.year
age=[Link]-birth_year
if today < datetime([Link],
self.date_of_birth.month,self.date_of_birth.day):
age-=1
return age
new_person=person("Jeewan Bhatta","nepal",datetime(2003,8,21))
print("The age of the person is",new_person.calc_age())
Output:-

Q.N0.70. Write a Program to create a calculator class include methods for


basic arithmetic operations.
Code:-
class calculator:
def __init__(self,num1,num2):
self.num1=num1
self.num2=num2
def sum(self):
return self.num1+self.num2
def difference(self):
return self.num1-self.num2
def mul(self):
return self.num1*self.num2
def div(self):
return self.num1/self.num2

if __name__== "__main__":
num1=float(input("Enter first number"))
num2=float(input("Enter second number"))
cal=calculator(num1,num2)
print(f"sum of {cal.num1}and{cal.num2}is{[Link]()}")
print(f"Difference of {cal.num1}and{cal.num2}is{[Link]()}")
print(f"Multiplication of {cal.num1}and{cal.num2}is{[Link]()}")
print(f"Division of {cal.num1}and{cal.num2}is{[Link]()}")

Output:-

[Link].71. Write a python program to create a class that represent a shape


include methods to calculate its area and [Link] subclass for
different shapes like circle,triangle and square.
Code:-
class shape:
def calc_area(self):
pass
def calc_perimeter(self):
pass
class circle(shape):
PI=3.14159
def __init__(self,radious):
[Link]=radious
def calc_area(self):
return [Link]*[Link]**2
def calc_perimeter(self):
return 2*[Link]*[Link]
class triangle(shape):
def __init__(self,length,base,height):
[Link]=length
[Link]=base
[Link]=height
def calc_area(self):
return (1/2)*[Link]*[Link]
def calc_perimeter(self):
return [Link]+[Link]+[Link]
class rectangle(shape):
def __init__(self,length,breadth):
[Link]=length
[Link]=breadth
def calc_area(self):
return [Link]*[Link]
def calc_perimeter(self):
return 2*([Link]+[Link])
class square(shape):
def __init__(self,length):
[Link]=length
def calc_area(self):
return [Link]**2
def calc_perimeter(self):
return 4*[Link]
circ=circle(7) #for circle
circle_area=circ.calc_area()
circle_perimeter=circ.calc_perimeter()
print(f"the area of circle is{circle_area} and primeter is
{circle_perimeter}")
tri=triangle(3,5,8)#for triangle
triangle_area=tri.calc_area()
triangle_perimeter=tri.calc_perimeter()
print(f"the area of triangle is{triangle_area} and primeter is
{triangle_perimeter}")
rect=rectangle(4,5) # For rectangle
rectangle_area=rect.calc_area()
rectangle_perimeter=rect.calc_perimeter()
print(f"the area of rectangle is{rectangle_area} and primeter is
{rectangle_perimeter}")
sq=square(5) # For sqare
square_area=sq.calc_area()
square_perimeter=sq.calc_perimeter()
print(f"the area of Square is{square_area} and primeter is
{square_perimeter}")

Output:-

[Link] a python program to create a class representing a binary


search [Link] methods of inserting and searching for elements in the
binary tree.
Code:-
class binary_search_tree:
def __init__(self):
[Link]={}
def insert(self,key):
if key not in [Link]:
[Link][key]=(None,None)
def search(self,key):
return key in [Link]
def get_all_elements(self):
return list([Link]())
bst=binary_search_tree()
keys=[1,2,3,4,5,8,"jeewan",3.00,"Bhatta"]
for key in keys:
[Link](key)
all_elements=bst.get_all_elements()
search_value="jeewan"
print(f"elements in the binary search tree are:{all_elements}")
if [Link](search_value):
print(f"{search_value} is present in the binary search tree")
else:
print(f"{search_value} is not present in the binary search tree")

Output:-

[Link].73. Write a python program to create a class representation a stack


data structure includes methods for pushing and popping elements.
Code:-

class stack:
def __init__(self) :
[Link]=[]
def push(self,item):
[Link](item)
def pop(self):
if self.is_empty():
raise IndexError ("error stack is empty cannot pop item")
else:
return [Link]()
def show_top_element(self):
if not self.is_empty():
return [Link][-1]
else:
raise IndexError("Stack is empty cannot see the empty
stack")
def is_empty(self):
return len([Link])==0
def size_of_stack(self):
return len([Link])

if __name__=="__main__":
my_stack=stack()
# my_stack.push("jeewan")
# my_stack.push("Bhatta")
# my_stack.push(14)
# my_stack.push(6.9)

keys=[1,2,"jeewan","bhatta"]
for item in keys:
my_stack.push(item)
print(f"size of stack is:{my_stack.size_of_stack()}")
print(f"top element in the stack is:{my_stack.show_top_element()}")
popped_item=my_stack.pop()
print(f"popped item is:{popped_item}")
print(f"size of stack after pop operation is:
{my_stack.size_of_stack()}")

Output:-

[Link].74. Write a python program to create a class represent a linked list


data structure include methods for displaying linked list, inserting and
deleting nodes.
Code:-
class Node:
def __init__(self,data):
[Link]=data
[Link]=None
class Linked_List:
def __init__(self):
[Link]=None
def insert(self,data):
newnode=Node(data)
if [Link] is None:
[Link]=newnode
else:
[Link]=[Link]
[Link]=newnode
def delete(self,key):
current=[Link]
previous=None
while current:
if [Link]==key:
if previous:
[Link]=[Link]
else:
[Link]=[Link]
return
previous=current
current=[Link]
def display(self):
current=[Link]
while current:
print([Link],end="-> ")
current=[Link]
print("None")
if __name__=="__main__":
ll=Linked_List()
[Link](10)
[Link](11)
[Link](12)
[Link](13)
[Link](14)
print("Linked List:")
[Link]()
[Link](11)
print("Linked list after deletion: ")
[Link]()
Output:-

[Link].75. Write a program to create a class representing a shopping cart include


methods for adding and removing items and calculating the total price.
Code:-
class Shopping_Cart:
def __init__(self):
[Link]=[]
def insert(self,item,price,quantity):
items=Item(item,price,quantity)
[Link](items)
def remove(self,item):
[Link]=[items for items in [Link]
if [Link]!=item]
def claculate_total_price(self):
total=sum([Link]*[Link] for items in [Link])
return total
cart=Shopping_Cart()
[Link]("Watermelon",100,2)
[Link]("Mango",130,3)
[Link]("apple",180,5)
print("the cart")
for items in [Link]:
print(f"{[Link]} -{[Link]}kg-Rs{[Link]}each")
total_price=cart.claculate_total_price()
print(f"Total price:{total_price}")
[Link]("apple")
print("\nUpdated items after removing apple:")
for items in [Link]:
print(f"{[Link]} -{[Link]}kg-Rs{[Link]}each")
total_price=cart.claculate_total_price()
print(f"Total price after delrtion of apple:{total_price}")

Output:-

You might also like