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

Practical Python

The document contains various Python programs covering topics such as student details management, queue and stack operations, library management, matrix operations, Armstrong number checks, password validation, and shopping cart functionality. Each section includes user input prompts and functions to perform specific tasks, such as enqueueing and dequeueing in queues, performing matrix arithmetic, and sorting words by length. The document serves as a comprehensive guide to basic programming concepts and data structures in Python.
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)
2 views17 pages

Practical Python

The document contains various Python programs covering topics such as student details management, queue and stack operations, library management, matrix operations, Armstrong number checks, password validation, and shopping cart functionality. Each section includes user input prompts and functions to perform specific tasks, such as enqueueing and dequeueing in queues, performing matrix arithmetic, and sorting words by length. The document serves as a comprehensive guide to basic programming concepts and data structures in Python.
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

DICTIONARY

students={}
for i in range(4):
print("\n enter details of students",i+1)
name=input("enter name: ")
dob=input("enter date of birth (DD-MM-YYYY): ")
year=input("enter year of admission: ")
dept=input("enter department: ")

students[name]={
"Date of birth" : dob,
"Year of admission" : year,
"department":dept
}

with open("[Link]","w") as file:


for name, details in [Link]():
[Link](f"Name: {name}\n")
[Link](f"Date of birth: {details['Date of birth']}\n")
[Link](f"Year of admission: {details['Year of admission']}\n")
[Link](f"Department: {details['department']}\n")
[Link](".........................\n")

print("\n student details are stored successfully")

command line
import sys
if len([Link])!=3:
print("usage: python [Link] [Link] [Link]")
exit()

source=[Link][1]
destination=[Link][2]

with open(source,"r") as fin:


with open(destination,"w")as fout:
line_no=1
for line in fin:
line=[Link]("\n")
length=len(line)
[Link](f"{line_no}. {line} ({length})\n")
line_no+=1

QUADRATIC EQUATION
import math
a=float(input("enter coefficient a : "))
b=float(input("enter coefficient b : "))
c=float(input("enter coefficient c : "))

if a==0:
print("not a quadratic equation")

else:
d=b**2 - 4*a*c

if d>0:
x1=(-b+[Link](d))/(2*a)
x2=(-[Link](d))/(2*a)
print("two distinct real roots are: ")
print(f"x1 = {x1:.3f}")
print(f"x2 = {x2:.3f}")

elif d==0:
x=-b/(2*a)
print("two equal real roots are : ")
print("x1=x2=",x)

else:
real=-b/(2*a)
imag=[Link](-d)/(2*a)
print("complex roots are:")
print("x1=",real,"+",imag,"i")
print("x2=",real,"-",imag,"i")

queue=[]
MAX=5

def overflow():
if len(queue)==MAX:
return True
return False

def underflow():
if len(queue)==0:
return True
return False

def enqueue():
if overflow():
print("overflow")
else:
item=int(input("enter an element: "))
[Link](item)
print(item,"item inserted into the queue")
def dequeue():
if underflow():
print("underflow")
else:
item=[Link](0)
print("deleted item= ",item)

def display():
if underflow():
print("queue is empty")
else:
print("queue",queue)

while True:
print("\n .....Queue menu........")
print("[Link]")
print("2. Dequeue")
print("3. Display")
print("4. Exit")

choice=int(input("enter a choice : "))

if choice==1:
enqueue()

elif choice==2:
dequeue()

elif choice==3:
display()

elif choice==4:
print("program ended")
break
else:
print("invalid choice")

# Stack Operations in Python

stack = []
MAX = 5

def Overflow():
if len(stack) == MAX:
return True
return False
def Underflow():
if len(stack) == 0:
return True
return False

def Push():
if Overflow():
print("Stack Overflow")
else:
item = int(input("Enter element: "))
[Link](item)
print(item, "inserted")

def Pop():
if Underflow():
print("Stack Underflow")
else:
item = [Link]()
print("Deleted element:", item)

def Display():
if Underflow():
print("Stack is Empty")
else:
print("Stack:", stack)

while True:
print("\[Link]")
print("[Link]")
print("[Link]")
print("[Link]")

choice = int(input("Enter your choice: "))

if choice == 1:
Push()
elif choice == 2:
Pop()
elif choice == 3:
Display()
elif choice == 4:
print("Program Ended")
break
else:
print("Invalid Choice")

library
class library:
def __init__(self):
self.acc_number=""
[Link]=""
[Link]=""
[Link]=""

def read(self):
self.acc_number=input("enter accession number: ")
[Link]=input("enter publisher name: ")
[Link]=input("enter book title: ")
[Link]=input("enter author name: ")

def compute(self):
days=int(input("enter no. of days late: "))
fine=days*1.50
print("fine charged = $",fine)

def display(self):
print("\n ........library details...............")
print("Accession number: ",self.acc_number)
print("Publisher: ",[Link])
print("Title: ",[Link])
print("Author: ",[Link])

book= library()
[Link]()
[Link]()
[Link]()

def non_fibonacci(n):
a=1
b=2
count=0

while count<n:
for i in range (a+1,b):
if count<n:
print(i,end=" ")
count+=1

a, b = b, a + b

while True:
print("\n1. Print non fibonacci series")
print("2. exit")
ch=int(input("enter your choice : "))

if ch==1:
n=int(input("enter no. of terms: "))
non_fibonacci(n)
print()

elif ch==2:
break
else:
print("invalid choice")

sort a list
n=int(input("enter no. of terms: "))
Ist=[]
print("enter elements\n")
for i in range(n):
[Link](int(input()))

duplicate=False

for i in range(n):
for j in range(i+1,n):
if Ist[i]==Ist[j]:
duplicate=True

if duplicate:
print("duplicate element found , sorting not possible")

else:
for i in range(n-1):
for j in range(n-i-1):
if Ist[j]>Ist[j+1]:
Ist[j],Ist[j+1]=Ist[j+1],Ist[j]

print("sorted list: ",Ist)

5. Queue Operations (createQueue, enque, deque)


queue = []

def createQueue():
global queue
queue = []
print("Queue Created")
def enque():
item = int(input("Enter element: "))
[Link](item)
print(item, "Inserted")

def deque():
if len(queue) == 0:
print("Queue Underflow")
else:
print("Deleted:", [Link](0))

while True:
print("\[Link] Queue")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")

ch = int(input("Enter choice: "))

if ch == 1:
createQueue()

elif ch == 2:
enque()

elif ch == 3:
deque()

elif ch == 4:
print("Queue =", queue)

elif ch == 5:
break

else:
print("Invalid Choice")

def reverse_string(s):
if s==s[::-1]:
return s
else:
return s[::-1]

n=int(input("enter no. of strings: "))


listStr=[]
for i in range(n):
[Link](input("enter string : "))
print("\n result: ")

for s in listStr:
print(reverse_string(s))

BINARY SEARCH

n=int(input("enter no. of elements: "))


lst=[]
print("enter elements: ")
for i in range(n):
[Link](int(input()))

for i in range(n-1):
for j in range(n-i-1):
if lst[j]>lst[j+1]:
lst[j],lst[j+1]=lst[j+1],lst[j]
print("sorted list: ",lst)

key=int(input("enter the elements to search: "))


low=0
high=len(lst)-1
found=False

while low<=high:
mid=(low+high)//2

if lst[mid]==key:
print("elements found at index",mid)
found=True
break
elif lst[mid]<key:
low=mid+1

else:
high=mid-1

if not found:
print("element not found")

print("enter dimenstions of matrix A")


r1=int(input("rows: "))
c1=int(input("columns: "))
A=[]
print("enter elements of matrix A : ")
for i in range(r1):
row=[]
for j in range(c1):
[Link](int(input()))
[Link](row)

print("\n enter dimensions of matrix B")


r2=int(input("rows: "))
c2=int(input("coloumns: "))
B=[]
print("enter elements of matrix B: ")
for i in range (r2):
row=[]
for j in range(c2):
[Link](int(input()))
[Link](row)

while True:
print("\n .......Menu.........")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. exit")

ch=int(input("enter your choice: "))

if ch==1:
if r1!=r2 or c1!=c2:
print("\n Matrix addtion is not possible.")

else:
print("\n Addition.")
for i in range(r1):
for j in range(c1):
print(A[i][j] + B[i][j], end=" ")
print()

elif ch==2:
if r1!=r2 or c1!=c2:
print("\nmatrix subtraction is not possible.")

else:
print("\n subtraction")
for i in range(r1):
for j in range(c2):
print(A[i][j] - B[i][j], end=" ")
print()
elif ch==3:
if c2!=r1:
print("\n multiplicatioin is not possible")
else:
result=[]
for i in range(r1):
row=[]
for j in range(c2):
[Link](0)
[Link](row)

for i in range(r1):
for j in range(c2):
for k in range(c1):
result[i][j]+=A[i][k] + B[k][j]

print("\n matrix multiplication")


for i in range(r1):
for j in range(c2):
print(result[i][j], end=" ")

print()
else:
print("invalid choice")

Program 1: Check Whether a Number is an Armstrong Number


def armstrong(n):
temp = n
digits = len(str(n))
total = 0

while temp > 0:


digit = temp % 10
total = total + digit ** digits
temp = temp // 10

if total == n:
print(n, "is an Armstrong Number")
else:
print(n, "is not an Armstrong Number")

num = int(input("Enter a number: "))


armstrong(num)
Another Method (Using [Link]())
import math

def perfect_square(start, end):


for i in range(start, end + 1):
if [Link](i) == int([Link](i)):
print(i, end=" ")

start = int(input("Enter starting number: "))


end = int(input("Enter ending number: "))

perfect_square(start, end)

passwords=input("enter comma separated password: ").split(",")


valid=[]
for password in passwords:
password=[Link]()
lower=False
upper=False
digit=False
special=False

if len(password)>=6 and len(password)<=12:


for ch in password:
if [Link]():
lower=True
elif [Link]():
upper=True

elif [Link]():
digit=True

elif ch in "@#$&":
special=True

if lower and upper and digit and special:


[Link](password)

print("valid passwords are: ")


print(" , ".join(valid))

Q6. Deque (Double Ended Queue) Menu Driven


deque = []

while True:

print("\n----- MENU -----")


print("1. Insert Front")
print("2. Insert Rear")
print("3. Delete Front")
print("4. Delete Rear")
print("5. Display")
print("6. Exit")

ch = int(input("Enter choice: "))

if ch == 1:
item = int(input("Enter element: "))
[Link](0, item)
print("Inserted at Front")

elif ch == 2:
item = int(input("Enter element: "))
[Link](item)
print("Inserted at Rear")

elif ch == 3:
if len(deque) == 0:
print("Deque Underflow")
else:
print("Deleted:", [Link](0))

elif ch == 4:
if len(deque) == 0:
print("Deque Underflow")
else:
print("Deleted:", [Link]())

elif ch == 5:
print("Deque =", deque)

elif ch == 6:
break

else:
print("Invalid Choice")

Q4. Shopping Cart Using Class (Menu Driven)


class ShoppingCart:

def __init__(self):
[Link] = {}

def add_item(self):
name = input("Enter item name: ")
price = float(input("Enter price: "))
[Link][name] = price
print("Item Added Successfully.")

def remove_item(self):
name = input("Enter item name to remove: ")

if name in [Link]:
del [Link][name]
print("Item Removed Successfully.")
else:
print("Item not found.")

def total_price(self):
total = sum([Link]())
print("Total Price =", total)

def display(self):
if len([Link]) == 0:
print("Shopping cart is empty.")
else:
print("\nItems in Cart")
for item, price in [Link]():
print(item, ":", price)

cart = ShoppingCart()

while True:

print("\n----- MENU -----")


print("1. Add Item")
print("2. Remove Item")
print("3. Display Cart")
print("4. Total Price")
print("5. Exit")

ch = int(input("Enter choice: "))

if ch == 1:
cart.add_item()

elif ch == 2:
cart.remove_item()

elif ch == 3:
[Link]()
elif ch == 4:
cart.total_price()

elif ch == 5:
break

else:
print("Invalid Choice")
1. Sort Words in Decreasing Order of Length
sentence = input("Enter a sentence: ")

words = [Link]()

for i in range(len(words)):
for j in range(i + 1, len(words)):
if len(words[i]) < len(words[j]):
words[i], words[j] = words[j], words[i]

print("\nWords in decreasing order of length:")

for word in words:


print(word, "-", len(word))
Sample Output
Enter a sentence: Python is a powerful programming language

programming - 11
powerful - 8
language - 8
Python - 6
is - 2
a-1

2. Reverse Each Word in a Text File


input_file = input("Enter input file name: ")
output_file = input("Enter output file name: ")

with open(input_file, "r") as fin, open(output_file, "w") as fout:

for line in fin:


words = [Link]()

for word in words:


[Link](word[::-1] + " ")

[Link]("\n")

print("Words reversed successfully.")


Q2. Matrix Operations Using Separate Functions
def addition(A, B, r, c):
print("\nAddition:")
for i in range(r):
for j in range(c):
print(A[i][j] + B[i][j], end=" ")
print()

def subtraction(A, B, r, c):


print("\nSubtraction:")
for i in range(r):
for j in range(c):
print(A[i][j] - B[i][j], end=" ")
print()

def multiplication(A, B, r1, c1, c2):


result = []

for i in range(r1):
row = []
for j in range(c2):
[Link](0)
[Link](row)

for i in range(r1):
for j in range(c2):
for k in range(c1):
result[i][j] += A[i][k] * B[k][j]

print("\nMultiplication:")
for i in range(r1):
for j in range(c2):
print(result[i][j], end=" ")
print()

# Input

r1 = int(input("Enter rows of Matrix A: "))


c1 = int(input("Enter columns of Matrix A: "))

A = []

print("Enter Matrix A")


for i in range(r1):
row = []
for j in range(c1):
[Link](int(input()))
[Link](row)

r2 = int(input("Enter rows of Matrix B: "))


c2 = int(input("Enter columns of Matrix B: "))

B = []

print("Enter Matrix B")

for i in range(r2):
row = []
for j in range(c2):
[Link](int(input()))
[Link](row)

if r1 == r2 and c1 == c2:
addition(A, B, r1, c1)
subtraction(A, B, r1, c1)
else:
print("Addition and Subtraction not possible.")

if c1 == r2:
multiplication(A, B, r1, c1, c2)
else:
print("Multiplication not possible.")

# Create Set A (even numbers less than 12)


A = set(range(2, 12, 2))

# Create Set B (perfect squares less than 30)


B = set()

for i in range(1, 30):


if i * i < 30:
[Link](i * i)
else:
break

print("Set A =", A)
print("Set B =", B)

print("Union =", A | B)
print("Intersection =", A & B)
print("Difference (A-B) =", A - B)
print("Difference (B-A) =", B - A)

date and time

from datetime import datetime

class Clock:

def show_time(self):
now = [Link]()
print("Time :", [Link]("%H:%M:%S"))

class Calendar:

def show_date(self):
now = [Link]()
print("Date :", [Link]("%d-%m-%Y"))
print("Month:", [Link]("%B"))

class CalendarClock(Clock, Calendar):

def display(self):
self.show_date()
self.show_time()

obj = CalendarClock()
[Link]()

You might also like