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

Python Lab Programs(2022-23)

The document contains various Python programs covering topics such as sum of digits, addition of positive numbers, finding the largest number, checking for palindromes, generating patterns, and performing matrix operations. It also includes implementations for searching algorithms, factorial calculation, Fibonacci series, prime number checking, and basic file operations. Additionally, it demonstrates concepts of inheritance and polymorphism in object-oriented programming.

Uploaded by

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

Python Lab Programs(2022-23)

The document contains various Python programs covering topics such as sum of digits, addition of positive numbers, finding the largest number, checking for palindromes, generating patterns, and performing matrix operations. It also includes implementations for searching algorithms, factorial calculation, Fibonacci series, prime number checking, and basic file operations. Additionally, it demonstrates concepts of inheritance and polymorphism in object-oriented programming.

Uploaded by

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

1.

# SUM OF DIGITS

n=int(input("Enter the value of n:"))


val=n
total=0
while(n>0):
digit=n%10
total=total+digit
n=n//10
print("The Sum of given number is...:",total)

INPUT
Enter the value of n : 12345

OUTPUT
The Sum of given number is...: 15
2. # ADDITION OF POSITIVE NUMBERS
a=[]
n=int(input("Enter the Number of Elements:"))
while n>=0:
x=int(input('Enter the Number:'))
if x >0 :
a.append(x)
if x == -1:
print(sum(a))
break

INPUT :
Enter the Number of Elements: 4

Enter the Number: 3


Enter the Number: 2
Enter the Number: 4
Enter the Number: 5
Enter the Number: -1

OUTPUT :
14
3. #LARGEST THREE INTEGERS USING IF-ELSE CONDITIONAL OPERATOR
a=int(input("Enter the First Number:"))
b=int(input("Enter the Second Number:"))
c=int(input("Enter the Third Number:"))
max= (a if(a>c)else c) if (a>b) else ( b if (b>c) else c)
print( "Largest number is:" ,max )

INPUT:
Enter the First Number: 45
Enter the Second Number: 65
Enter the Third Number: 79

OUTPUT :
('Largest number is: ', 79)
4. # PALINDROME OR NOT
n=int(input("Enter the value of n:"))
g=n
rev=0
while (n>0):
dig=n%10
rev = rev*10+dig
n=n//10
if(g==rev):
print("Given Number is Palindrome")
else:
print("Given Number is not a Palindrome")

INPUT /OUTPUT:
Enter the value of n: 456
Given Number is not a Palindrome

Enter the value of n: 121


Given Number is Palindrome
5. #INVERTED STAR PATTERN

n=int(input("Enter the Number of rows:"))


for i in range(n,0,-1):
print((n-i)*''+i *'*')

INPUT/OUTPUT :

Enter the Number of rows: 15


***************
**************
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*
6. THREE DIGIT NUMBER WITH ALL ITS COMBINATION

a=int(input("Enter the First Number..."))


b=int(input("Enter the Second Number..."))
c=int(input("Enter the Third Number..."))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])

INPUT :
Enter the First Number...8
Enter the Second Number...5
Enter the Third Number...4

OUTPUT :
854
845
584
548
485
458
7. # CHECK THE GIVEN NUMBER WHETHER IT IS POSITIVE, NEGATIVE AND ZERO

num=int(input("Enter the Value..."))


if(num>0):
print("Given number is Positive")
elif(num<0):
print("Given number is Negative")
else:
print("Given Number is Zero")

INPUT/OUTPUT :
Enter the Value... 67
Given number is Positive

Enter the Value... 0


Given Number is Zero

Enter the Value... -8


Given number is Negative
8. # a) DISPLAY YEAR
import calendar
year=int(input("Enter the year..."))
calendar.prcal(year)

OUTPUT :
8. # b) DISPLAY MONTH

import calendar
year1=int(input("Enter the year..."))
month1 = int(input("Enter the Month..."))
print(calendar.month(year1,month1))

OUTPUT :
Enter the year...2023
Enter the Month...1

Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
9. # GCD OF TWO NUMBERS

def GCD(x,y):
r=x%y
if(r==0):
return y
else:
return GCD(y,r)
n=int(input("Enter the First Number:"))
m=int(input("Enter the Second Number:"))
print("The GCD of two numbers is :",GCD(n,m))

INPUT :
Enter the First Number: 27
Enter the Second Number: 18

OUTPUT :
('The GCD of two numbers is :', 9)
10. #FACTORIAL PROGRAM USING RECURSION

def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
n=int(input("Enter the number:"))
if n < 0:
print("Factorial does not exist for negative numbers")
elif n==0:
print("The factorial of 0 is 1")
else:
print("The factorial is ",factorial(n))

INPUT :
Enter the number: 5

OUTPUT :
('The factorial is ', 120)
11. # FIBONACCI SERIES USING RECURSION

def fibo(n):
if n <= 1:
return n
else:
return fibo(n-1) + fibo(n-2)
n=int(input("Enter the number of terms:"))
print("The fibonacci sequence is")
for i in range(n):
print(fibo(i))

INPUT :
Enter the number of terms: 8

OUTPUT :
The fibonacci sequence is
0
1
1
2
3
5
8
13
12. # PRIME NUMBER OR NOT USING RECURSION

def isprime (n,i=2):


if(n <= 2) :
return True if (n==2) else False
if (n % i == 0):
return False
if (i * i> n):
return True
return isprime(n,i+1)
n=int(input("Enter the Number:"))
if (isprime(n)):
print("The Number is a prime")
else:
print("The Number is not a prime")

INPUT/OUTPUT :
Enter the Number: 13
The Number is a prime

Enter the Number: 12


The Number is not a prime
13. SORT THE NUMBERS IN ASCENDING ORDER

temp = 0
n=int(input("Enter the Number of Terms:"))
a=[]
for i in range(0,n):
element = int(input("Enter the Numbers one by one\n"))
a.append(element)

#Sort the array in Ascending order

for i in range(0,n):
for j in range (i+1,n):
if (a[i] > a[j]):
temp = a[i]
a[i] = a[j]
a[j] = temp

#Displaying the elments


print("The Ascending order is:\n")
for i in range(0,n):
print(a[i])
INPUT :
Enter the Number of Terms: 5
Enter the Numbers one by one
67
Enter the Numbers one by one
45
Enter the Numbers one by one
23
Enter the Numbers one by one
12
Enter the Numbers one by one
89

OUTPUT :
The Ascending order is:

12
23
45
67
89
14. #PRODUCT OF TWO MATRICES

X = [[1,2,3],
[4,5,6],
[7,8,9]]
#3*3 matrix
Y = [[1,2,1],
[2,4,6],
[7,2,5]]
#Result is 3*3

result = [[0,0,0],
[0,0,0],
[0,0,0,]]
#Iterate through rows of X
for i in range(len(X)):
#Iterate through columns of Y
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

OUTPUT :
[26, 16, 28]
[56, 40, 64]
[86, 64, 100]
15. a) MATRIX ADDITION
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

OUTPUT :

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]
15. b) MATRIX SUBTRACTION
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]

for r in result:
print(r)

OUTPUT:

[-8, -6, -4]


[-2, 0, 2]
[4, 6, 8]
16. LINEAR SEARCH
def linearsearch(list1,n,key):
#Searching list1 sequentially
for i in range(0,n):
if(list1[i]==key):
return i
return -1

list1 = [1,3,5,4,7,9]
print (list1)
key=int(input("Enter the key value\n"))
n=len(list1)
res = linearsearch(list1,n,key)
if(res==-1):
print("Element not found")
else:
print("Element found at index",res)

INPUT/OUTPUT :
[1, 3, 5, 4, 7, 9]
Enter the key value
4
('Element found at index', 3)
[1, 3, 5, 4, 7, 9]
Enter the key value
10
Element not found
17. BINARY SEARCH
def binsearch(a,x):
low = 0
high = len(a)-1
mid = 0
while low <= high:
mid = (high + low) // 2
if a[mid] < x:
low = mid +1
elif a[mid] > x:
high = mid - 1
else:
return mid
return -1
#a = [2,3,4,10,40]
#print("The Elements are",a)
n=int(input("Enter the number of elements\n"))
a = []
for i in range(0,n):
element=int(input("Enter the elements one by one"))
a.append(element)
x=int(input("Enter the search element\n"))
result = binsearch(a,x)
if (result != -1):
print("Element is present at index",str(result))
else:
print("Element is not present in array")
OUTPUT :

Enter the number of elements


5
Enter the elements one by one 1
Enter the elements one by one 6
Enter the elements one by one 8
Enter the elements one by one 9
Enter the elements one by one 10
Enter the search element
10
('Element is present at index', '4')

Enter the search element


12
Element is not present in array
18. # IMPLEMENTATION OF CALCULATOR
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
return a/b

print("Select the Choice \n"\


"1.Add\n"\
"2.Subtract\n"\
"3.Multiply\n"\
"4.Divide\n")

select=int(input("Select operations from 1,2,3,4 :"))

a1=int(input("Enter the First Number"))


b1=int(input("Enter the second Number"))

if select==1:
print(a1 , "+", b1 , "=" , add(a1,b1))
elif select==2:
print(a1 , "-", b1 , "=" ,subtract(a1,b1))
elif select==3:
print(a1 , "*", b1 , "=" ,multiply(a1,b1))
elif select==4:
print(a1 , "/", b1 , "=" ,divide(a1,b1))
else :
print("Invalid Input")

INPUT/OUTPUT :
Select the Choice
1.Add
2.Subtract
3.Multiply
4.Divide

Select operations from 1,2,3,4 :1


Enter the First Number 45
Enter the second Number 67
(45, '+', 67, '=', 112)

Select the Choice


1.Add
2.Subtract
3.Multiply
4.Divide

Select operations from 1,2,3,4 :3


Enter the First Number 12
Enter the second Number 12
(12, '*', 12, '=', 144)
19. #SUM OF THE ARRAY ELEMENTS
def sumarray(a):
sum = 0
for i in a:
sum = sum + i
return(sum)
a=[]

n1=int(input("Enter the number of terms\n"))


a = []

for i in range (0,n1):


element = int(input("Enter the elment one by one...."))
a.append(element)
n = len(a)
ans = sumarray(a)
print("Sum of the array is",ans)

INPUT/OUTPUT :
Enter the number of terms
5
Enter the elment one by one....1
Enter the elment one by one....2
Enter the elment one by one....3
Enter the elment one by one....4
Enter the elment one by one....5
('Sum of the array is', 15)
20. # COUNT THE NUMBER OF WORDS USING FILE

#COUNT THE NUMBER OF WORDS

file = open("F:\data.txt", "rt")

data = file.read()

words = data.split()

print("Number of Words in text file",len(words))

OUTPUT :
Data.txt – “India is My Country”

('Number of Words in text file', 4)


21. # COPY A FILE

#COPY A FILE

#Open both files

with open('F:\data.txt','r') as firstfile ,open('F:\data1.txt','a') as secondfile :

#Read content from first file

for line in firstfile:

#Append content to second file

secondfile.write(line)

OUTPUT :
data.txt - : India is My Country

data1.txt - : India is MY Country


22. # HYBRID INHERITANCE

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

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

OUTPUT :
This function is in school.
This function is in student 1.
23. # POLYMORPHISM WITH A FUNCTION
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")

def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

OUTPUT :

New Delhi is the capital of India.


Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
24.# PASSWORD CHECKING
import re
password = "R@m@_f0rtu9e$"
flag = 0
while True:
if (len(password)<8):
flag = -1
break
elif not re.search("[a-z]",password):
flag = -1
break
elif not re.search("[A-z]",password):
flag = -1
break
elif not re.search("[0-9]",password):
flag = -1
break
elif not re.search("[_@$]",password):
flag = -1
break
elifre.search("[\s]",password):
flag = -1
break
else :
flag = 0
print("Valid Password")
break
if flag == -1:
print("Not a Valid Password")

OUTPUT :

Valid Password
25.#Various Pandas Library operations in python.

import pandas as pd
import numpy as np
def series_operations():
f_dict = {'apples':500,'kiwi':200,'oranges':100,'cherries':600,'orange':100}
se = pd.Series(f_dict)
print('Series Items : \n',se)
print("-------------------------------------------")
se.index.name="Fruits"
print('Series after assigned index name : \n',se)
print("-------------------------------------------")
print("Values in Series : ",se.values)
print("-------------------------------------------")
print("Index of Series : ",se.index)
print("-------------------------------------------")
print("Price greater than 300 : \n",se[se > 300],"\t")
print("-------------------------------------------")
print("Get unique values with frequency : \n",se.value_counts())
print("-------------------------------------------")
if 'kiwi' in se:
print("Price of kiwi : ",se['kiwi'])
print("-------------------------------------------")
print("Check for null : \n",se.isnull())
print("-------------------------------------------")
def dataframe_operations():
df=pd.DataFrame(np.arange(16).reshape((4,4)),
index=['red','blue','yellow','white'],
columns=['ball','pen','pencil','paper'])
print(df)
print("Shape of dataframe : ",df.shape)
print("Size of dataframe : ",df.size)
print("Dropped year column : \n",df.drop('paper',axis=1))
print(df.describe())
series_operations()
dataframe_operations()

OUTPUT :
Series Items :
apples 500
kiwi 200
oranges 100
cherries 600
orange 100
dtype: int64
-------------------------------------------
Series after assigned index name :
Fruits
apples 500
kiwi 200
oranges 100
cherries 600
orange 100
dtype: int64
-------------------------------------------
Values in Series : [500 200 100 600 100]
-------------------------------------------
Index of Series : Index(['apples', 'kiwi', 'oranges', 'cherries', 'orange'], dtype='object',
name='Fruits')
-------------------------------------------
Price greater than 300 :
Fruits
apples 500
cherries 600
dtype: int64
-------------------------------------------
Get unique values with frequency :
100 2
500 1
200 1
600 1
dtype: int64
-------------------------------------------
Price of kiwi : 200
-------------------------------------------
Check for null :
Fruits
apples False
kiwi False
oranges False
cherries False
orange False
dtype: bool
-------------------------------------------
ball pen pencil paper
red 0 1 2 3
blue 4 5 6 7
yellow 8 9 10 11
white 12 13 14 15
Shape of dataframe : (4, 4)
Size of dataframe : 16
Dropped year column :
ball pen pencil
red 0 1 2
blue 4 5 6
yellow 8 9 10
white 12 13 14

ball pen pencil paper


count 4.000000 4.000000 4.000000 4.000000
mean 6.000000 7.000000 8.000000 9.000000
std 5.163978 5.163978 5.163978 5.163978
min 0.000000 1.000000 2.000000 3.000000
25% 3.000000 4.000000 5.000000 6.000000
50% 6.000000 7.000000 8.000000 9.000000
75% 9.000000 10.000000 11.000000 12.000000
max 12.000000 13.000000 14.000000 15.000000
26. # Plot various types of charts to visualize data using matplotlib library
in Python.

import matplotlib.pyplot as plt

import pandas as pd

labels=['Nokia','Samsung','Apple','Motorola']

values=[10,30,45,20]

colors=['yellow','green','red','blue']

explode=[0.3,0,0,0]

plt.title('A pie chart for mobile brand')

plt.pie(values,labels=labels,colors=colors,explode=explode,startangle=180)

data={'Product1':[1,3,4,3,5],

'Product2':[2,4,5,2,4],

'Product3':[3,2,3,1,3]}

# Plot using data frame

df=pd.DataFrame(data)

df.plot(kind='bar')

df.plot(kind='bar',stacked=True)

plt.show()
OUTPUT :

You might also like