Python Lab Programs(2022-23)
Python Lab Programs(2022-23)
# SUM OF DIGITS
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
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
INPUT/OUTPUT :
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
INPUT/OUTPUT :
Enter the Value... 67
Given number is Positive
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
INPUT/OUTPUT :
Enter the Number: 13
The Number is a prime
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)
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
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]]
for r in result:
print(r)
OUTPUT :
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
OUTPUT:
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 :
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
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
data = file.read()
words = data.split()
OUTPUT :
Data.txt – “India is My Country”
#COPY A FILE
secondfile.write(line)
OUTPUT :
data.txt - : India is My Country
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.")
# 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 :
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
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.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]}
df=pd.DataFrame(data)
df.plot(kind='bar')
df.plot(kind='bar',stacked=True)
plt.show()
OUTPUT :