Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
103 views

Practical Record Book - Python

Lab exercises using Python

Uploaded by

ilanjv40
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Practical Record Book - Python

Lab exercises using Python

Uploaded by

ilanjv40
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON PRACTICAL RECORD BOOK

BY

KATABALWA JOHN VIANNEY


(012220073)

This is to certify that I have completed the Python Practical Record Book for

Fourth Semester under the guidance of Ms. ALEKHYA.

HEAD OF THE DEPARTMENT FACULTY IN CHARGE

(SIGNATURE WITH DATE) (SIGNATURE WITH DATE)

FACULTY OF INFORMATION AND COMMUNICATION TECHNOLOGY


INTERNATIONAL BUSINESS SCIENCE AND TECHNOLOGY UNIVERSITY
Plot 11A, Rotary Avenue, Lugogo Bypass, Kololo, Kampala, Uganda
List of Activities

1 Write a program to demonstrate working with dictionaries in python.

2 Write a python program to find factorial of a number using recursion.

Write a python program to define a module and import a specific function


3 in that module to another module.

Write a python program to define a module and import the content of


4 another module with alias name used.

5 How to access modules saved inside other locations into current module?

6 Write a program to demonstrate working with LIST in python.

7 Write a program to demonstrate working with SET in python.

8 Implement multilevel inheritance in python.

9 Create a CSV file with the name emp.csv and write data into the file.

10 Create a CSV file with the name emp.csv and read data from it.

11 Create a file with the name student.txt and write data to the file.

12 Create a file with the name student.txt and read data from the file.

13 Implement the working of packages.

14 Implement calculator program using functions.


Tools used for the Lab activities:

1) Windows Operating System: Default PC operating system for the lab Experiments.

2) Python: Programming Language installed on PC and used for the Experiments.

3) IDLE Shell 3.12.2 – Integrated Development Environment (IDE) used to write the source
code and output the compiled results of the Experiments.

Screen shot of the IDLE Shell 3.12.2:


Experiment-1: Program to demonstrate working with dictionaries in python.

Source code:

# write a program to read scores of n players


# each player is having name and runs scored

p={}
while True:
print("1. Adding")
print("2. Updating")
print("3. Finding")
print("4. Score Board")
print("5. Exit")
opt=int(input("Enter your option"))
if opt==1:
name=input("Enter Name")
score=int(input("Enter Score"))
if name in p:
print(name,"is exists")
else:
p[name]=score
elif opt==2:
name=input("Enter Name")
if name in p:
s=int(input("Enter Updated Score"))
p[name]=s
else:
print(name,"not exists")
elif opt==3:
name=input("Enter name")
if name in p:
s=p[name]
print("score ",s)
else:
print(name,"is not exists")
elif opt==4:
tot=0
for x in p.items():
name,score=x
print(name,score)
tot=tot+score
print("Total Score :",tot)
elif opt==5:
break
Output:

Adding + score board:

Updating + Score board:

Finding + Exit:
Experiment-2: Program to find factorial of a number using recursion:

Source code:

def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)

def main():
num=int(input("enter any number"))
res=factorial(num)
print(f'factorial is {res}')

main()

Output:

Scenario1 – num=6:

Scenario2 – num=9:

Scenario3 – num=20:

Scenario4 – num=90:

Scenario5 – num=35:
Experiment-3: Program to define a module and import a specific function from that module to
another module.

Source code:

#Module1 – saved as Exp3_module1


x=100 #global variable
y=200 #global variable

def fun1():
print("inside fun1 of module1")

def fun2():
print("inside fun2 of module1")

#Module2– saved as Exp3_module2


from Exp3_module1 import *

def main():
print(x)
print(y)
fun1()

main()

Output:
Experiment-4: Program to define a module and import the content of another module with
alias name used.

Source code:

#Module1-saved as Exp4_module1
x=100 #global
y=200 #global

def fun1():
print("inside fun1 of module1")

def fun2():
print("inside fun2 of module1")

#Module2-saved as Exp4_module2
from Exp4_module1 import x as k
from Exp4_module1 import fun1 as f1

def fun1():
print("fun1 of current module")

x=99
def main():
print(x)
fun1()
print(k)
f1()

main()

Output:
Experiment-5: How to access modules saved inside other locations into current module?

Source code:

#Module1-saved as Exp5_module1
def fun1():
print("fun1 of module1")

#Module2-saved as Exp5_module2
import sys
sys.path.append(r"C:\Users\CARE
IT\Documents\Isbat\Via_Aspiration\AIT_Isbat\SEM4\Python\Lab")

import Exp5_module1

def main():
Exp5_module1.fun1()

main()

Output:
Experiment-6: Program to demonstrate working with LIST in python.

Source code:

#write a program to read the scores of n players


#and display total, max, min

n=int(input("enter how many players?")) # 5

scores=[]

for i in range(n):# range(5) --> 0 1 2 3 4


r=int(input("Enter score"))
scores.append(r)

print("Total Score :", sum(scores))


print("Maximum Score :", max(scores))
print("Minimum Score :", min(scores))

Output:

Scenario1 - n=5:

Scenario2 - n=10:
Experiment-7: Program to demonstrate working with SET in python.

Source code:

# Email Book Application


email_set=set()

while True:
print("***Email Book***")
print("1. Add")
print("2. Search")
print("3. Remove")
print("4. List")
print("5. Exit")

opt=int(input("enter your option"))


if opt==1:
email_id=input("Enter Email-id")
if email_id in email_set:
print("this email id exists")
else:
email_set.add(email_id)
elif opt==2:
email_id=input("Enter Email_id")
if email_id in email_set:
print(email_id,"is found")
else:
print("this email id not exists")
elif opt==3:
email_id=input("Enter Email_id")
if email_id in email_set:
email_set.remove(email_id)
else:
print("this email id not exists")
elif opt==4:
for email_id in email_set:
print(email_id)
elif opt==5:
break
Output:

Add + List:

Search:

Remove + List:
Experiment-8: Implement multilevel inheritance in python.

Source code:

# Multilevel inheritance
class Animal:
def speak(self):
print("Animal Speaking")

#The child class Dog inherits the base class Animal


class Dog(Animal):
def bark(self):
print("dog barking")

#The child class Dogchild inherits another child class Dog


class DogChild(Dog):
def eat(self):
print("Eating bread...")

d = DogChild()
d.bark()
d.speak()
d.eat()

Output:
Experiment-9: Create a CSV file with the name emp.csv and write data into the file.

Source code:

import csv

def main():

try:
f=open("emp.csv","w",newline='')
cw=csv.writer(f)
cw.writerow(['empno','ename','salary'])
cw.writerow([101,'naresh',50000.0])
cw.writerow([102,'suresh',65000.0])
cw.writerow([103,'kiran',75000.0])
cw.writerow([104,'ramesh',70000.0])

except OSError:
print("error in creating csv file")

finally:
f.close()

main()

Output – CSV file created under same folder as module:

Output – CSV file opened to view the contents defined in the module:
Experiment-10: Create a CSV file with the name emp.csv and read data from it.

Source code:

import csv

def main():

try:
f=open("emp.csv","r")
cr=csv.reader(f)
for row in cr:
print(row)
f.close()
f=open("emp.csv","r")
cr=csv.reader(f)
empList=list(cr)
print(empList)
salaryList=[float(empList[i][2]) for i in range(1,len(empList))]
print(salaryList)
print(f'Maximum Salary :{max(salaryList)}')
print(f'Minimum Salary :{min(salaryList)}')
print(f'Total Salary :{sum(salaryList)}')

except FileNotFoundError:
print("file not found")

main()

Output - Reference to CSV file created in Experiment-9 above. Below the contents read in IDLE.
Experiment-11: Create a file with the name student.txt, and write data to the file.

Source code:

# write a program to store student data


def main():
try:
f=open("student.txt","w")
while True:
rollno=int(input("Rollno:"))
name=input("Name:")
course=input("Course:")
print(rollno,name,course,file=f)

ch=input("Add another student?")


if ch=="no":
break

except OSError:
print("unable to create file")

finally:
f.close()

main()

Writing or Adding data contents to Text file:

Output – Text file created under same folder as module, and opened to view the added contents:
Experiment-12: Create a file with the name student.txt, and read data from the file.

Source code:

#reading text from file


def main():

try:
f=open("student.txt","r")
s=f.read()
print(s)

except FileNotFoundError:
print("file not found")

finally:
f.close()

main()

Output - Reference to Text file created in Experiment-11 above. Below the contents read in IDLE:
Experiment-13: Implement the working of packages.

Source code:

#Create a folder with name package1 in a given location, and add two python modules.
#Module1: saved as Exp13_module1 under folder “package1”.
def fun1():
print("inside fun1")
def fun2():
print("inside fun2")
def fun3():
print("inside fun3")

#Module2: saved as Exp13_module2 under folder “package1”.


def fun1():
print("fun1 of module1")

import sys

sys.path.append(r"C:\Users\CARE
IT\Documents\Isbat\Via_Aspiration\AIT_Isbat\SEM4\Python\Lab\package1")

import package1.Exp13_module1
import package1.Exp13_module2

def main():
package1.Exp13_module1.fun1()
package1.Exp13_module1.fun2()
package1.Exp13_module1.fun3()
package1.Exp13_module2.fun4()

main()

Output:
Experiment-14: Implement calculator program using functions.

Source code:

def calculator(n1,n2,opr):

def add():
return n1+n2
def sub():
return n1-n2
def multiply():
return n1*n2
def div():
return n1/n2

if opr=='+':
print(f'Result is {add()}')
elif opr=='-':
print(f'Result is {sub()}')
elif opr=='*':
print(f'Result is {multiply()}')
elif opr=='/':
print(f'Result is {div()}')

def main():
num1=int(input("Enter First Number"))
num2=int(input("Enter Second Number"))
opr=input("Enter Operator")
calculator(num1,num2,opr)

main()

Output:

Add operation (+):

Subtract operation (-):


Multiply operation (*):

Division operation (/):

You might also like