0% found this document useful (0 votes)
3 views

Python Mca Lab

The document outlines various Python programming tasks including list and dictionary operations, arithmetic operations, sorting words, pattern printing, and implementing inheritance. It also covers recursive functions, class creation for power calculation, file character/word/line counting, date/time formatting, and basic database operations. Each task includes algorithms, sample programs, and expected outputs.

Uploaded by

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

Python Mca Lab

The document outlines various Python programming tasks including list and dictionary operations, arithmetic operations, sorting words, pattern printing, and implementing inheritance. It also covers recursive functions, class creation for power calculation, file character/word/line counting, date/time formatting, and basic database operations. Each task includes algorithms, sample programs, and expected outputs.

Uploaded by

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

Python Programming Lab

1.A) Create a list and perform the following methods:

(1)insert()

(2)remove()

(3)append()

(4)len()

(5)pop()

6)clear()

Aim: To write a python program to create a list and perform

Algorithms:

Step 1: start the program

Step 2: To selete the idle python

Step 3: To create the list insert (),remove (),append(),len(),pop(),and clear()

Step 4: To print the method

Step 5: To stop the program

PROGRAM

numbers = [21, 34, 54, 12]

print("List",numbers)

#using Remove method

numbers.remove(34)

print("after remove",numbers)

#using insert method


numbers.insert(0,1)

print("after insertion:",numbers)

# using append method

numbers.append(32)

print("After Append:", numbers)

#using len method

len(numbers)

print("lengnth:",numbers)

#using pop method

numbers.pop(2)

print("after pop",numbers)

#using clear method

numbers.clear()

print("after clear method",numbers)

OUTPUT

List [21, 34, 54, 12]

after remove [21, 54, 12]

after insertion: [1, 21, 54, 12]

After Append: [1, 21, 54, 12, 32]


lengnth: [1, 21, 54, 12, 32]

after pop [1, 21, 12, 32]

after clear method []

1.B) Create a dictionary and apply the following methods


1) Print the dictionary items
2) access items
3) use get()
4)change values
5) use len()

Aim: To write a python program to create a dictionary and apply

Algorithms :

Step 1: To start the all program

Step 2: To selete idle python

Step 3: to create and update the dictionary methods

Step 4: To print the method dictionary items,access item,use get(),change


value,len()

Step 5: stop the program

PROGRAM

# demo for all dictionary methods

#create a dictionary

dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}


print(dict1)

#add element to dictionary

dict1[5]="VB"

print("Updated Dictionary: ",dict1)

#accessing dictionary element

print(dict1[2])

#Change Value of Dictionary

dict1[3]="oracle"

print(dict1)

# get() method

print(dict1.get(3))

# len() method

print ("Length : %d" % len (dict1))

OUTPUT:

{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}


Updated Dictionary: {1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala', 5: 'VB'}

Java

{1: 'Python', 2: 'Java', 3: 'oracle', 4: 'Scala', 5: 'VB'}

oracle

Length : 5

2.A)Write a program to create a menu with the following options:

(1)TO PERFORM ADDITION

(2)TO PERFORM SUBTRACTION

(3)TO PERFORM MULTIPICATION

(4)TO PERFORM DIVISION

Aim: To write a python program to create a program menu

Algorithm:

1. Addition Operator : In Python, + is the addition operator. It is used to


add 2 vvalues.
2. Subtraction Operator : In Python, – is the subtraction operator. It is
used to subtract the second value from the first value.
3. Multiplication Operator : In Python, * is the multiplication operator. It
is used to find the product of 2 values.
4. Division Operator : In Python, / is the division operator. It is used to
find the quotient when first operand is divided by the second.
5. Stop the program

PROGRAM:

#store input numbers:

num1=input(‘Enter first number:’)

num2=input(‘Enter second number:’)

#Add two numbers

sum=float(num1)+float(num2)

#Subtract two numbers

min=float(num1)-float(num2)

# Multiply two numbers

mul=float(num1)*float(num2)

# Divide two numbers

div=float(num1)/float(num2)

#Display the sum

print(‘The sum of {0} and {1} is {2}’.format(num1,num2,sum))

#Display the subtraction

print(‘The subtraction of {0} and {1} is {2}’.format(num1,num2,min))

#Display the Multiplication


print(‘The multiplication of {0} and {1} is {2}’.format(num1,num2,mul))

#Display the division

print(‘The division of {0} and {1} is {2}’.format(num1,num2,div))

OUTPUT:

Enter first number :10

Enter second number:20

The sum of 10 and 20 is 30.0

The subtraction of 10 and 20 is -10.0

The multiplication of 10 and 20 is 200.0

The division of 10 and 20 is 0.5

2)B)Write a python program to sort words in Alphabetic order?

Aim: To write a python program to create sort words in alphabetic order

Algorithms:

Step 1: To start the program

Step 2: To using idle python to create the program

Step 3: To declare the words and print the method

Step 4: To print the sorted values

Step 5: stop the program


PROGRAM:

#sort words in alphabetic order

mystr=” Hello this is an example”

words=[word.lower()for word in mystr.split()]

words.sort()

print(“ The sorted words are:”)

for word in |words:

print(word)

OUTPUT:

an

example

Hello

Is

This
3)A)Write a python program to construct the following pattern using nested
for loop?

*
**
***
****
*****
****
***
**
*
Aim: To write a python program to construct the pattern using nested for
loop

Algorithm:
Step 1: Start the program

Step 2: Decide the number of rows and columns

There is a typical structure to print any pattern, i.e., the number of rows
and columns. We need to use two loops to print any pattern, i.e.,
use nested loops.

The outer loop tells us the number of rows, and the inner loop tells us the
column needed to print the pattern.

Accept the number of rows from a user using the input() function to
decide the size of a pattern.

Step 3:Iterate rows

Next, write an outer loop to Iterate the number of rows using a for
loop and range() function.

Step 4:Iterate columns


Next, write the inner loop or nested loop to handle the number of
columns. The internal loop iteration depends on the values of the outer
loop.

Step 5:Print star or number

Use the print() function in each iteration of nested for loop to display the
symbol or number of a pattern (like a star (asterisk *) or number).

Step 6:Add new line after each iteration of outer loop

Add a new line using the print() function after each iteration of the outer
loop so that the pattern display appropriately

PROGRAM:

num=int(input(“enter the no.of inputs:”))


for i in range(num):
for j in range(i):
print(‘*’,end=””)
print(“)

for I in range(num,0,-1):
for j in range(i):
print(‘*’,end=””)
print(“)

OUTPUT:
Enter the no.of inputs:5
*
**
***
****
*****
****
***
**
*

3)b)Write a python program, using for loop that prints out the decimal
equivalents of 1/2,1/3,1/4...1/10

PROGRAM:

1)for i in range(2,11):

print((1/i),end=" ")

2)a=[]

for i in range(2,11):

a.append(1/i)

print(a)

Output 1

0.5 0.3333333333333333 0.25 0.2 0.16666666666666666 0.14285714285714285


0.125 0.1111111111111111 0.1

Output 2

[0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666,


0.14285714285714285, 0.125, 0.1111111111111111, 0.1]

4. Write a program in python, A library charges a fine for every book


returned late. For first 5 days the fine is 50 paisa, for 6-10 days fine is one
rupee and above 10days fine is 5 rupees. If you return the book after 30 days
your membership will be cancelled. Write a program to accept the number of
days the member is late to return the book and display the fine or the
appropriate message?

Aim: To write a python program to a library charges


Algorithms:

Step 1:To start the program

Step 2: To selete idle python to create a library

Step 3:To declare the days and fine amount

Step 4: To print the values and run

Step 5: stop the program

PROGRAM:

days = int(input("Enter the Number of Days :"))

if (days>0 and days<= 5):

amt = 0.50 * days

print("Fine Amount Pay to Rs :", amt)

elif(days >= 6 and days <= 10):

amt = 1 * days

print("Fine Amount Pay to Rs :", amt)

elif (days > 10):

amt = 5 * days

print("Fine Amount Pay to Rs :", amt)

if (days > 30):

print("Your Membership would be Cancelled..")

else:
print("Invalid")

OUTPUT

Enter the Number of Days :11

Fine Amount Pay to Rs : 55

5. Write a python program to implement single, multiple and multilevel


inheritance.
Aim : To write a python program to implement single , multiple nad
multilevel inheritance

ALGORITHM:
Step 1: Start the program

Step 2: Single Inheritance:


Single inheritance enables a derived class to inherit properties from a
single parent class, thus enabling code reusability and the addition of new
features to existing code.
Step3: Multiple Inheritance:
When a class can be derived from more than one base class this type of
inheritance is called multiple inheritances. In multiple inheritances, all the
features of the base classes are inherited into the derived class.
Step 4: Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class
are further inherited into the new derived class. This is similar to a
relationship representing a child and a grandfather.
Step 5: Stop the program
PROGRAM

# single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class

class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()

OUTPUT:
This function is in parent class.
This function is in child class.

Multiple Inheritance:
# Base class1
class Mother:
mothername = ""

def mother(self):
print(self.mothername)

# Base class2

class Father:
fathername = ""
def father(self):
print(self.fathername)

# Derived class

class Son(Mother, Father):


def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

OUTPUT:

Father : RAM
Mother : SITA

Multilevel Inheritance :

# Base class

class Grandfather:

def __init__(self, grandfathername):


self.grandfathername = grandfathername

# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername

# invoking constructor of Grandfather class


Grandfather.__init__(self, grandfathername)

# Derived class

class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname

# invoking constructor of Father class


Father.__init__(self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)

# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()

Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

6) Write a python program to implement recursive function.


Aim: To write a python program to implement recursive function

ALGORITHM:

Step 1: Start the program

Step 2: factorial() is a recursive function as it calls itself.

Step 3: When we call this function with a positive integer, it will recursively
call itself by decreasing the number.

Step 4: Each function multiplies the number with the factorial of the number
below it until it is equal to one.

Step 5:Our recursion ends when the number reduces to 1. This is called the
base condition.

Step 6:Stop the program

PROGRAM

def factorial(x):

“”””This is a recursive function to find the factorial of an integer””

if x==1:

return 1

else:

return(x*factorial(x-1))

num=3

print(“The factorial of”,num ,”is”,factorial(num))

OUTPUT:
The factorial of 3 is 6

6)B) Write a program to create a class to implement pow(x,n).

Aim: To write a program to create a class implement

Algorithms:

Step 1: To start the program

Step 2: To select the idle python to using create a class

Step 3: To declare the class abc

Step 4: to print the values

Step 5 : Stop the program

PROGRAM:
class abc:

def f(x,y):

return pow(x,y)

print(abc.f(2,3))

OUTPUT:

7)write a python program to compute the number of characters,words and


lines in a file

Aim:To write a python program to compute the number of characters words


and lines in a file

Algorithms:

Step 1: start the program

Step 2: To selete the idle python

Step 3: To compute the number of characters words and lines in file


Step 4: To print the method

Step 5: To stop the program

Program:
file = open("trial.txt", "r")

number_of_lines = 0

number_of_words = 0

number_of_characters = 0

for line in file:

number_of_lines =number_of_lines +1

line = line.strip("\n")

print(line)

words = line.split()

number_of_words += len(words)

number_of_characters += len(line)

file.close()

print("lines:", number_of_lines, "words:", number_of_words, "characters:", number_of_characters)

OUTPUT:

Hello World

Hello Again

Goodbye
lines: 3 words: 5 characters: 29

8)write a python program to display different date and time formats.

Aim:To write a python program to display dtae nd time format

Algorithms:

Step 1: start the program

Step 2: To selete the idle python

Step 3: To create display the date and time format

Step 4: To print the time

Step 5: To stop the program

program:

import datetime

now = datetime.datetime.now()

print("Current date and time:- ")

print(now.strftime("%Y-%m-%d %H:%M:%S"))

print(now.strftime("%d/%m/%Y %I:%M:%S %p"))

print(now.strftime("%a, %b %d, %Y"))

print(now.strftime("%c"))

OUTPUT:
Current date and time:

2023-05-3111:05:20

31/05/202311:52:20AM

Wed,May31,2023

05/31/23 11:52:20

9) Write a python program using database connection to execute the following


SQL query.

1.create

2.insert

3.select

4.delete operation

Aim:To write a python program using database connection the SQL query

Algorithms:

Step 1: start the program

Step 2: To selete the idle python

Step 3: To using database the SQL query to create ,insert,select,delete


operation

Step 4: To print the table

Step 5: To stop the program

Program:
import sqlite3
# connect to the database

conn = sqlite3.connect("test.db")

# create the student table

cursor = conn.cursor()

conn.execute("create table comp5(id number(5),name char(30),age number(3),address char(50),salary


number(7,2));")

print("table created successfully");

# insert a new student

cursor.execute("""insert into comp5(id,name,age,address,salary) values(1,'meera',22,'new st',5000)""")

print(cursor.rowcount,"record inserted.")

cursor.execute("""insert into comp5(id,name,age,address,salary) values(2,'usha',23,'west st',6000)""")

print(cursor.rowcount,"record inserted.")

cursor.execute("""insert into comp5(id,name,age,address,salary) values(3,'divya',25,'west st',40000)""")

conn.commit()

print(cursor.rowcount,"record inserted.")

# select all students

cursor.execute("SELECT * FROM comp5")

myresult = cursor.fetchall()

for x in myresult:

print(x)

# delete a student

cursor.execute("DELETE FROM comp5 WHERE name = 'meera'")

conn.commit()

print(cursor.rowcount,"record(s) deleted.")
cursor.execute("SELECT * FROM comp5")

myresult = cursor.fetchall()

for x in myresult:

print(x)

# close the database connection

conn.close()

OUTPUT:

>>>

table created successfully

1 record inserted.

1 record inserted.

1 record inserted.

(1, 'meera', 22, 'new st', 5000)

(2, 'usha', 23, 'west st', 6000)

(3, 'divya', 25, 'west st', 40000)

1 record(s) deleted.

(2, 'usha', 23, 'west st', 6000)

(3, 'divya', 25, 'west st', 40000)

>>>
10)Write a python program to implement digital clock using GUL

Aim:To write a python program to implement digital clock using GUL

Algorithm:

Step 1: start the program

Step 2: To selete the idle python

Step 3: To implement the digital clock using GUL

Step 4: To update the clock and print

Step 5: To stop the program

Program:

import tkinter as tk

import time

def update_clock():

current_time = time.strftime('%H:%M:%S')

clock_label.config(text=current_time)

clock_label.after(1000, update_clock)
root = tk.Tk()

root.title("Digital Clock")

root.geometry("300x150")

clock_label = tk.Label(root, font=('Helvetica', 48), bg='black', fg='white')

clock_label.pack(expand=True)

update_clock()

root.mainloop()

OUTPUT:

You might also like