KEMBAR78
Phy Pgms Alter | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
45 views44 pages

Phy Pgms Alter

Uploaded by

tajon71673
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)
45 views44 pages

Phy Pgms Alter

Uploaded by

tajon71673
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
You are on page 1/ 44

Ex.no:1.

A ELECTRICITY BILLING Date:

AIM: To make a Flowchart for Electricity Billing

ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the required variables
Step 3: Get an input
Step 4: Calculate the given input
Step 5: Print the output
Step 6: Stop
FLOW CHART:

1
CODE:
units=int(input("Number of unit consumed: "))
if(units>0 and units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units>100 and units<=200):
payAmount= (100*1.5) +(units-100) *2.5
fixedcharge=50.00
elif(units>200 and units<=300):
payAmount=(100*1.5) +(200-100)*2.5+(units-200)*4
fixedcharge=50.00
elif(units>300):
payAmount=2500;
fixedcharge=75.00
else:
payAmount=0;
fixedcharge=0;

2
Total= payAmount+fixedcharge
print("\nElecticity bill pay=%.2f: " %Total);

OUTPUT:

Number of units consumed: 700


Electricity bill pay = 2575.00

RESULT:
Thus, the python program was implemented and output was verified successfully.

Ex.no:1.B SINE SERIES Date:

AIM:
Write a program to find Sine Series.

ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the required variables
Step 3: Get an input
Step 4: Calculate the square root
Step 5: Print the output
Step 6: Stop

3
FLOW CHART:

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))/math.factorial(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))

OUTPUT :
Enter the value of x in degrees:3

4
Enter the number of terms:4
0.05

RESULT:
Thus, the python program was implemented and output was verified successfully.

def main():
# Define available items and their prices
items = {
'apple': 0.50,
'banana': 0.30,
'milk': 1.20,
'bread': 2.00
}

# Initialize cart and total amount


cart = {}
total_amount = 0.0

print("Welcome to the Retail Shop!")

while True:
# Input item name
item_name = input("\nEnter item name (or 'done' to finish): ").lower()

5
if item_name == 'done':
break

# Check if item exists in the store


if item_name not in items:
print("Item not found. Please enter a valid item.")
continue

try:
# Input quantity
quantity = int(input(f"Enter quantity for {item_name}: "))
except ValueError:
print("Invalid quantity. Please enter a number.")
continue

if quantity <= 0:
print("Quantity should be positive.")
continue

# Add item to cart and calculate cost


if item_name in cart:
cart[item_name] += quantity
else:
cart[item_name] = quantity

total_amount += items[item_name] * quantity

if total_amount > 0:
# Print receipt
print("\n--- Receipt ---")
for item, quantity in cart.items():
item_cost = items[item] * quantity
print(f"{item.capitalize()}: {quantity} x ${items[item]:.2f} = ${item_cost:.2f}")

print(f"Total Amount: ${total_amount:.2f}")


else:
print("No items were added to the cart.")

if __name__ == "__main__":
main()

6
Ex.no:2.A EXCHANGE THE VALUE OF TWO VARIABLES Date:

AIM:

To write a python program to exchange the values of two variables.

ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the two variables
Step 3: Assign the variables
Step 4: Swap the variables
Step 5: Print the output
Step 6: Stop

CODE:

a=input("enter the a value:")


b=input("enter the b value:")
print("The values of a and b: Before Swapping:",a,b)
a,b=b,a
print("The values of a and b: After Swapping:",a,b)

OUTPUT:

enter the a value: 2


enter the b value: 3
The values of a and b: Before Swapping: 2 3
The values of a and b: After Swapping: 3 2

RESULT:
Thus, the python program was implemented and output was verified successfully.

7
Ex.no:2B CIRCULATE THE VALUES OF N VARIABLES Date:

AIM:
Write a python program to circulate the values of n variables
ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the List with values
Step 3: Initialize the variable
Step 4: Print the output
Step 5: Stop

CODE:

List = [10,20,30,40,50]
n=2
List [2:] +List [:2]

OUTPUT:
[30, 40, 50, 10, 20]

RESULT:
Thus, the python program was implemented and output was verified successfully

8
Ex.no: 2.C DISTANCE BETWEEN TWO POINTS Date:

AIM:

Write a python program to find distance between two points


ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program
CODE:

p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(“ The distance between p1 and p2 is”, distance)

OUTPUT:
The distance between p1 and p2 is : 6.324555320336759

RESULT:
Thus, the python program was implemented and output was verified successfully

9
Ex.no:3A NUMBER SERIES: TO FIND SUM OF N NUMBERS Date:

AIM:

Write a python program to find sum of N number


ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
n = int(input("Enter number:"))
sum = 0
for num in range(n+1):
sum = sum + num
print("Sum of first ", n, "numbers is: ", sum)

OUTPUT:
Enter number: 5
Sum of first 5 numbers is: 15

RESULT:
Thus, the python program was implemented and output was verified successfully.

Ex.no:3.B NUMBER PATTERN Date:

10
AIM:

Write a python program to print number pattern

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print("")

OUTPUT:

1
22
333
4444
55555
RESULT:
Thus, the python program was implemented and output was verified successfully

11
Ex.no:3.C PYRAMID PATTERN Date:

AIM:
Write a python program to create a pyramid pattern
ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
row = 5
a=0
for i in range(row, 0, -1):
a += 1
for j in range(1, i + 1):
print(a, end=' ')
print('\r')

OUTPUT:
11111
2222
333
44
5

RESULT:

Thus, the python program was implemented and output was verified successfully.

12
Ex.no:4.A OPERATIONS OF LIST: COMPONENTS OF A CAR Date:

AIM:

Write a python program for operations of list: components of a car

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
iList = ['wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel',
'fuel_tank', 'seat', 'number_plate']

print('iList: ',iList)

print('first element: ',iList[0])

print('fourth element: ',iList[3])

print('iList elements from 0 to 4 index:',iList[0: 5])

print('3rd or -7th element:',iList[-7])

iList.append('wheel_cover')

print('iList after append():',iList)

print('index of door: ',iList.index('door'))

iList.sort()

print('after sorting: ', iList)

13
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);

iList.remove('engine')

print('after removing \engine: ',iList)

iList.insert(2, 'car_key')

print('after insert: ', iList)

print('number of occurences of seat: ', iList.count('seat'))

iList.extend(['front_mirror','rear_mirror' ])

print('after extending:', iList)

iList.reverse()

print('after reversing:', iList)

Output:
iList: ['wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel',
'fuel_tank', 'seat', 'number_plate']

first element: wheel

fourth element: tail_lamp

iList elements from 0 to 4 index: ['wheel', 'door', 'head_lamp', 'tail_lamp', 'engine']

3rd or -7th element: tail_lamp

iList after append(): ['wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat',


'steering_wheel', 'fuel_tank', 'seat', 'number_plate', 'wheel_cover']

index of door: 1

after sorting: ['door', 'engine', 'fuel_tank', 'head_lamp', 'number_plate', 'seat', 'seat',


'steering_wheel', 'tail_lamp', 'wheel', 'wheel_cover']

Popped elements is: wheel_cover

14
after pop(): ['door', 'engine', 'fuel_tank', 'head_lamp', 'number_plate', 'seat', 'seat',
'steering_wheel', 'tail_lamp', 'wheel']

after removing \engine: ['door', 'fuel_tank', 'head_lamp', 'number_plate', 'seat', 'seat',


'steering_wheel', 'tail_lamp', 'wheel']

after insert: ['door', 'fuel_tank', 'car_key', 'head_lamp', 'number_plate', 'seat', 'seat',


'steering_wheel', 'tail_lamp', 'wheel']

number of occurences of seat: 2

after extending: ['door', 'fuel_tank', 'car_key', 'head_lamp', 'number_plate', 'seat', 'seat',


'steering_wheel', 'tail_lamp', 'wheel', 'front_mirror', 'rear_mirror']

after reversing: ['rear_mirror', 'front_mirror', 'wheel', 'tail_lamp', 'steering_wheel', 'seat',


'seat', 'number_plate', 'head_lamp', 'car_key', 'fuel_tank', 'door']

RESULT:
Thus, the python program was implemented and output was verified successfully.

15
Ex.no:4.B OPERATIONS OF TUPLES: COMPONENTS OF A CAR Date:

AIM:

To write a python program for operations of tuples: components of a car

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
iTuple = ('wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel',
'fuel_tank', 'seat', 'number_plate')

print(iTuple)

print(iTuple.count('seat'))

print( iTuple.index('seat'))

uTuple=('front_mirror','real_mirror')

nTuple=iTuple+uTuple

print(nTuple)

print(min(nTuple))

print(max(nTuple))

print(sorted(nTuple))

print(nTuple[::-1])

16
print(nTuple[0])

print(nTuple[1:4])

if 'door' in nTuple
print('yes item exists')

else:
print('no item not exists')

iList=list(nTuple)

iList[1]='car_key'

nTuple=tuple(iList)

print(nTuple)

iList=list(nTuple)

iList.remove('engine')

nTuple=tuple(iList)

print(nTuple)

OUTPUT:
('wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank',
'seat', 'number_plate')

5
('wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank',
'seat', 'number_plate', 'front_mirror', 'real_mirror')

Door

Wheel

17
['door', 'engine', 'front_mirror', 'fuel_tank', 'head_lamp', 'number_plate', 'real_mirror',
'seat', 'seat', 'steering_wheel', 'tail_lamp', 'wheel']

('real_mirror', 'front_mirror', 'number_plate', 'seat', 'fuel_tank', 'steering_wheel', 'seat',


'engine', 'tail_lamp', 'head_lamp', 'door', 'wheel')

Wheel

('door', 'head_lamp', 'tail_lamp')

yes item exists

('wheel', 'car_key', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank',


'seat', 'number_plate', 'front_mirror', 'real_mirror')

('wheel', 'car_key', 'head_lamp', 'tail_lamp', 'seat', 'steering_wheel', 'fuel_tank', 'seat',


'number_plate', 'front_mirror', 'real_mirror')

RESULT:
Thus, the python program was implemented and output was verified successfully.

18
Ex.no:5.A ELEMENTS OF CIVIL STRUCTURE: OPERATIONS OF SETS Date:

AIM:

To write a python program for elements of civil structure: operations of sets

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
set1={'foundation','walls','doors'}
set2={'roofs','steps','stairs','lifts','doors'}

for x in set1,set2:
print(x)
print('roofs' in set2)

set1.add('pillar')

print(set1)

set2.intersection_update(set1)

print(set2)

set1.update(set2)

print(set1)

set1.remove('pillar')

print(set1)

19
set1.pop()

print(set1)

OUTPUT:
{'walls', 'foundation', 'doors'}
{'stairs', 'steps', 'roofs', 'doors', 'lifts'}
True
{'walls', 'foundation', 'pillar', 'doors'}
{'doors'}
{'walls', 'pillar', 'foundation', 'doors'}
{'walls', 'foundation', 'doors'}
{'foundation', 'doors'}

RESULT:
Thus, the python program was implemented and output was verified successfully.

20
Ex.no:5.B COMPONENTS OF AUTOMOBILE: OPERATIONS OF DICTIONARIES Date:

AIM:
To write a python program for components of automobile: operations of dictionaries

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
dict1={"brand": "Ford","model": "Mustang","year": 1964}

print(dict1)

x=dict1.get('brand')

print(x)

print(dict1['model'])

print(dict1.keys())

print(dict1.items())

dict1['color']='white'

print(dict1)

if 'model' in dict1:
print('yes it is one of the key in dictionary')

dict1['year'] = '2020'

print(dict1)

21
dict1.popitem

print(dict1)

dict1.pop('model')

print(dict1)

dict2=dict1.copy()

print(dict2)

child1 = {"brand" : "Ford","year" : 2012}

child2 = {"color" : "Meroon", "capacity" :"four-seated"}

dict3 = {"child1" : child1, "child2" : child2}

print(dict3)

OUTPUT:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Ford
Mustang
dict_keys(['brand', 'model', 'year'])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white'}
yes it is one of the key in dictionary
{'brand': 'Ford', 'model': 'Mustang', 'year': '2020', 'color': 'white'}
{'brand': 'Ford', 'model': 'Mustang', 'year': '2020'}
{'brand': 'Ford', 'year': '2020'}
{'brand': 'Ford', 'year': '2020'}
{'child1': {'brand': 'Ford', 'year': 2012}, 'child2': {'color': 'Meroon', 'capacity': 'four-
seated'}}

RESULT:
Thus, the python program was implemented and output was verified successfully.

22
Ex.no:6.A FACTORIAL OF N NUMBERS Date:

AIM:
To write a python program to find factorial of n numbers
ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

n=int(input("Input a number to compute the factiorial : "))


print(“The factorial is:”,factorial(n))

OUTPUT:

Input a number to compute the factiorial : 5


The factorial is :12

RESULT:
Thus, the python program was implemented and output was verified successfully.

23
Ex.no:6.B SWAPPING OF TWO VALUES Date:

AIM:

To write a python program to perform swapping of two values


ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
def swap(a,b):
a,b=b,a
print("The values of a and b: After Swapping:",a,b)

a=input("enter the a value:")


b=input("enter the b value:")

print("The values of a and b: Before Swapping:",a,b)


swap(a,b)

OUTPUT:
enter the a value: 2
enter the b value: 3
The values of a and b: Before Swapping: 2 3
The values of a and b: After Swapping: 3 2

RESULT:
Thus, the python program was implemented and output was verified successfully.

24
Ex.no:6.C LARGEST TWO NUMBERS OF LIST Date:

AIM:

To write a python program to Print largest two numbers of list


ALGORITHM:

Step 1: Start the program


Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:
integers = [1, 16, 3, 39, 26, 4, 8, 16]
copy_of_integers = integers[:]
first_largest_integer = max(copy_of_integers)
copy_of_integers.remove(first_largest_integer)
second_largest_integer = max(copy_of_integers)
print("Two largest integers in the list are:",first_largest_integer,second_largest_integer)

OUTPUT:

Two largest integers in the list are: 39 26

RESULT:
Thus, the python program was implemented and output was verified successfully.

25
Ex.no:6.D AREA OF SHAPE Date:

AIM:

To write a python program to print area of shape

ALGORITHM:
Step 1: Start the program
Step 2: Declare necessary variable
Step 3: Write the process to get desired output
Step 4: print the result
Step 5: Stop the program

CODE:

len=int(input("Enter the Lenth of rectangle:"))


bre=int(input("Enter the Breadth of rectangle:"))
r=int(input("Enter the Redius of Circle:"))
area1=len*bre
perimeter=2*(len+bre)
area2=3.14*r*r
circum=2*3.14*r
print("Area of Rectangle =",area1)
print("Perimeter of Rectangle =",perimeter)
print("Area of Circle =",area2)
print("Circum of Circle =",circum)
OUTPUT:

Enter the Lenth of rectangle:20


Enter the Breadth of rectangle:50
Enter the Redius of Circle:15
Area of Rectangle = 1000

26
Perimeter of Rectangle = 140
Area of Circle = 706.5
Circum of Circle = 94.2

RESULT:
Thus, the python program was implemented and output was verified successfully.

27
EX.NO:7.A REVERSE OF GIVEN STRING Date:

AIM:

To write a python program to check for palindrome.

ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
txt = "Hello World"
print(“Reverse of the string:”, txt[::-1])

OUTPUT:
Reverse of the string: dlroW olleH

RESULT:

Thus, the python program to perform word count in a file is executed successfully.

28
EX.NO:7.B CHECK FOR PALINDROME Date:

AIM:

To write a python program to check for palindrome.

ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
s = "malayalam"
if s==s[::-1]:
print("The given string",s,"is palindrome")
else:
print("The given string",s,"is not palindrome")

OUTPUT:

The given string malayalam is palindrome

RESULT:

Thus, the python program to perform word count in a file is executed successfully.

29
EX.NO:7.C CHARACTER COUNT Date:

AIM:

To write a python program to count characters.

ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
str1 = "Hello World"
str_count1 = str1.count('o')
print("The count of 'o' is", str_count1)
str_count2 = str1.count('o', 0,len(str1))
print("The count of 'o' using start/end is", str_count2)

OUTPUT:
The count of 'o' is 2
The count of 'o' using start/end is 2

RESULT:
Thus, the python program to perform word count in a file is executed successfully.

30
EX.NO:7.D REPLACING CHARACTERS Date:

AIM:

To write a python program to replace characters.


ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
string = "Dhoni Sachin Kohli Sachin Sachin"
print(string.replace("Sachin", "Dhoni"))
print(string.replace("Sachin", "Dhoni", 2))

OUTPUT:
Dhoni Dhoni Kohli Dhoni Dhoni
Dhoni Dhoni Kohli Dhoni Sachin

RESULT:
Thus, the python program to perform word count in a file is executed successfully.

31
Ex.no:8.A DATA ANALYSIS USING PANDAS Date:

AIM:

To write a python program to perform data analysis using panda .


ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
import pandas as pd
import matplotlib.pyplot as plt
data = {"pass%": [90, 70, 50], "students_count": [20, 50, 30]}
df = pd.DataFrame(data, index = ["Test_1", "Test_2", "Test_3"])
print(df)
df.plot(kind = 'bar', x = 'pass%', y = 'students_count')
plt.show()

OUTPUT:
pass% students_count
Test_1 90 20
Test_2 70 50
Test_3 50 30

32
RESULT:
Thus, the python program to perform word count in a file is executed successfully.

33
Ex.no:8.B SEARCHING AND SORTING OF ARRAY USING NUMPY Date:

AIM:

To write a python program to search and sort an array using numpy.


ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
import numpy as np
arr = np.array([40, 20, 30, 10])
print(arr)
print(arr[1:3])
x=np.where(arr==10)
print(x)
print(np.sort(arr))

OUTPUT:
[40 20 30 10]
[20 30]
(array([3]),)
[10 20 30 40]

RESULT:
Thus, the python program to perform word count in a file is executed successfully.

34
Ex.no:8.C BAR CHART USING MATPLOT Date:

AIM:

To write a python program to create bar chart using matplot.


ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the required variables
Step 3: Creating the module file
Step 4: Import the module
Step 5: Pass the arguments to Module Functions using Module name Step
6: Stop
CODE:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([90, 80, 70, 50]) #students pass percentage
y = np.array([10, 20, 40, 30]) #no of students
plt.bar(x,y)
plt.show()

OUTPUT:

35
RESULT:
Thus, the python program was implemented and output was verified successfully.

36
Ex.no:8.D DISTANCE BETWEEN TWO POINTS USING SCIPY Date:

AIM:

To write a python program to calculate distance between two points using scipy.
ALGORITHM:
Step 1: Start
Step 2: Import necessary predefined packages (e.g., math package)
Step 3: Use the package name and its predefined functions
Step 4: Pass the arguments to predefined functions
Step 5: prints it result
Step 6: Stop

CODE:
from scipy import constants
from scipy.spatial.distance import euclidean
print(constants.pi) #display the value of pi
print(constants.kibi) #return the unit in bytes that is kilobytes
p1 = (1, 0)
p2 = (10, 2)
res = euclidean(p1, p2) #euclidean distance bewteen two points
print(res)

OUTPUT:
3.141592653589793

1024

9.219544457292887
RESULT: Thus, the python program to perform word count in a file is executed successfully.

37
Ex.no:9.A COPY FROM ONE FILE TO ANOTHER Date:

AIM:

To write a python program to copy from one file to another.


ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the required variables
Step 3: Create class
Step 4: Perform operations
Step 5: Print the output
Step 6: Stop
CODE:
from shutil import copyfile
sourceFile=input("Enter source file name: ")
destinationFile=input("Enter destination file name: ")
CopyFile(sourceFile,destinationFile)
print("File copied successfully")
c=open(destinationFile,"r")
print(c.read())
c.close()

OUTPUT:
Enter source file name: Document1.txt
Enter destination file name: Document2.txt
File copied successfully
A day begins with your hope. Good morning!!!!!

RESULT:
Thus, the python program was implemented and output was verified successfully.

38
Ex.no:9.B WORD COUNT Date:

AIM:

To write a python program with class and object.


ALGORITHM:
Step 1: Start
Step 2: create a class and its required variables
Step 3: Create an object for the class
Step 4: Perform operations
Step 5: Print the output
Step 6: Stop

CODE:

import sys numWords = 0


with open(sys.argv[1], 'r') as f:
for line in f:
words = line.split()
numWords += len(words)
print("Number of words:")
f.close()
print(numWords)

OUTPUT:
>>>python wordCount.py algorithm.txt
Number of words: 67

RESULT:
Thus, the python program was implemented and output was verified successfully.

39
Ex.no:9.C LONGEST WORD Date:

AIM:
To write a python program to longest word in a text file.
ALGORITHM:
Step 1: Start
Step 2: Initialize and declare the required variables
Step 3: Create a constructor
Step 4: Perform operation
Step 5: Print the output
Step 6: Stop

CODE:
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_words('about.txt'))

OUTPUT:
Pythonprogramming

RESULT:
Thus, the python program was implemented and output was verified successfully.

40
Ex.no:10.A DIVIDE BY ZERO ERROR Date:

AIM:

To write a python program to handle divide by zero error.


ALGORITHM:
Step 1:Start
Step 2: Initialize and declare the required variables
Step 3: Get input
Step 4: Inherit the class
Step 5:Print the output
Step 6: Stop

CODE:

try:
a = int (input ("Enter a:"))
b = int (input ("Enter b:"))
c = a/b
print ("a/b =",c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")

OUTPUT:
Enter a: 5
Enter b: 0
can't divide by zero
division by zero

RESULT:
Thus, the python program was implemented and output was verified successfully.

41
Ex.no: 10.B VOTER’S AGE VALIDITY Date:

AIM:

To Write a python program to check voter’s age validity

ALGORITHM:
Step 1: Start
Step 2: Initialize and import game library the required variables

Step 3: Write the function by using pygame library


Step 4: Run the program & play it
Step 5: Stop

CODE:

from datetime import date


current_year = date.today().year
year_of_birth = int(input('Enter Year of Birth: '))
age = current_year - year_of_birth
print('You are %s years old.' % age)
if age >=18:
print('You can Vote!')
else:
print('You cant Vote.')

OUTPUT:
Enter Year of Birth: 2012
You are 9 years old.
You can’t Vote.

RESULT:
Thus, the python program was implemented and output was verified successfully.

42
Ex.no: 10.C STUDENT MARK RANGE VALIDATION
Date:

AIM:

To Write a python program to validate student mark range.


ALGORITHM:
Step 1: Start
Step 2: Initialize and import game library the required variables
Step 3: Write the function by using pygame library
Step 4: Run the program & play it
Step 5: Stop

CODE:

def marks_Validation ():


marks = [25, 65, 46, 98, 78, 65 ]
max_marks = len(marks)* 100
total = 0
grade = 'F'
for i in range(len(marks)):
total += marks[i]
percentage = ((total) /max_marks) * 100
if (percentage >= 90):
grade = 'A'
else :
if (percentage >= 80 and percentage <= 89) :
grade = 'B'
else :
if (percentage >= 60 and percentage <= 79) :
grade = 'C'
else :
if (percentage >= 33 and percentage <= 59) :
grade = 'D'
else:
grade = 'F'
print(“The Student Grade is:”,grade)
marks_Validation()

43
OUTPUT:

The Student Grade is: C

RESULT:
Thus, the python program was implemented and output was verified successfully.

44

You might also like