0% found this document useful (0 votes)
5 views66 pages

INDEX

The document outlines a series of programming experiments and tasks, including student mark processing, countdown sequences, list operations, matrix calculations, and string analysis. Each experiment is dated and includes input prompts, processing logic, and expected outputs. The content serves as a guide for implementing various programming concepts and functions.

Uploaded by

anbuselvan0396
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)
5 views66 pages

INDEX

The document outlines a series of programming experiments and tasks, including student mark processing, countdown sequences, list operations, matrix calculations, and string analysis. Each experiment is dated and includes input prompts, processing logic, and expected outputs. The content serves as a guide for implementing various programming concepts and functions.

Uploaded by

anbuselvan0396
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
You are on page 1/ 66

INDEX

EX.N DATE EXPERIMENTS PG.N SIGN

O O

1. 24/6/24 LIST: Student Mark 1

Processing

2. 24/6/24 Countdown Sequence 3

3. 27/6/24 LIST: Perform Ascending, 5

Descending, Small &

Biggest No.

4. 27/6/24 CHOICE: Perform Mul, 7

SOD, Fact

5. 2/7/24 MATRIX: Add, Sub, Mul 9

Operation

6. 5/7/24 COUNT: Vowels, Cons, 13

Digs, SplChars, Alphas,

UCs & LCs

7. 5/7/24 CALCULATE: Mean, 17

Median, Mode

8. 5/7/24 LIST: Perform Stack 19


Operations

9. 10/7/24 DICTIONARY: Book 21

Management

10. 10/7/24 DICTIONARY: Student 23

Mark Detail

11. 15/7/24 User Defined Function 26

Fibonacci Series

12. 15/7/24 User Defined Function 28

nPr, nCr Calculation

13. 23/7/24 User Defined Function 30

Palindrome Check

14. 23/7/24 RECURSIVE: GCD 32

15. 23/7/24 User Defined Function 34

Armstrong, Adam,

Perfect & Power

Operations

16. 26/7/24 RECURSIVE: SOD 38

17. 26/7/24 RECURSIVE: SOS 40

18. 9/8/24 Product Billing Using 42

Tuple
19. 9/8/24 Sum & Product of Nos. 45

Using Tuple

20. 19/8/24 Reverse the String Using 47

File

21. 19/8/24 Count Char & Words 49

Using File

22. 22/8/24 Regular Expression: Read 51

a File

23. 22/8/24 Regular Expression: 53

HTML File

24. 28/8/24 Create a Calculator Using 55

GUI

25. 31/8/24 Create a Chat Using TCP 58

& IP

26. 4/9/24 Perform Tasks Using 60

Thread

27. 4/9/24 Perform Tasks Using 62

Queue
1. STUDENT MARK SHEET PROCESS
USING LIST
print("\t\t STUDENT MARK SHEET \t\t")
l=[]
na=input("Enter Student Name :")
rn=input("Enter Roll NO :")
l.append(na)
l.append(rn)
for i in range(3):
mark=int(input("Enter Marks :"))
l.append(mark)
tot=l[2]+l[3]+l[4]
avg=tot/3
print("\t\t\t ------ OUTPUT ------ \t\t\t")
print("Student Name :",na)
print("Roll NO :",rn)
print("Computer Science :",l[2])
if(l[2]<40):
print("Result : Fail")
else:
print("Result : Pass")
print("Mathematics :",l[3])
if(l[3]<40):
print("Result : Fail")
else:
print("Result : Pass")
print("English :",l[4])
if(l[4]<40):
print("Result : Fail")
else:
print("Result : Pass")
print("Total :",tot)
print("Average :",avg)
if(l[2]<40 or l[3]<40 or l[4]<40):
print("You Failed in a Subject")
else:
if(avg>=60):
print("First Class")
elif(avg>=50 and avg<60):
print("Second Class")
else:
print("Third Class")
OUTPUT:
STUDENT MARK SHEET
Enter Student Name: Mani
Enter Roll NO: 22AUCS044
Enter Marks: 90
Enter Marks: 98
Enter Marks: 89
------ OUTPUT ------
Student Name: Mani
Roll NO: 22AUCS044
Computer Science: 90
Result: Pass
Mathematics: 98
Result: Pass
English: 89
Result: Pass
Total: 277
Average: 92.33333333333333
First Class

2
2. COUNTDOWN SEQUENCE
while(True):
print("1.Using While Loop")
print("2.Using For Loop")
ch=int(input("Enter Your Choice : "))
if(ch==1):
print("1.Using While Loop")
n=int(input("Enter a Number : "))
while(n>=0):
print(n)
n=n-1

if(ch==2):
print("2.Using For Loop")
n1=int(input("Enter a Number : "))
for i in range(n1,-1,-1):
print(i)

if(ch==3):
break

ch1=input("Do You Want To Continue


(Y/N) ? :")
if ch1.lower()!='y':
break

3
OUTPUT:
1.Using While Loop
2.Using For Loop
Enter Your Choice : 1
1.Using While Loop
Enter a Number : 5
5
4
3
2
1
0
Do You Want To Continue (Y/N) ? :Y
1.Using While Loop
2.Using For Loop
Enter Your Choice : 2
2.Using For Loop
Enter a Number : 4
4
3
2
1
0
Do You Want To Continue (Y/N) ? :N

4
3. PERFORM ASCENDING, DESCENDING,
SMALLEST & BIGGEST USING LIST
l=[]
print("Enter the number of
elements: ")
n=int(input())
print("Enter list elements: ")
for i in range(n):
element=int(input())
l.append(element)
for i in range(0,len(l)):
for j in range(i+1,len(l)):
if(l[i]>l[j]):
l[i],l[j]=l[j],l[i]
print("Ascending order:",l)
for i in range(0,len(l)):
for j in range(i+1,len(l)):
if(l[i]<l[j]):
l[i],l[j]=l[j],l[i]
print("Descending order:",l)
print("Smallest value:",l[-1])
print("Biggest value:",l[0])

5
OUTPUT:
Enter the number of elements:
5
Enter list elements:
6
7
3
-7
-33
Ascending order: [-33, -7, 3, 6, 7]
Descending order: [7, 6, 3, -7, -33]
Smallest value: -33
Biggest value: 7
6
4. PERFORM Mul, SOD & FACTORIAL
USING CHOICE
while(True):
print("1.Multiplication Table")
print("2.Factorial")
print("3.Sum of Digits")
ch=int(input("Enter Your Choice : "))
if(ch==1):
print("\t\t ----MULTIPLICATION TABLE---- \t\t")
m=int(input("Enter the multiplier : "))
n=int(input("Enter the number of terms : "))
for i in range(1,n+1,1):
print(m,"*",i,"=",m*i)
elif(ch==2):
print("\t\t ----FACTORIAL---- \t\t")
n=int(input("Enter the number : "))
f=1
for i in range(n,0,-1):
f=f*i
print("Factorial value is : ",f)
elif(ch==3):
print("\t\t ----SUM OF DIGITS---- \t\t")
s=0
n=int(input("Enter the Number : "))
while(n>0):
r=n%10
s=s+r
n=n//10
if(s%9==0):
s=9
print("Sum of digits is : ",s)
else:
print("Invalid choice")

ch1=input("Do You Want To Continue (Y/N) ? :")


if ch1.lower()!='y':
break

7
OUTPUT:
1.Multiplication Table
2.Factorial
3.Sum of Digits
Enter Your Choice : 1
----MULTIPLICATION TABLE----
Enter the multiplier : 4
Enter the number of terms : 4
4*1=4
4*2=8
4 * 3 = 12
4 * 4 = 16
Do You Want To Continue (Y/N) ? :Y
1.Multiplication Table
2.Factorial
3.Sum of Digits
Enter Your Choice : 2
----FACTORIAL----
Enter the number : 4
Factorial value is : 24
Do You Want To Continue (Y/N) ? :Y
1.Multiplication Table
2.Factorial
3.Sum of Digits
Enter Your Choice : 3
----SUM OF DIGITS----
Enter the Number : 99
Sum of digits is : 9
Do You Want To Continue (Y/N) ? :N

8
5. ADDITION, SUBTRACTION,
MULTIPLICATION USING MATRIX
r1 = int(input("Enter the No.of Rows in Matrix 1: "))
c1 = int(input("Enter the No.of Columns in Matrix 1: "))
r2 = int(input("Enter the No.of Rows in Matrix 2: "))
c2 = int(input("Enter the No.of Columns in Matrix 2: "))
if c1 != r2:
print("Matrix Multiplication is Not Possible")
else:
matrix1 = []
matrix2 = []
print("Enter values for Matrix 1:")
for i in range(r1):
row = []
for j in range(c1):
value = int(input(f"Enter a Value for {i+1},
{j+1}: "))
row.append(value)
matrix1.append(row)
print("Enter values for Matrix 2:")
for i in range(r2):
row = []
for j in range(c2):
value = int(input(f"Enter a Value for {i+1},
{j+1}: "))
row.append(value)
matrix2.append(row)
9

choice = input("Enter 'add' for addition, 'sub' for


subtraction, 'mul' for multiplication: ").strip().lower()

if choice == 'add' or choice == 'sub':


if r1 == r2 and c1 == c2:
add = []
sub = []
for i in range(r1):
a_row = []
s_row = []
for j in range(c1):
a_row.append(matrix1[i][j] + matrix2[i][j])
s_row.append(matrix1[i][j] - matrix2[i][j])
add.append(a_row)
sub.append(s_row)

if choice == 'add':
print("Addition of matrices:")
for row in add:
print(row)
elif choice == 'sub':
print("Subtraction of matrices:")
for row in sub:
print(row)

10

else:
print("Addition and Subtraction are not
possible due to dimension mismatch.")
elif choice == 'mul':
mul = []
for i in range(r1):
m_row = []
for j in range(c2):
value = 0
for k in range(c1):
value += matrix1[i][k] * matrix2[k][j]
m_row.append(value)
mul.append(m_row)

print("Multiplication of matrices:")
for row in mul:
print(row)
else:
print("Invalid choice. Please enter 'add',
'sub', or 'mul'.")

11

OUTPUT:
Enter the No.of Rows in Matrix 1: 3
Enter the No.of Columns in Matrix 1: 2
Enter the No.of Rows in Matrix 2: 2
Enter the No.of Columns in Matrix 2: 3
Enter values for Matrix 1:
Enter a Value for 1,1: 1
Enter a Value for 1,2: 2
Enter a Value for 2,1: 3
Enter a Value for 2,2: 4
Enter a Value for 3,1: 5
Enter a Value for 3,2: 6
Enter values for Matrix 2:
Enter a Value for 1,1: 1
Enter a Value for 1,2: 2
Enter a Value for 1,3: 3
Enter a Value for 2,1: 4
Enter a Value for 2,2: 5
Enter a Value for 2,3: 6
Enter 'add' for addition, 'sub' for subtraction,
'mul' for multiplication: mul
Multiplication of matrices:
[9, 12, 15]
[19, 26, 33]
[29, 40, 51]

12
6.COUNT VOWELS, ALPHABETS,
CONSONANTS, DIGITS, SPECIAL, UPPER &
LOWER CASE LETTERS
a = []
v = []
c = []
d = []
u = []
l = []
s = []
ca = cv = cc = cd = cu = cl = cs = 0
alpha="abcdefghijklmnopqrstuvwxyzABCDEFG
HIJKLMNOPQRSTUVWXYZ"
vowels = "aeiouAEIOU"
cons =
"bcdfghijklmnpqrstvwxyzBCDFGHIJKLMNPQRST
VWXYZ"
dig = "0123456789"
st = input("Enter a String : ")
for char in st:
if char in vowels:
cv += 1
v.append(char)
print("List of Vowels : ", v)
print("Count of Vowels : ", cv)
for char in st:
if char in alpha:
13

ca += 1
a.append(char)
print("List of Alphabets : ", a)
print("Count of Alphabets : ", ca)
for char in st:
if char in cons:
cc += 1
c.append(char)
print("List of Consonants : ", c)
print("Count of Consonants : ", cc)
for char in st:
if char in dig:
cd += 1
d.append(char)
print("List of Digits : ", d)
print("Count of Digits : ", cd)
for char in st:
if (char not in alpha) and (char not in dig):
cs += 1
s.append(char)
print("List of Special Characters : ", s)
print("Count of Special Characters : ", cs)

14

for char in st:


if char.isupper():
cu += 1
u.append(char)
print("List of UpperCase Letters : ", u)
print("Count of UpperCase Letters : ", cu)
for char in st:
if char.islower():
cl += 1
l.append(char)
print("List of LowerCase Letters : ", l)
print("Count of LowerCase Letters : ", cl)
15

OUTPUT:
Enter a String: KANAGARAJraj24$$%^
List of Vowels: ['A', 'A', 'A', 'A', 'a']
Count of Vowels: 5
List of Alphabets: ['K', 'A', 'N', 'A', 'G', 'A', 'R',
'A', 'J', 'r', 'a', 'j']
Count of Alphabets: 12
List of Consonants: ['K', 'N', 'G', 'R', 'J', 'r', 'j']
Count of Consonants: 7
List of Digits: ['2', '4']
Count of Digits: 2
List of Special Characters: ['$', '$', '%', '^']
Count of Special Characters: 4
List of UpperCase Letters: ['K', 'A', 'N', 'A', 'G',
'A', 'R', 'A', 'J']
Count of UpperCase Letters: 9
List of LowerCase Letters: ['r', 'a', 'j']
Count of LowerCase Letters: 3
16
7. CALCULATE MEAN, MEDIAN, MODE
l=[]
n=int(input("Enter List of Elements: "))
print("Enter",n,"Elements: ")
for i in range(0,n):
l.append(int(input()))
print("Given List:", l)
s=0
for i in range(0,n):
na=l[i]
s=s+na
mean=s/n
print("Mean:", mean)

l.sort()
print("Sorted Elements are:", l)

m=len(l)
if(m%2==0):
m1=l[m//2]
m2=l[m//2-1]
m3=(m1+m2)//2
else:
m3=l[m//2]
print("Median:", m3)

d=0
m=0
for i in range(0,len(l)):
e=0
for j in range(0,len(l)):
if(l[i]==l[j]):
e+=1
if(d<e):
d=e
mo=l[i]
print("Mode:", mo)

17
OUTPUT:
Enter List of Elements: 5
Enter 5 Elements:
6
3
0
-87
-54
Given List: [6, 3, 0, -87, -54]
Mean: -26.4
Sorted Elements are: [-87, -54, 0, 3, 6]
Median: 0
Mode: -87
18

8. PERFORM STACK OPERATIONS


l=[]
n=int(input("Enter Size of Elements : "))
print("Enter",n,"Elements : ")
for i in range(0,n):
l.append(int(input()))
print("Original Stack : ",l)
while(True):
print("STACK OPERATIONS")
print("1.INSERTION")
print("2.DELETION")
print("3.SEARCHING")
print("4.DISPLAY")
ch=int(input("Enter Your Choice : "))
if(ch==1):
print("1.INSERTION")
if(len(l)==n):
print("Stack is Full")
else:
a=int(input("Enter Data : "))
l.append(a)
elif(ch==2):
print("2.DELETION")
if(len(l)<=0):
print("Stack is Empty")
else:
l.pop()
print("Deletion Successful")
elif(ch==3):
print("3.SEARCHING")
s=int(input("Enter Elements for Search : "))
if(s in l):
print("Data Found in Stack")
else:
print("Data Not Found")
elif(ch==4):
print("4.DISPLAY")
print("Display : ",l)
elif(ch==5):
break

19
OUTPUT:
Enter Size of Elements : 5
Enter 5 Elements :
4
7
0
-24
-98
Original Stack : [4, 7, 0, -24, -98]
STACK OPERATIONS
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 1
1.INSERTION
Stack is Full
STACK OPERATIONS
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 2
2.DELETION
Deletion Successful
STACK OPERATIONS
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 3
3.SEARCHING
Enter Elements for Search : -98
Data Not Found
STACK OPERATIONS
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 4
4.DISPLAY
Display : [4, 7, 0, -24]
STACK OPERATIONS
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 5

20
9. LIBRARY BOOK MANAGEMENT USING
DICTONARY
book={}
print("\t\t ----BOOK SELECTION---- \t\t")
print("1.INSERTION")
print("2.DELETION")
print("3.SEARCHING")
print("4.DISPLAY")
while(True):
ch=int(input("Enter Your Choice : "))
if(ch==1):
print("\t\t ----BOOK INSERTION---- \t\t")
n1=input("Enter Book Name : ")
n2=input("Enter Author Name : ")
book.update({n1:n2})
print("----Book Insertion Success----")
if(ch==2):
print("\t\t ----BOOK DELETION---- \t\t")
de=input("Enter Book Name for Delete : ")
if de in book:
del book[de]
print("----Book Deletion Success----")
else:
print("----Book Not Found----")
if(ch==3):
print("\t\t ----BOOK SEARCHING---- \t\t")
s=input("Enter Book Name for Search : ")
if s in book:
print("----Book Found----")
else:
print("----Book Not Found----")
if(ch==4):
print("\t\t ----BOOK DISPLAY---- \t\t")
if(len(book)==0):
print("----Dictonary Empty----")
else:
for i,j in book.items():
print("Book Name : " ,i)
print("Author Name : " ,j)
if(ch==5):
break
21
OUTPUT:
----BOOK SELECTION----
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 1
----BOOK INSERTION----
Enter Book Name : Python
Enter Author Name : Guido van Rossum
----Book Insertion Success----
Enter Your Choice : 1
----BOOK INSERTION----
Enter Book Name : Java
Enter Author Name : James Gostling
----Book Insertion Success----
Enter Your Choice : 2
----BOOK DELETION----
Enter Book Name for Delete : Java
----Book Deletion Success----
Enter Your Choice : 3
----BOOK SEARCHING----
Enter Book Name for Search : Java
----Book Not Found----
Enter Your Choice : 4
----BOOK DISPLAY----
Book Name : Python
Author Name : Guido van Rossum
Enter Your Choice : 5
22

10. STUDENT MARK DETAILS USING


DICTONARY
student={}
print("\t\t ----STUDENT DETAILS---- \t\t")
print("1.INSERTION")
print("2.DELETION")
print("3.SEARCHING")
print("4.DISPLAY")
while(True):
ch=int(input("Enter Your Choice : "))
if(ch==5):
break
if(ch==1):
m=[]
na=input("Enter Student Name : ")
rno=input("Enter Roll No : ")
for i in range(3):
m.append(int(input("Enter Marks : ")))
student.update({na:{rno:m}})
print("---- Student Info Updated----")
if(ch==2):
de=input("Enter Student Name for Delete : ")
if de in student:
student.pop(de)
print("----Deletion Success----")
else:
print("----Student Not Found----")
if(ch==3):
23

s=input("Enter Student Name for Search : ")


if s in student:
print("----Student Record Found----")
else:
print("----Student Record Not Found----")
if(ch==4):
if(len(student)==0):
print("----Empty----")
else:
for i,j in student.items():
print("Student Name : " ,i)
for a,b in j.items():
tot=0
for c in b:
tot=tot+c
avg=tot/3
print("Roll No : " ,a)
print("Total : " ,tot)
print("Average : ",avg)
if(avg>=60):
print("Result : 1st GRADE")
elif(avg>=50 and avg<60):
print("Result : 2nd GRADE")
elif(avg>=40 and avg<50):
print("Result : 3rd GRADE")
else:
print("Result : FAIL")
24
OUTPUT:
----STUDENT DETAILS----
1.INSERTION
2.DELETION
3.SEARCHING
4.DISPLAY
Enter Your Choice : 1
Enter Student Name : Mani
Enter Roll No : 22AUCS044
Enter Marks : 20
Enter Marks : 35
Enter Marks : 39
---- Student Info Updated----
Enter Your Choice : 2
Enter Student Name for Delete : Raj
----Student Not Found----
Enter Your Choice : 3
Enter Student Name for Search : Mani
----Student Record Found----
Enter Your Choice : 4
Student Name : Mani
Roll No : 22AUCS044
Total : 94
Average : 31.333333333333332
Result : FAIL
Enter Your Choice : 5

25
11. USER DEFINED FIBONACCI SERIES
def fib(ran):
a = -1
b=1
for i in range(ran):
c=a+b
print(c)
a=b
b=c
def fibche(check):
a = -1
b=1
c=a+b
while c <= check:
c=a+b
a=b
b=c
if c == check:
print("The Given Value is Found in this Series")
break
else:
print("The Given Value is not Found in this Series")
r = int(input("Enter the Range: "))
fib(r)
while True:
s = int(input("Enter the Searching Value: "))
fibche(s)
ch1 = input("Do You Want To Continue (Y/N) ? :")
if ch1.lower() != 'y':
break
26
OUTPUT:
Enter the Range: 10
0
1
1
2
3
5
8
13
21
34
Enter the Searching Value: 2
The Given Value is Found in this Series
Do You Want To Continue (Y/N) ? :Y
Enter the Searching Value: 5
The Given Value is Found in this Series
Do You Want To Continue (Y/N) ? :N

27
12. USER DEFINED nPr, nCr CALCULATION
def find(a):
f=1
i=1
while(i<=a):
f=i*f
i=i+1
return f
def npr(b,c):
num=find(b)
n=find(b-c)
ans=num/n
return ans
def ncr(b,c):
num1=find(b)
n1=find(b-c)
ans1=find(c)
ans2=num1/(n1*ans1)
return ans2
n=int(input("Enter Value for n: "))
r=int(input("Enter Value for r: "))
print("Answer of npr:", npr(n,r))
print("Answer of ncr:", ncr(n,r))
28

OUTPUT:
Enter Value for n: 5
Enter Value for r: 3
Answer of npr: 60.0
Answer of ncr: 10.0

29

13. USER DEFINED PALINDROME CHECK


def strpalin(s):
str1=''
for char in s:
str1=char+str1
if(s==str1):
print("The Given",s,"is Palindrome")
else:
print("The Given",s,"is Not Palindrome")
def numpalin(num):
t=num
num1=0
while(t>0):
r=t%10
num1=num1*10+r
t=t//10
if(num==num1):
print("The Given",num,"is Palindrome")
else:
print("The Given",num,"is Not Palindrome")
s=input("Enter a String : ")
strpalin(s)
n=int(input("Enter a Number : "))
numpalin(n)
30

OUTPUT:
Enter a String : malayalam
The Given malayalam is Palindrome
Enter a Number : 4321234
The Given 4321234 is Palindrome

31

14. GCD USING RECURSIVE METHOD


def gcd(a,b):
if(a==0):
return b
if(b==0):
return a
if(a==b):
return a
if(a>b):
return(gcd(a-b,b))
if(b>a):
return(gcd(a,b-a))
x=int(input("Enter 1st Number : "))
y=int(input("Enter 2nd Number : "))
res=gcd(x,y)
print("The GCD of",x,"and",y,"is : ",res)

32

OUTPUT:
Enter 1st Number : 12
Enter 2nd Number : 36
The GCD of 12 and 36 is : 12
33

15. USER DEFINED ARMSTRONG, ADAM,


PERFECT & POWER OPERATIONS
import math
print("1.ARMSTRONG NUMBER CHECK")
print("2.ADAM NUMBER CHECK")
print("3.PERFECT NUMBER CHECK")
print("4.POWER OF NUMBERS")
while(True):
ch=int(input("Enter your choice:"))
if(ch>4):
break
if(ch==1):
def armstrong(num):
s=0
n=num
while(num>0):
r=num%10
s=s+(r*r*r)
num=num//10
return n==s
num=int(input("Enter a number:"))
if(armstrong(num)):
print(num," is a armstrong number")
else:
print(num," is not a armstrong number")
if(ch==2):
def adam(num):
n=num
rev=0
re=0
n1=n*n
while(n1>0):
rem=n1%10
rev=(rev*10)+rem
n1=n1//10
sq=math.sqrt(rev)
while(sq>0):
r=sq%10
re=(re*10)+r
sq=sq//10
return re==n
num=int(input("Enter a number:"))
if(adam(num)):
print(num," is a adam number")
else:
print(num," is not a adam number")
if(ch==3):
def perfect(num):
s=0
for i in range(1,num):
if(num%i==0):
s+=i
return s==num
num=int(input("Enter a number:"))
if(perfect(num)):
print(num," is a perfect number")
else:
print(num," is not a perfect number")
if(ch==4):
def power(a,b):
r=a**b
return r
a=int(input("Enter Base:"))
b=int(input("Enter Exponent:"))
print("Power of",(a,b),":",a**b)

36

OUTPUT:
1.ARMSTRONG NUMBER CHECK
2.ADAM NUMBER CHECK
3.PERFECT NUMBER CHECK
4.POWER OF NUMBERS
Enter your choice:1
Enter a number:153
153 is a armstrong number
Enter your choice:2
Enter a number:12
12 is a adam number
Enter your choice:3
Enter a number:6
6 is a perfect number
Enter your choice:4
Enter Base:8
Enter Exponent:4
Power of (8, 4) : 4096
Enter your choice:5

37

16. SUM OF DIGITS USING RECURSIVE METHOD


def sod(n):
if(n<10):
return n
else:
r=n%10
n=n//10
return r+sod(n)
while(True):
n=int(input("Enter a Number : "))
print("Sum of",n,"is : ",sod(n))
ch=input("Do you want to continue?
(y/n): ")
if ch.lower() != "y":
break

38

OUTPUT:
Enter a Number : 106
Sum of 106 is : 7
Do you want to continue? (y/n): n
39

17. SUM OF SERIES USING RECURSIVE FUNCTION


def sos(i,n,s):
if(i>n):
return s
else:
if(i%2==0):
s-=1/i
else:
s+=1/i
return sos(i+1,n,s)
while(True):
i=int(input("Enter Start Index : "))
n=int(input("Enter End Index : "))
s=0
print("Sum of Series : ",sos(i,n,s))
ch=input("Do You Want To Continue (Y/N) ? : ")
if ch.lower()!='y':
break

40

OUTPUT:
Enter Start Index : 1
Enter End Index : 5
Sum of Series : 0.7833333333333332
Do You Want To Continue (Y/N) ? : N
41

18. PRODUCT BILLING USING TUPLE


prod=("Rice", 50, "Dhaal", 45, "Milk", 60,
"Chocolate", 20)
while(True):
l=[]
s=0
cid=int(input("Enter Customer Id : "))
l.append(cid)
while(True):
pd=input("Product Name : ")
if pd in prod:
qt=int(input("Enter Quantity : "))
i=prod.index(pd)
l.append(pd)
l.append(qt)
l.append(prod[i+1])
p=qt*prod[i+1]
l.append(p)
s+=p
else:
print("No Such Products are Available")
y=int(input("Enter 1 to Continue : "))
if(y!=1):
break
tp=tuple(l)
print("\t\t PRODUCT BILL \t\t")
print("Customer ID : ", cid)
print("Products Purchased")
print("Product Details : ", tp)
print("Total Amount : ", s)
x=int(input("Enter 1 to Continue : "))
if(x!=1):
break
43

OUTPUT:
Enter Customer Id : 55
Product Name : Rice
Enter Quantity : 2
Enter 1 to Continue : 1
Product Name : Milk
Enter Quantity : 1
Enter 1 to Continue : 1
Product Name : Chocolate
Enter Quantity : 2
Enter 1 to Continue : 1
Product Name : Dhaal
Enter Quantity : 1
Enter 1 to Continue : 0
PRODUCT BILL
Customer ID : 55
Products Purchased
Product Details : (55, 'Rice', 2, 50, 100, 'Milk', 1,
60, 60, 'Chocolate', 2, 20, 40, 'Dhaal', 1, 45, 45)
Total Amount : 245
Enter 1 to Continue : 0

44

19. SUM & PRODUCT OF NUMBERS USING TUPLE


def add(t):
l=list(t)
c=0
for i in l:
c+=i
return c
def mul(t):
l=list(t)
n=1
for i in l:
n*=i
return n
n=int(input("Enter No.of Elements : "))
m=[]
for i in range(n):
m.append(int(input("Enter Elements : ")))
tp=tuple(m)
print("Original Elements : ",tp)
print("Sum of Elements : ",add(tp))
print("Product of Elements : ",mul(tp))

45

OUTPUT:
Enter No.of Elements : 5
Enter Elements : 3
Enter Elements : 9
Enter Elements : 6
Enter Elements : 4
Enter Elements : 2
Original Elements : (3, 9, 6, 4, 2)
Sum of Elements : 24
Product of Elements : 1296
00

46

20. REVERSE THE STRING USING FILE


f=open("myfile.txt","w")
while(True):
n=input("Enter text to write in file: " )
if(n=="end"):
break
else:
f.write(n)
f.write('\n')
f.close()
with open('myfile.txt')as f:
lines=[line.rstrip()for line in f]
for l in lines:
k=l[::-1]
print(k)
47

OUTPUT:
Enter text to write in file: ih
Enter text to write in file: olleh
Enter text to write in file: uoy ees ot doog
Enter text to write in file: eyb
Enter text to write in file: end
hi
hello
good to see you
bye
48

21. COUNT CHAR & WORDS USING FILE


f=open("cfile.txt","w")
while(True):
n=input("Enter Text to Write in File : ")
if(n=="end"):
break
else:
f.write(n)
f.write('\n')

count_char=0
l=[]

with open('cfile.txt')as f:
lines=[line.rstrip()for line in f]
for line in lines:
count_char+=len(line)
words=line.split(" ")
for word in words:
if(word!='\n'):
l.append(word)
wordc=len(l)
linec=len(lines)

print("No.of Char is : ",count_char)


print("No.of Words : ",wordc)
print("No.of Lines : ",linec)

OUTPUT:
Enter Text to Write in File : hi
Enter Text to Write in File : how are you?
Enter Text to Write in File : i am fine
Enter Text to Write in File : end
No.of Char is : 23
No.of Words : 7
No.of Lines : 3
50

22. READ A FILE USING REGULAR EXPRESSION


import re
f=open('refile.txt',"w")
while(True):
n=input("Enter Text to Write in File : ")
if(n=="end"):
break
else:
f.write(n)
f.write("\n")
f.close()
count_char=0
l=[]
with open('refile.txt')as f:
lines=[line.rstrip()for line in f]
for line in lines:
m=re.findall(r'\w*l+w*',line)
print(m)
51

OUTPUT:
Enter Text to Write in File : hello
Enter Text to Write in File : lingesh
Enter Text to Write in File : old is gold
Enter Text to Write in File : end
['hell']
['l']
['ol', 'gol']
52

23. READ A HTML FILE USING REGULAR


EXPRESSION
import re
matched=re.compile('<title>').search
match=re.compile('<h1>').search
mat=re.compile('<p>').search
with open('sample.html','r')as inp:
for line in inp:
if(matched(line)):

print(line.replace("<title>","").replace("</title>",
""))
with open('sample.html','r')as inp:
for line in inp:
if(match(line)):

print(line.replace("<h1>","").replace("</h1>",""))
with open('sample.html','r')as inp:
for line in inp:
if(mat(line)):

print(line.replace("<p>","").replace("</p>",""))
53

OUTPUT:
Simple Html File

Welcome to Python Programming

In this Session We Are Going To Study About


Regular Expression
54

24. CREATING A CALCULATOR USING GUI


import tkinter as tk

def button_click(num):
current=str(entry.get())
entry.delete(0,tk.END)
entry.insert(0,current+str(num))

def button_clear():
entry.delete(0,tk.END)

def button_equal():
try:
result=eval(entry.get())
entry.delete(0,tk.END)
entry.insert(0,str(result))
except Exception:
entry.delete(0,tk.END)
entry.insert(0,"Error")

def button_backspace():
current=str(entry.get())
if len(current)>0:
entry.delete(len(current)-1,tk.END)

root=tk.Tk()
root.title("Simple Calculator")
entry=tk.Entry(root,width=16,font=('Arial',24),b
orderwidth=2,relief='solid',justify='right',bg='lig
htgray',fg='black')
entry.grid(row=0,column=0,columnspan=4,sticky
='nsew')
buttons=[
'7','8','9','/',
'4','5','6','*',
'1','2','3','-',
'0','.','=','+',
'C','~','**','%'
]
row=1
column=0
for button in buttons:
if(button=='C'):
b=tk.Button(root,text=button,width=5,height=2,
command=button_clear)
elif(button=='='):
b=tk.Button(root,text=button,width=5,height=2,
command=button_equal)
elif(button=='~'):
b=tk.Button(root,text=button,width=5,height=2,
command=button_backspace)
else:
b=tk.Button(root,text=button,width=5,height=2,
command=lambda b=button:button_click(b))
b.grid(row=row,column=column)
column+=1
if(column>3):
column=0
row+=1
root.mainloop()

OUTPUT:
57

25. CREATE A CHAT USING TCP & IP


SERVER
import socket

host = socket.gethostname()
port = 5000

server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(1)
conn, address = server_socket.accept()
print("Connection From: " + str(address))
while(True):
data = conn.recv(1024).decode()
if data.lower().strip() == 'bye':
break
print("Received From Client: " + str(data))
response = input("Server: ")
conn.send(response.encode())

conn.close()

58

CLIENT
import socket

host = socket.gethostname()
port = 5000

client_socket = socket.socket()
client_socket.connect((host, port))

message = ""
while message.lower().strip() != 'bye':
message = input("Client: ")
client_socket.send(message.encode())
data = client_socket.recv(1024).decode()
print("Received From Server: " + data)

client_socket.close()

59

26. PERFORM TASKS USING THREAD


import threading

def print_cube(num):
for i in range(1, num):
print("Cube :{}\n".format(i*i*i))

def print_square(num):
for j in range(1, num):
print("Square:{}\n".format(j*j),)

if __name__ == "__main__":
t1 = threading.Thread(target=print_square,
args=(10,))
t2 = threading.Thread(target=print_cube,
args=(5,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done")

60

OUTPUT:
Square:1
Cube :1

Square:4
Cube :8

Square:9
Cube :27
Square:16
Cube :64
Square:25
Square:36
Square:49
Square:64
Square:81

Done

61

27. PERFORM TASKS USING QUEUE


import threading
import queue
def producer(q):
for i in range(5):
q.put(i)

def consumer(q):
while(True):
data = q.get()
if data is None:
break
print("Consumed:", data)
sq = queue.Queue()
pt = threading.Thread(target=producer,
args=(sq,))
ct = threading.Thread(target=consumer,
args=(sq,))
pt.start()
ct.start()

pt.join()
sq.put(None)
ct.join()

62

OUTPUT:
Consumed: 0
Consumed: 1
Consumed: 2
Consumed: 3
Consumed: 4
63

You might also like