Professional Documents
Culture Documents
Date:
AIM:
ALGORITHM:
Step 4: Consumed=Present-Previous
PROGRAM:
srlno=int(input())
rcptno=input()
billmonth=input()
date=input()
present=int(input())
previous=int(input())
consumed=present-previous
print(“Consumed:”, consumed)
if(consumed>=200):
total=consumed*2.50
else:
total=consumed*1.50
print(“\t\t______________”)
9293
M1308
07/2021
13/08/2021
3000
1500
Consumed: 1500
ELECTRICITY BILL
RESULT:
Thus, the program to generate electricity bill preparation using python language was executed and
verified.
Ex: No: 2A EXCHANGE THE VALUES OF TWO VARIABLES
Date:
AIM:
To write a program to exchange (swap) the values of two variables using python language.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the values for x and y
Step 3: Exchange the variables using temp variable
Step 4: temp=x; x=y; y=temp
Step 5: Print the interchanged values x and y
Step 6: Stop the execution
PROGRAM:
OUTPUT:
Read value for x: 50
RESULT:
Thus the program to exchange (swap) the values of two variables using python language was executed and
verified.
Ex: No: 2B CIRCULATE THE VALUES OF N VARIABLES
Date:
AIM:
To write a program to circulate the values of ‘n’ variables using python language.
ALGORITHM:
Step 1: Start.
Step 2: Read upper limit ‘n’.
Step 3: Read ‘n elements using loop’ and store them in list.
Step 4: POP out each element from list and append to list.
Step 5: Print list.
Step 6: Stop.
PROGRAM:
list1 = []
for i in range(0,n,1):
list1.append(x)
x = list1.pop(0)
list1.append(x)
print(list1)
OUTPUT
Enter integer: 1
Enter integer: 2
Enter integer: 3
[2,3,1]
[3,1,2]
[1.2.3]
RESULT:
Thus the program to circulate the values of ‘n’ variables using python language was executed and verified.
Ex: No: 2C DISTANCE BETWEEN TWO POINTS
Date:
AIM:
To write a program to find distance between two points using python language.
ALGORITHM:
Step 1: Start the execution.
Step 2: Read coordinates of 1st and 2nd points
Step 3: Compute the distance using formula (x2-x1)2+ (y2-y1)2
Step 4: Print the value of distance
Step 5: Stop the execution
PROGRAM:
OUTPUT :
RESULT:
Thus the program to circulate the values of ‘n’ variables using python language was executed and verified.
Ex: No: 3 SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE LOOPS
Date:
A)NUMBER SERIES
AIM:
To write a program to generate the number series using python language.
ALGORITHM:
Step 1: Take a value from the user and store it in a variable n.
Step 2. Use a for loop where the value of i ranges between the values of 1 and n.
Step 3. Print the value of i and ‘+’ operator while appending the value of i to a list.
Step 4. Then find the sum of elements in the list.
Step 5. Print ‘=’ followed by the total sum.
Step 6. Exit.
PROGRAM:
n=int(input("Enter a number: "))
a=[]
foriinrange(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
OUTPUT:
Case 1:
Enter a number: 4
1 + 2 + 3 + 4 = 10
Case 2:
Enter a number: 5
1 + 2 + 3 + 4 + 5 = 15
RESULT:
Thus the program to to generate the number series using python language was executed and verified.
Ex No:3B NUMBER PATTERNS
Date:
AIM:
To write a program to generate number patterns using python program.
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Read the number of rows
Step 3: The outer loop will print the number of rows which was incremented by 1
Step 4: The inner loop will print the value of I after each iteration.
Step 5: Print the number line after each row to display pattern correctly.
PROGRAM:
rows = int(input("Enter the number of rows: "))
# Outer loop will print number of rows
for i in range(rows+1):
# Inner loop will print the value of i after each iteration
for j in range(i):
print(i, end=" ") # print number
# line after each row to display pattern correctly
print(" ")
OUTPUT:
Enter the number of rows: 5
1
22
333
4444
55555
RESULT:
Thus the program to to generate the number patterns using python language was executed and verified
Ex No:3C PYRAMID PATTERN
Date:
AIM:
To write python program for printing pyramid pattern using stars.
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Read the number of rows
Step 3: Assign k to 0.
Step 4: The outer most loop(i) starts from 1 to rows+1
Step 5: Among the two inner loops, the for loop prints the required spaces for each row using
formula (rows-i) +1, where rows is the total number of rows and i is the current row number.
Step 6: The while loop prints the required number stars using formula 2 * i - 1. This formula gives the
number of stars for each row, where row is i.
Step 7: Display the value after the iteration is done.
Step 8: Stop the algorithm.
PROGRAM:
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
OUTPUT:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
RESULT:
Thus the program to generate the pyramid patterns using stars in python language was executed and
verified.
Ex No: 4A IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS
Date:
AIM
To write a python program to display the items present in a library using list methods.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the list of items present in a library. Apply the list methods and execute them.
Step 3: Display the output of each method in list.
Step 4: Stop the algorithm.
Python List Methods
Methods Descriptions
PROGRAM:
extend( ):
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
Output
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
insert():
fruits = ['apple','banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
Output
['apple', 'orange', 'banana', 'cherry']
remove():
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
Output
['apple', 'cherry']
pop():
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
Output
['apple', 'cherry']
RESULT:
Thus, the python program to display the items present in a library using list methods was executed and
verified successfully.
Ex No: 4B IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING TUPLES
Date:
AIM
To write a python program to display the items present in a tuple using tuple operations
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the list of items present in a tuple. Apply the tuple operations and execute them.
Step 3: Display the output of each method in tuple.
Step 4: Stop the algorithm.
Basic Tuples Operations
PROGRAM
Concatenation
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output
('a', 'b', 'c', 1, 2, 3)
Repetition
test_tup = (1, 3)
print("The original tuple : " + str(test_tup))
N=4
res = ((test_tup, ) * N)
print("The duplicated tuple elements are : " + str(res))
Output
The original tuple: (1, 3)
The duplicated tuple elements are: ((1, 3), (1, 3), (1, 3), (1, 3))
Concatenation
Program
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output
('a', 'b', 'c', 1, 2, 3)
Repetition
Program
test_tup =(1, 3)
print("The original tuple : "+str(test_tup))
N =4
res =((test_tup, ) *N)
print("The duplicated tuple elements are : "+str(res))
Output
The original tuple: (1, 3)
The duplicated tuple elements are: ((1, 3), (1, 3), (1, 3), (1, 3))
Python Membership Operators
In operator
Program
x = ["apple", "banana"]
print("banana" in x)
Output
True
Not in operator
Program
x = ["apple", "banana"]
print("pineapple" not in x)
Output
True
Iteration
1.Program
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Output:
apple
banana
cherry
2. Program
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output:
b
a
n
a
n
a
RESULT:
Thus, the python program to display the items present in a tuple using tuple operations was executed and
verified successfully.
Ex.No.5A IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING SETS
Date:
AIM
To write a python program to display the elements present in a set using set operations.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the list of elements present in a set. Apply the set operations and execute them.
Step 3: Display the output of each method in a set.
Step 4: Stop the algorithm.
OPERATIONS ON SETS
Operation Notation Meaning
Intersection A∩B all elements which are in both and
Union A∪B all elements which are in either or (or both)
Difference A−B all elements which are in but not in
Complement (or) all elements which are not in
PROGRAM
Intersection
GEEK = {'g', 'e', 'k'}
GEEK.add('s')
print('Letters are:', GEEK)
GEEK.add('s')
print('Letters are:', GEEK)
Output:
('Letters are:', set(['k', 'e', 's', 'g']))
('Letters are:', set(['k', 'e', 's', 'g'])
Union
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {7, 8, 9, 10}
print("set1 U set2 : ", set1.union(set2))
print("set1 U set2 U set3 :", set1.union(set2, set3))
Output:
set1 U set2 : {2, 4, 5, 6, 7, 8}
set1 U set2 U set3 : {2, 4, 5, 6, 7, 8, 9, 10}
Difference
A = {10, 20, 30, 40, 80}
B = {100, 30, 80, 40, 60}
print (A.difference(B))
print (B.difference(A))
Output:
{10, 20}
{100, 60}
Complement
x ={1,2,3,4,5,6}
y ={1,2,3,4}
z =x.difference(y)
Output:
5, 6
RESULT:
Thus, the python program to display the elements present in a set using set operations was executed and
verified successfully.
Ex.No.:5B IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
DICTIONARIES
Date:
AIM
To write a python program to display the elements present in a dictionary using dictionary operations.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the list of elements present in a set. Apply the set operations and execute them.
Step 3: Display the output of each method in a set.
Step 4: Stop the algorithm.
OPERATIONS ON DICTIONARIES
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
PROGRAM
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Output:
{}
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Output:
dict_values(['Ford', 'Mustang', 1964
RESULT:
Thus, the python program to display the elements present in a set using set operations was executed and
verified successfully
Ex.No.:6A IMPLEMENTING FACTORIAL USING FUNCTIONS
Date:
AIM:
ALGORITHM:
Step 6: i = i + 1
Step 7: Repeat the step 4,5,6 until the condition became false
if n == 1:
return n
else:
return n*recur_factorial(n-1)
if num < 0:
elif num == 0:
else:
OUTPUT:
Enter a number: 6
The factorial of 6 is 720
RESULT:
Thus the program to find the factorial of a number using functions in python language was executed and
verified.
Ex.No. 6B IMPLEMENTING LARGEST NUMBER IN A LIST USING FUNCTIONS
Date:
AIM
To write a program to implement the largest number in a list using functions in python.
ALGORITHM
Step 2- Use max() method and store the value returned by it in a variable
PROGRAM
def largest(list):
large= max(list)
return large
#input of list
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
#smallest
print("Largest in ",li,"is")
print(largest(li))
OUTPUT:
RESULT:
Thus the program to implement the largest number in a list using functions in python language was
executed and verified.
Ex: No.6C IMPLEMENTING AREA OF SHAPE USING FUNCTIONS
Date:
AIM:
To write a program to implement area of shape using functions in python program.
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Declare the function for area with parameters
PROGRAM:
def AreaofRectangle(width, height):
AreaofRectangle(8, 6)
OUTPUT:
RESULT:
Thus the program to implement area of shape using functions in python language was executed and
verified.
Ex.No:7A IMPLEMENTING REVERSE THE STRING
Date:
AIM:
To write a program to implement reverse the string in python.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Declare the reverse_string() function and pass the str argument. In the function body, the declared
empty string variable str1 that will hold the reversed string.
Step 3: Next, the for loop iterated every element of the given string, join each character in the beginning
and store in the str1 variable.
Step 4: After the complete iteration, it returned the reverse order string str1 to the caller function.
PROGRAM:
def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function
OUTPUT:
RESULT:
Thus the program to implement reverse the string in python language was executed and verified.
Ex No.: 7B IMPLEMENTING STRING PALINDROME
Date:
AIM:
To write a program to implement the string palindrome in python.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Read and find the string value.
Step 3: Compare every character above the middle character with the below character of the middle
character.
Step 4: If any character is equal then print yes. Otherwise, No .
Step 5: Stop the algorithm.
PROGRAM:
defisPalindrome(s):
returns ==s[::-1]
# Driver code
s ="malayalam"
ans =isPalindrome(s)
ifans:
print("Yes")
else:
print("No")
OUTPUT:
Yes
RESULT:
Thus the program to implement the string palindrome in python language was executed and verified.
Ex No.7C IMPLEMENTING CHARACTER COUNT IN STRING
Date:
AIM:
To write a program to implement the count of characters of string in python.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Create the value and store it in a file test_str.
Step 3: Display the original string. The isalpha() is use to compute the number of
alphabets in a string. len function is used to find the length of the string.
Step 4: Display the count of alphabets.
Step 5: Stop the algorithm.
PROGRAM:
test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'
# printing result
print("Count of Alphabets : " + str(res))
OUTPUT:
RESULT:
Thus the program to implement the count of characters of string in python language was executed and
verified.
Ex.No. 7D IMPLEMENTING CHARACTER REPLACING IN STRING
Date:
AIM:
To write a program to implement the replacing of characters of string in python.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Read the values of own string, own character and new character.
Step 3: Replace the new character from the old character. old character is Original string
PROGRAM:
str1 = input("Please Enter your Own String : ")
RESULT:
Thus, the program to implement the replacing of characters of string in python language was executed
and verified.
Ex.No. 8 IMPLEMENTING PROGRAMS USING WRITTEN MODULES AND STANDARD
LIBRARIES
Date:
8A) PANDAS
AIM
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the data frame. Apply the Pandas operations and execute them.
Step 3: Display the output of each operation.
Step 4: Stop the algorithm.
OPERATIONS ON PANDAS
Method Description
Slicing the Data Frame Convert a dictionary into a pandas Data Frame along with index
Merging Merge two data frames to form a single data frame
Joining Combine two differently indexed dataframes into a single result
dataframe
Concatenation Glues the dataframes together
PROGRAM
Merging
Output
IND_GDP Int_Rate Low_Tier_HPI Unemployment
2001 50 2 50.0 1.0
2002 45 1 NaN NaN
2003 45 2 45.0 3.0
2004 67 3 67.0 5.0
2004 67 3 34.0 6.0
Joining
df1 = pd.DataFrame({"Int_Rate":[2,1,2,3], "IND_GDP":[50,45,45,67]}, index=[2001, 2002,2003,2004])
df2=pd.DataFrame({"Low_Tier_HPI":[50,45,67,34],"Unemployment":[1,3,5,6]}, index=[2001,
2003,2004,2004])
joined= df1.join(df2)
print(joined)
Output:
IND_GDP Int_Rate Low_Tier_HPI Unemployment
2001 50 2 50.0 1.0
2002 45 1 NaN NaN
2003 45 2 45.0 3.0
2004 67 3 67.0 5.0
2004 67 3 34.0 6.0
Concatenation
import pandas as pd
df1 = pd.DataFrame({"HPI":[80,90,70,60],"Int_Rate":[2,1,2,3], "IND_GDP":[50,45,45,67]},
index=[2001, 2002,2003,2004])
df2 = pd.DataFrame({"HPI":[80,90,70,60],"Int_Rate":[2,1,2,3],"IND_GDP":[50,45,45,67]},
index=[2005, 2006,2007,2008])
concat= pd.concat([df1,df2])
print(concat)
Output:
HPI IND_GDP Int_Rate
2001 80 50 2
2002 90 45 1
2003 70 45 2
2004 60 67 3
2005 80 50 2
2006 90 45 1
2007 70 45 2
2008 60 67 3
Change the index
import pandas as pd
df= pd.DataFrame({"Day":[1,2,3,4], "Visitors":[200, 100,230,300], "Bounce_Rate":[20,45,60,10]})
df.set_index("Day", inplace= True)
print(df)
Output:
Day Bounce_Rate Visitors
1 20 200
2 45 100
3 60 230
4 10 300
import pandas as pd
df = pd.DataFrame({"Day":[1,2,3,4], "Visitors":[200, 100,230,300], "Bounce_Rate":[20,45,60,10]})
df = df.rename(columns={"Visitors":"Users"})
print(df)
Output:
Bounce_Rate Day Users
0 20 1 200
1 45 2 100
2 60 3 230
3 10 4 300
Data Munging
import pandas as pd
country=pd.read_csv("D:\\Users\\Aayushi\\Downloads\\world-bank-youth-unemployment\\API_ILO_co
untry_YU.csv",index_col=0)
country.to_html('edu.html')
Output:
RESULT:
Thus, the python program using modules and libraries in Pandas was executed and verified
successfully.
Ex No: 8B NUMPY
Date:
AIM
ALGORITHM:
Step 1: Start the algorithm
Step 2: Select the array. Apply the Numpy operations and execute them.
Step 3: Display the output of each operation.
Step 4: Stop the algorithm.
OPERATIONS ON NUMPY
Method Description
Flatten a multidimensional array
flatten
Returns a flattened one-dimensional array
ravel
reshape Returns a new array with a new shape.
Concatenating Arrays Concatenate three one-dimensional arrays to one array
Adding new New dimensions can be added to an array by using slicing and
dimensions np.newaxis
PROGRAM
Flatten:
import numpy as np
A = np.array([[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11],
[12, 13],
[14, 15]],
[[16, 17],
[18, 19],
[20, 21],
[22, 23]]])
flattened_X = A.flatten()
print(Flattened_X)
print(A.flatten(order="C"))
print(A.flatten(order="F"))
print(A.flatten(order="A"))
Output
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 8 16 2 10 18 4 12 20 6 14 22 1 9 17 3 11 19 5 13 21 7 15 23]
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Ravel:
If the order parameter is set to 'C', it means that the array gets flattened in row-major order. If 'F' is set, the
array gets flattened in column-major order. The array is flattened in column-major order only when 'A' is
Fortran contiguous in memory, and when the order parameter to 'A'. The last order is 'K', which flatten the
array in same order in which the elements occurred in the memory. By default, this parameter is set to 'C'.
print(A.ravel())
print(A.ravel(order="A"))
print(A.ravel(order="F"))
print(A.ravel(order="A"))
print(A.ravel(order="K"))
Output
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 8 16 2 10 18 4 12 20 6 14 22 1 9 17 3 11 19 5 13 21 7 15 23]
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Reshape:
Parameter Meaning
A array_like, Array to be reshaped.
Newshape int or tuple of ints
Order 'C', 'F', 'A', like in flatten or ravel
X = np.array(range(24))
Y = X.reshape((3,4,2))
Output
array([[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11],
[12, 13],
[14, 15]],
[[16, 17],
[18, 19],
[20, 21],
[22, 23]]])
Concatenate
x = np.array([11,22])
y = np.array([18,7,6])
z = np.array([1,3,5])
c = np.concatenate((x,y,z))
print(c)
Output
[11 22 18 7 6 1 3 5]
x = np.array([2,5,18,14,4])
y = x[:, np.newaxis]
print(y)
Output
[[ 2]
[ 5]
[18]
[14]
[ 4]]
RESULT:
Thus, the python program using modules and libraries in Numpy was executed and verified
successfully.
Ex No: 8C MATPLOTLIB
Date:
AIM
ALGORITHM:
Step 1: Start the algorithm
Step 2: Define the x-axis and corresponding y-axis values as lists.
Step 3: Plot them on canvas using .plot() function.
Step 4: Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
Step 5: Give a title to plot using .title() function.
Step 6: Finally, to view your plot, use .show() function.
Step 7: Stop the algorithm
PROGRAM:
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
RESULT:
Thus, the python program using modules and libraries in Matplotlib was executed and verified
successfully.
Ex No: 8D SCIPY
Date:
AIM
ALGORITHM:
Step 1: Start the algorithm
Step 2: Import the essential SciPy library in Python with I/O package and Numpy.
Step 3: Create 4 x 4, dimensional one’s array.
Step 4: Store array in example.mat file.
Step 5: Get data from example.mat file.
Step 6: Print output.
Step 7: Stop the algorithm
PROGRAM:
import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat(‘example.mat', struct_as_record=True)
data['ar']
OUTPUT:
Thus, the python program using modules and libraries in SciPy was executed and verified successfully.
Ex.No.9 IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING FILE
HANDLING
Date:
AIM:
To write a python program to copy the contents from one file to another using file handling functions.
ALGORITHM:
Step 1: Start the algorithm
Step 2: Declare the name of source file and target file
Step 3: Open the sFile and read the contents of that file.
Step 4: Write the contents in tFile using fileHandle.write()and close the file using
fileHandle.close()
Step 5: Display the output.
Step 6: Stop the algorithm.
PROGRAM:
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")
OUTPUT:
Enter the name of source file: ramesh.txt
Enter the name of target file: sundar.txt
File Copied Successfully!
RESULT:
Thus, the program to copy the contents from one file to another using file handling functions was executed
and verified.
Ex NO:9B WORD COUNT
Date:
AIM:
To write a python program to find the most frequent words(word count) in a text from a file using file
handling function.
ALGORITHM:
Step 1: Open the file in read mode and handle it in text mode.
Step 2: Read the text using read() function.
Step 3: Split the text using space separator.
Step 4: assume that words in a sentence are separated by a space character.
Step 5: The length of the split list should equal the number of words in the text file.
Step 6: We can refine the count by cleaning the string prior to splitting or validating the words after
splitting.
PROGRAM:
file = open("C:\data.txt", "rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
TEXT FILE: Welcome to pythonexamples.org. Here, you will find python programs for all general use
cases.
OUTPUT:
Number of words in text file: 14
RESULT:
Thus, the program to to find the most frequent words (word count) in a text from a file using file
handling function was executed and verified.
Ex No: 9C LONGEST WORD
Date:
AIM:
To write a python program to find the longest word in a text using file handling function.
ALGORITHM:
Steps:
1. Open text file say ‘name.txt’ in read mode using open function
2. Pass file name and access mode to open function
3. Read the whole content of text file using read function and store it in another variable say ‘str’
4. Use split function on str object and store words in variable say ‘words’
5. Find maximum word from words using len method
6. Iterate through word by word using for loop
7. Use if loop within for loop to check the maximum length of word
8. Store maximum length of word in variable say ‘longest_word’
9. Display longest_word using print function
PROGRAM:
fin = open("name.txt","r")
str = fin.read()
words = str.split()
max_len = len(max(words, key=len))
for word in words:
if len(word)==max_len:
longest_word =word
print(longest_word)
OUTPUT:
Sumedh
name.txt file:
RESULT:
Thus, the program to find the longest word in a text using file handling function was executed and
verified.
Ex.No.10. IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING EXCEPTION
HANDLING
Date:
Step 3:The try block test a block of code for errors and the except block handles the error.
RESULT:
Thus, the program to implement divide by zero error using exception handling was executed and verified.
Ex.No.10B VOTER’S AGE VALIDITY
Date:
AIM:
To write a python program to find voter’s age validity for election using exception handling.
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Call the main function which includes try and except statement.
Step 3: The try block test a block of code for errors and the except block handles the
error.
RESULT:
Thus, the program to find voter’s age validity for election using exception handling was executed and
verified.
Ex.No.10.C STUDENT MARK RANGE VALIDATION
Date:
AIM:
ALGORITHM:
Step 2: Get the data from student database such as roll number, name, and marks for three
subjects.
Step 3: Calculate the total and average marks for three subjects.
PROGRAM:
class Student:
marks = []
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
def total(self):
def average(self):
s1 = Student()
s1.displayData()
OUTPUT:
RESULT:
Thus, the program to find voter’s age validity for election using exception handling was executed and
verified.
Ex.No. 11 EXPLORING PYGAME TOOL
Date:
Python Pygame (Game Development Library)
Pygame
Pygame is a cross-platform set of Python modules which is used to create video games.
It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
Pygame was officially written by Pete Shinners to replace PySDL.
Pygame is suitable to create client-side applications that can be potentially wrapped in a standalone
executable.
Pygame Installation
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1 or above
version because it is much friendlier to beginners, and additionally runs faster. There are mainly two ways
to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what python uses
to install packages). The command is the following:
2. Installing through an IDE: The second way is to install it through an IDE and here we are using
Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can install it by running the
above command in the terminal or use the following steps:
To check whether the pygame is properly installed or not, in the IDLE interpreter, type the following
command and press Enter:
import pygame
If the command runs successfully without throwing any errors, it means we have successfully installed
Pygame and found the correct version of IDLE to use for pygame programming.
Simple pygame Example
Here is the simple program of pygame which gives a basic idea of the syntax.
import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
Output:
import pygame - This provides access to the pygame framework and imports all functions of pygame.
pygame.init() - This is used to initialize all the required module of the pygame.
pygame.display.set_mode((width, height)) - This is used to display a window of the desired size. The
return value is a Surface object which is the object where we will perform graphical operations.
pygame.event.get()- This is used to empty the event queue. If we do not call this, the window messages
will start to pile up and, the game will become unresponsive in the opinion of the operating system.
pygame.QUIT - This is used to terminate the event when we click on the close button at the corner of the
window.
pygame.display.flip() - Pygame is double-buffered, so this shifts the buffers. It is essential to call this
function in order to make any updates that you make on the game screen to make visible.
Ex.No. 12 DEVELOPING A GAME ACTIVITY USING PYGAME LIKE BOUNCING BALL
Date:
AIM:
To develop a bouncing ball game using Pygame
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Import the pygame and sys module at the top of python file.
Step 3: The pygame.display.set_mode() function returns the surface object for the window. This
function accepts width and height of the screen as arguments.
Step 4:.The image have been opened using pygame.image.load() method and set the ball rectangle area
boundary using get_rect() method.
Step 5: Using infinite loop make the ball to move continuously and reverse the direction of ball if it hits
the edges.
Step 6:.The fill() method is used to fill the surface background color.
RESULT:
Thus, the bouncing ball game using Pygame was developed and executed successfully.