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

Python Lab PDF

Uploaded by

mkeerthikacse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views46 pages

Python Lab PDF

Uploaded by

mkeerthikacse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

USE LINUX SHELL COMMANDS,USE PYTHON


INTERACTIVE MODE,AND AND EDITOR
a) [Link]( )
CODE :
import os

cmd1="date"

cmd2="notepad"

[Link](cmd1)

[Link](cmd2)

OUTPUT :
2. WRITE SIMPLE PROGRAM FOR

a) Area of a geometric shape

CODE :

s=input("Input the shape and number:")

cmd,para=[Link](":")

print(f"{cmd}->{[Link]('',',')}")

if cmd == 'cir':

r = float(para)

print(f"area={r*r*3.14}")

elif cmd == 'rect':

sw, sh = [Link](" ")

print(f"area={float(sw)*float(sh)}")

elif cmd == 'trapz':

ul,bl,h =[Link](" ")

print(f"area={(float(ul)+float(bl))
*float(h)/2}")

else:

print("wrong input")
OUTPUT :

Case 1:

Case 2:

Case 3:
b) Simple interest

CODE :

def simple_interest(p,t,r):

print("The principle is ",p)

print("The time Period is ",t)

print("The rate of interest is ",r)

si=(p*t*r)/100

print("The Simple Interest is ",si)

simple_interest(8,6,8)

OUTPUT :
c) Solve the quadratic Equation

CODE :

import cmath

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

b =int(input("Enter b :"))

c =int(input("Enter c :"))

d=(b**2)-(4*a*c)

sol1 =(-[Link](d))/(2*a)

sol2 =(-b+[Link](d))/(2*a)

print("The solution are {0} and {1}".format(sol1,sol2))

OUTPUT :
d) Net salary

CODE :

print("SALARY PROGRAM")

name= str(input("Enter name of employee:"))

basic=float(input("Enter Basic Salary


:"))

da=float(basic*0.25)

hra=float(basic*0.15)

pf=float((basic+da)*0.12)

ta=float(basic*0.075)

netpay=float(basic+da+hra+ta)
3. WRITE SIMPLE PROGRAM USING CONDITIONAL
STATEMENT FOR

a) Leap Year

CODE :

year = int(input("Enter a year: "))

if (year% 400 ==0) and (year % 100 == 0):

print("{0} is a leap year".format(year))

elif (year % 4 ==0) and (year % 100 != 0):

print("{0} is a leap year".format(year))

else:

print("{0} is not a leap year".format(year))

OUTPUT :
b) Simple calculator

CODE :

def add (x,y):

return x+y

def subtract (x,y):

return x-y

def multiply (x,y):

return x*y

def divide (x,y):

return x/y

print("Select operation.")

print("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")

while True:

choice = input("Enter choice(1/2/3/4): ")

if choice in ('1', '2', '3', '4'):

try:
num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

except ValueError:

print("Invalid input. Please enter a number.")

continue

if choice == '1':

print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':

print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':

print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':

print(num1, "/", num2, "=", divide(num1, num2))

next_calculation = input("Let's do next calculation? (yes/no)")

if next_calculation == "no":

break

else:

print("Invalid Input")
OUTPUT :

Case 1:

Case 2 :
c) Grade of the total mark

CODE :

sub1=int(input("Enter marks of the first subject: "))

sub2=int(input("Enter marks of
the second subject: "))

sub3=int(input("Enter marks of the third subject: "))

sub4=int(input("Enter marks of the fourth subject: "))

sub5=int(input("Enter marks of the fifth subject: "))

avg=(sub1+sub2+sub3+sub4+sub4)/5

if(avg>=90):

print("Grade : A")

elif(avg>=80 and avg<90):

print("Grade : B")

elif(avg>=70 and avg<80):

print("Grade : C")

elif(avg>=60 and avg<70):

print("Grade : D")

else:

print("Grade : F")
OUTPUT :

Case 1:

Case 2:
4. DEVELOP THE PROGRAMS USING LOOPS AND
NESTED LOOPS FOR

a) Multiplication table

CODE :

num=int(input("Display multiplication table of ? "))

for i in range(1, 11):

print(num,'x',i,"=", num*i)

OUTPUT :
b) Sum of series

CODE :
n=int(input("Enter a number: "))

a=[]

for i in range(1,n+1):

print(i,sep=" ",end=" ")

if(i<n):

print("+",sep="",end=" ")

[Link](i)

print("=",sum(a))

OUTPUT :

Case 1:

Case 2:
c) Print patterns

CODE :

rows = int(input('Enter the number of rows


: '))

for i in range(rows+1):

for j in range(i):

print(i, end='')

print(" ")

OUTPUT :
5. DEVELOP PROGRAM USING RECURSION FOR

a) Efficient power of a number

CODE :
def power(base,exp):

if(exp==1):

return(base)

elif (exp==0):

return 1

elif (exp<0):

return(1/(base*power(base,abs(exp)
-1)))

else:

return(base*power(base,exp
-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp))
OUTPUT :

Case 1:

Case2:

Case 3:
b) Factorial

CODE :

def recur_factorial(n):

if n==1:

return n

else:

return n*recur_factorial(n-1)

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

if num<0:

print("Sorry, factorial does not exist for negative numbers")

elif num==0:

print("The factorial of 0 is 1")

else:

print("The factorial of",num,"is",recur_factorial(num))

OUTPUT :
c) Fibonacci series
CODE :
def recur_fibo(n):

if n <= 1:

return n

else:

return(recur_fibo(n-1) + recur_fibo(n
-2))

nterms =int(input("Enter A Number : "))

if nterms <= 0:

print("Plese enter a positive integer")

else:

print("Fibonacci sequence:")

for i in range(nterms):

print(recur_fibo(i))

OUTPUT :
6. DEVELOP PROGRAM USING STINGS FOR

a) Palindrome
CODE :
def ispalindrome(s):

return s==s[::-1]

s=str(input("Enter The String :"))

ans=ispalindrome(s)

if ans:

print("yes")

else:

print("No")

OUTPUT :

Case 1:

Case 2:
b) Finding substring

CODE :

my_string = "I love python."

print(my_string[2:6])

print(my_string[2:])

print(my_string[:-1])

OUTPUT :
7. DEVELOP PROGRAM USING Functions For

a) Sine Series

CODE :

import math

def sin(x, n):

sine = 0

for i in range(n):

sign = -1)**i
(

pi = 22/7

y=x*(pi / 180)

sine = sine + ((y**(2.0*i+1))/[Link](2*i+1))*sign

return sine

x =int(input( "Enter the value of x in degrees:"))

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

print(round (sin(x, n), 2) )


b) Cos Series

CODE :

import math

def cosine(x,n):

cosx=1

sign=-1

for i in range(2, n, 2):


c) Pythogorean Triplets

CODE :

limit=int(input("Enter upper limit:"))

c= 0

m=2

while(c<limit):

for n in range (1, m + 1) :

a =m*m-n*n

b =2*m*n

c =m*m+n*n

if (c>limit) :

break

if (a==0 or b ==0 or c ==0 ):

break

print(a,b,c)

m=m+1
c) Pythogorean Triplets

CODE :

limit=int(input("Enter upper limit:"))

c= 0

m=2

while(c<limit):

for n in range (1, m + 1) :

a =m*m-n*n

b =2*m*n

c =m*m+n*n

if (c>limit) :

break

if (a==0 or b ==0 or c ==0 ):

break

print(a,b,c)

m=m+1
OUTPUT :

Case 1 :

Case 2 :
8. DEVELOP PROGRAM USING LISTS AND TUPLES

a) Linear search
CODE :
def linearSearch(array, n, x):

for i in range(0, n):

if (array[i] == x):

return i

return -1

array = [2, 4, 0, 1, 9]

x=1

n = len(array)

result = linearSearch(array, n, x)

if(result ==-1):

print("Element not found")

else:

print("Element found at index: ", result)

OUTPUT :
b) Binary search
CODE :
def binarySearch(array, x, low, high):

while low <= high:

mid =low + (high- low)//2

if array[mid] == x:

return mid

elif array[mid] < x:

low = mid +1

else:

high = mid- 1

return -1

array = [3, 4, 5, 6, 7, 8, 9]

x =4

result = binarySearch(array, x,len(array)


0, -1)

if result !=-1:

print("Element is present at index " + str(result))

else:

print("Not Found")

OUTPUT :
c) Selction Sort

CODE :

def selectionsort(array,size):

for step in range(size):

min_idx=step

for i in range(step+1,size):

if array[i]<array[min_idx]:

min_idx=i

(array[step],array[min_idx])=(array[min_idx],array[step])

data=[-2,45,0,11,-9]

size=len(data)

selectionsort(data,size)

print("Sorted Array inAscending Order :")

print(data)

OUTPUT :
d) Insertion Sort

CODE :

def insertionsort(array):

for step in range(1,len(array)):

key=array[step]

j=step-1

while j>=0 and key<array[j]:

array[j+1]=array[j]

j-=1

array[j+1]=key

data=[9,5,1,4,3]

insertionsort(data)

print("sorted Array in Asscending Order :")

print(data)

OUTPUT :
e) Quick Sort

CODE :

def partition(array,low,high):

pivot=array[high]

i=low-1

for j in range(low,high):

if array[j]<=pivot:

i+=1

(array[i],array[j])=(array[j],array[i])

(array[i+1],array[high])=(array[high],array[i+1])

return i+1

def quicksort(array,low,high):

if low<high:

pi=partition(array,low,high)

quicksort(array,low,pi
-1)

quicksort(array,pi+1,high)
data=[8,7,2,1,0,9,6]

print("Unsorted Array ")

print(data)

size=len(data)

quicksort(data,0,size
-1)

print("Sorted Array in Ascending Order ")

print(data)

OUTPUT :
9. DEVELOP MATRIX MULTIPLICATION PROGRAM
USING NESTED LISTS
CODE :
X=[[12,7,3],

[4,5,6],

[7,8,9]]

Y=[[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

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

for i in range(len(X)):

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 :
[Link] SIMPLE PROGRAMS USING
DICTIONARIES
a) Frequency Histogram
CODE :
import [Link] as plt

mydict = {1: 27, 34: 1, 3: 72, 62,


4: 5: 33, 6: 36, 7: 20, 8: 12, 9: 9, 10: 6, 11: 5,
12: 8, 2: 74, 14: 4, 15: 3, 16: 1, 17: 1, 18: 1, 19: 1, 21: 1, 27: 2}

mylist = [key for key, val in [Link]() for _ in range(val)]

[Link](mylist, bins=20)

[Link]()

OUTPUT :
b) Nested Dictionary
CODE :
#How to create a nested dictionary

people = {1: {'name':'John','age':'27','sex':'Male'}

,2: {'name':'Marie','age':'22','sex':'Female'}}

print(people)

print()

#Access the elements using the [] syntax

people = {1:{'name':'John','age':'27','sex':'Male'}

,2: {'name':'Marie','age':'22', 'sex':'Female'}}

print(people[1]['name'])

print(people[1]['age'])

print(people[1]['sex'])

print()

#How to change or add elements in a nested dictionary?

people = {1: {'name


':'John','age':'27','sex':'Male'},
2: {'name':'Marie','age':'22','sex':'Female'}}

people[3] = {}

people[3]['name'] = 'Luna'

people[3]['age'] = '24'

people[3]['sex'] = 'Female'

people[3]['married'] = 'No'

print(people[3])

print()

#Add anotherdictionary to the nested dictionary

people = {1: {'name':'John','age':'27','sex':'Male'},

2: {'name':'Marie','age':'22','sex':'Female'},

3: {'name':'Luna','age':'24','sex':'Female', 'married': 'No'}}

people[4] = {'name': 'Peter', 'age'


: '29', 'sex': 'Male', 'married': 'Yes'}

print(people[4])

print()

#How to delete elements from a nested dictionary?

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},

2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},


3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},

4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}

del people[3]['married']

del people[4]['married']

print(people[3])

print(people[4])

print()

OUTPUT :
11. DEVELOP PROGRAM USING FILES

a) Read Files
CODE :
a=str(input("Enter the name of the file with .txt extension:"))

try:

file=open(a,'r')

line=[Link]()

while(line!=""):

print(line)

line=[Link]()

[Link]()

exceptFileNotFoundError:

print("There is No such file to Read !")

OUTPUT :

Case 1 :

Case 2 :
b) Write Files

CODE :

file1=open('[Link]', 'w')

L = ["This is Delhi
\ n", "This is Paris
\ n", "This is London
\ n"]

s = "Hello\n"

[Link](s)

[Link](L)

[Link]()

file1=open('[Link]', 'r')

print([Link]())

[Link]()

OUTPUT :
[Link] PYTHON PROGRAMS TO PERFORM
ANY TASK BY READING ARUGMENTS FROM
COMMAND LINE

CODE :
import sys

n=len([Link])

print("Total argumentspassed:", n)

print("\ nName of Python script:", [Link][0])

print("\ nArguments passed:", end = " ")

for i in range(1, n):

print([Link][i], end = "")

Sum = 0

for i in range(1, n):

sum+=int([Link][i])

print("\ n\ nResult :",Sum)

OUTPUT :
x ={"geeks" "for", "geeks"}

print("Typeof x : ",type(x))

x = frozenset({"geeks", "for", "geeks"})

print("Type of x : ",type(x))

x = True

print("Type of x: ", type(x))

x = b"Geeks"

print("Type of x: ", type(x))

x = bytearray(4)

print("Type of x: ", type(x))

x = memoryview(bytes(6))

print("Typeof x: ", type(x))

x = None

You might also like