0% found this document useful (0 votes)
24 views

24GE101-Lab Manual Python (1)

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

24GE101-Lab Manual Python (1)

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

EX.NO.

1 Identification and solving of simple real life or scientific or technical


DATE: problems, and developing flow charts for the same.

1(a). Flowchart for Electricity Bill Calculation

AIM : To draw a flowchart for Electricity bill calculation with the following rates for its
customers:
No. of units consumed Charges/unit (RM)
1-200 2.50
201 - 500 3.50
over 501 5.00

ALGORITHM :
Step 1: Start.
Step 2: Read the unit values.
Step 3: Check 1<=unit<=200 then calculate total_charges=unit*2.50.
Step 4: Check 201<=unit<=500 then calculate total_charges=unit*3.50.
Step 5: Check unit>500 then calculate total_charges=unit*5.0.
Step 6: Print total_charges.
Step 7: Stop.

FLOWCHART:
1(b). Flowchart for retail shop bill calculation.

AIM : To draw a flowchart for retail bill preparation

ALGORITHM :
Step 1: Start.
Step 2: Read item name.
Step 3: Read price per unit.
Step 4: Read the quantity.
Step 5: Compute Totalcost=Quantity*price per unit.
Step 6: Display total.
Step 7: Read payment .
Step 8: Compute the values using the formula paychange=payment-totalcost.
Step 9: Display the items, payment and paychange.
Step 10: Stop.

FLOWCHART:
1 (c ). Flowchart for computing sin series

AIM: To draw a flowchart to compute sin series

ALGORITHM:
Step 1: Take in the value of x in degrees and the number of terms and store it in separate variables.
Step 2: Pass these values to the sine function as arguments.
Step 3: Define a sine function and using a for loop, first convert degrees to radians.
Step 4: Use the sine formula expansion and add each term to the sum variable.
Step 5: Print the final sum of the expansion.
Step 6: Stop.

FLOWCHART:

RESULT:

Thus, the flowchart for simple real-life scenario and scientific problem is identified and
created successfully.
EX.NO.2 Python programming using simple statements and expressions
DATE:

2(a). Python Program using Simple Statements and Expressions -Exchange the values of two
variables

AIM:
To write a python program to exchange the values of two variables using statements and
expressions.

ALGORITHM:
Step 1: Declare temporary variables a and b.
Step 2: Assign the values for a and b.
Step 3: Swap the value of a to b, and b to a.
Step 4: Print the result.

PROGRAM:
a=10
b=20
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)

OUTPUT:

The swapping of a value is= 20


The swapping of b value is= 10

2(b). Python Program using Simple Statements and Expressions - Circulate the Values of N
Variables

AIM:
To write a python program to circulate the values of n variables using statements and expressions.

ALGORITHM:
STEP 1: Read the values to be circulated in a list.
STEP 2: Read the number of times of shifting in n.
STEP 3: Using list slicing, perform rotation.
STEP 4: Print (list[n:] +list[:n]).
STEP 5: Stop.

PROGRAM:
list=[10,20,30,40,50]
n=2
print(list[n:]+list[:n])

OUTPUT:
[30, 40, 50, 10, 20]
2 (c). Python Program using Simple Statements and Expressions -Distance between two
points

AIM:
To find the distance between two points using Python Statements and Expressions.

ALGORITHM:
STEP 1: Read the values of x1,x2 and y1,y2
STEP 2: Import math module to calculate the square root
STEP 3: Compute the distance using the formula
STEP 4: Using the formula, find square root of ( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
STEP 5: Print the result
STEP 6: Stop

PROGRAM:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

OUTPUT:
6.324555320336759

RESULT:
Thus, the swapping of two variables, to circulate the of n variables, distance between of two points
was successfully executed and verified.
EX.NO.3 Scientific problems using Conditionals and Iterative loops.
DATE:

3(a). Scientific problems using Conditionals and Iterative loops- Number series

AIM:
To write a Python program with conditional and iterative statements for Number Series.

ALGOTITHM:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1, x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.

PROGRAM:
n=int(input(" enter the number of terms for the series "))
i=1
x=0
while(i<=n):
x=x*2+1
print(x, sep= "")
i+=1

OUTPUT:
enter the number of terms for the series 5
1
3
7
15
31

RESULT:
Thus the python program to print numbers series is executed successfully and verified.
3(b).Scientific Problems Using Conditionals And Iterative Loops. –Number Patterns

AIM:
To write a Python program with conditional and iterative statements for Number Pattern.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to i
Step 6: Set j in inner loop using range function and i integer will be initialized to j;
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.

PROGRAM:

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


for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')

OUTPUT:
Enter the number of rows=7
1
22
333
4444
55555
666666

RESULT:
Thus the python program to print numbers patterns is executed and verified successfully.
3(c). Scientific Problems Using Conditionals And Iterative Loops. -Pyramid

AIM:
To write a Python program with conditional and iterative statements for Pyramid Pattern.

ALGORITHM:

Step 1: Start the program.


Step 2: Read the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = 0 to rows ;
Step 6: Set j in inner loop using range function, j=0 to i+1;
Step 7: Print * until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.

PROGRAM:
num_rows = int(input("Enter the number of rows"))
for i in range(0, num_rows):
for j in range(0, num_rows-i-1):
print(end=" ")
for j in range(0, i+1):
print("*", end=" ")
print()

OUTPUT:

Enter the number of rows7


*
**
***
****
*****
******
*******

RESULT:
Thus the python program to print numbers pyramid patterns is executed and verified.
EX.NO.4 Implementing real-time/technical applications using Lists, Tuples.
DATE:

4(a). Implementing Real-Time/Technical Applications Using Lists, Tuples -Items Present in a


Library

AIM :
To Write a python program to implement items present in a library using List and Tuple.

ALGORITHM:
Step 1: Start the program.
Step 2: Create the variable and assign the list of elements based on the library using List and tuple.
Step 3: Using array index, print the items using list and tuple.
Step 4: Print the result using output statement.
Step 5: Stop the program.

PROGRAM:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234 print(library)
Tuple:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 Not assigned in tuple
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print(tup3)

OUTPUT:
ramayanam
['ramayanam', 'valmiki', 123987, 234]
TUPLE:
(12134, 250000, 'books', 'totalprice')
4(b). Implementing Real-Time/Technical Applications Using Lists, Tuples -Components of a
Car

AIM:
To Write a python program to implement components of a car using List and Tuple.

ALGORITHM:

Step 1: Start the program


Step 2: Create the variable and assign the list of elements based on the car using List and tuple.
Step 3: Using array index print the items using list and tuple.
Step 4: Print the result using output statement.
Step 5: Stop the program.

PROGRAM:
cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]
new_list = []
for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)
#TUPLE:
cars=("Ferrari", "BMW", "Audi", "Jaguar")
print(cars)
print(cars[0])
print(cars[1])
print(cars[2])
print(cars[3])
print(cars[-1])
print(cars[-2])
print(cars[-3])
print(cars[-4])

OUTPUT:
LIST:
['Mercedes Benz', 'Maserati', 'Maruti Suzuki']
TUPLE:
('Ferrari', 'BMW', 'Audi', 'Jaguar')
Ferrari
BMW
Jaguar
Jaguar
4 (c). Implementing Real-Time/Technical Applications Using Lists, Tuples - Materials
required for construction of a building.

AIM:
To write a python program to implement materials required for construction of building.

ALGORITHM:
Step 1: Start the program.
Step 2: Create the variable and store the unordered list of elements based on materials required for
construction of building using List and tuple.
Step 3: Using array index print the items using list and tuple.
Step 4: Print the result using output statement.
Step 5: Stop the program.

PROGRAM:
materials= ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
materials.append("Tiles")
materials.insert(3,"Aggregates")
materials.remove("sand")
materials[5]="electrical"
print(materials)
#TUPLE:
materials = ("cementbags", "bricks", "sand", "Steelbars", "Paint")
print(materials)
print ("list of element is=",materials)
print ("materials[0]:", materials [0])
print ("materials[1:3]:", materials [1:3])

OUTPUT:
#LIST:
['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical']
#TUPLE:
('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
list of element is= ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
materials[0]: cementbags
materials[1:3]: ('bricks', 'sand')

RESULT:

Thus, the Python Program for implementing Real-Time/Technical Applications Using Lists, Tuples is
executed successfully and the output is verified.
EX.NO.5 Implementing real-time/technical applications using Sets, Dictionaries.
DATE:

5(a). Implementing real-time/technical applications using Sets - Adding and Removing


automobile brands

AIM:
To write a python program to add and remove automobile brands using Sets.

ALGORITHM:
Step 1: Start the program.
Step 2: Create the variable and store the unordered list of elements.
Step 3: Using for loop, list the number of elements and using array index print the items using set
and dictionary.
Step 4: Print the result using output statement.
Step 5: Stop the program.

PROGRAM:
cars = {'BMW', 'Honda', 'Audi', 'Mercedes', 'Honda', 'Toyota', 'Ferrari', 'Tesla'}
print('Approach #1= ', cars)
print('==========')
print('Approach #2')
for car in cars:
print('Car name = {}'.format(car))
print('==========')
cars.add('Tata')
print('New cars set = {}'.format(cars))
cars.discard('Mercedes')
print('discard() method = {}'.format(cars))

OUTPUT:
Approach #1= {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda'}
==========
Approach #2
Car name = BMW
Car name = Mercedes
Car name = Toyota
Car name = Audi
Car name = Ferrari
Car name = Tesla
Car name = Honda
==========
New cars set = {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
discard() method = {'BMW', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
5(b). Implementing real-time/technical applications using Dictionaries-Materials required for
construction of building.

AIM:
To write a python program to get the materials required for construction of building car using
Dictionaries.

ALGORITHM:
Step 1: Start the program.
Step 2: Create the variable and store the unordered list of elements based on materials required for
construction of building using dictionary.
Step 3: Using for loop, list the number of elements and using array index print the items using set
and dictionary.
Step 4: Print the result using output statement.
Step 5: Stop the program.

DICTIONARY
PROGRAM:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = 'BLUE PRINT'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'STEEL'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("\nAdding a Nested Key: ")
print(Dict)
OUTPUT:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT'}
Dictionary after adding 3 elements:
{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'LIME', '2':
'SAND'}}}

RESULT:
Thus, the Python program to display automobile brands using sets and getting materials for
construction of building using Sets and Dictionaries is executed successfully and verified.
EX.NO.6 Implementing programs using Functions.
DATE:

6 (a). Implementing Factorial Programs Using Functions.


AIM:
To write a Python function to calculate the factorial of a number.

ALGORITHM:
Step 1: Get a positive integer input (n) from the user.
Step 2: Check if the values of n is equal to 0 or not, if it's zero it will return 1, otherwise else statement
can be executed.
Step 3: Calculate the factorial of a number using the formula n*factorial(n-1)
Step 4: Print the calculated output.

PROGRAM:
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(factorial(n))

OUTPUT:
Input a number to compute the factiorial: 4
24
6(b). Implementing Program Largest Number in a List Using Function

AIM: To write a Python program to get the largest number from a list.

ALGORITHM:
Step 1- Declare a function to find the largest number.
Step 2- Use max() method and store the value returned by it in a variable
Step 3- Return the variable.
Step 4- Declare and initialize a list.
Step 5- Call the function and print the value returned by it.

PROGRAM:
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

OUTPUT: 2
6(c). Program to find the area of different shapes.

AIM :
To write a program to find the area of different shapes using python.

ALGORITHM:
Step 1 : Start.
Step 2 : Call the appropriate shapes and get the inputs.
Step 3 : Compute the formula for required shapes.
Step 4 : Return the area
Step 5 : Print the area.
Step 6 : Stop
PROGRAM :
def cir():
r=int(input("Enter the radius"))
area=3.14*r*r
return area
def tria():
b=int(input("Enter the base"))
h=int(input("Enter the height"))
area=1/2*b*h
return area
def square():
a=int(input("Enter the side"))
area=a*a
return area
def rect():
l=int(input("Enter the length"))
w=int(input("Enter the width"))
area=l*w
return area
print(cir())
print(tria())
print(square())
print(rect())
OUTPUT
Enter the radius4
50.24
Enter the base7
Enter the height5
17.5
Enter the side2
4
Enter the length6
Enter the width8
48

RESULT:
Thus the python program to implement functions was successfully executed and verified.
EX.NO:7 Implementing programs using Strings.
DATE:

7(a). Reversing a string

AIM:

To write a python program to implement reverse of a string using string functions

ALGORITHM:

Step1: Get the input from the user.


Step2: The function call is invoked, where the string is passed as input to reverse function.
Step3: For loop is executed until the last character in the string is reached.
Step 4: The str variable is incremented for each iteration and returned as the reversed string.

PROGRAM:
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s =input("Enter the string to reverse:")
print ("The original string is : ",end="")
print (s)
print ("The reversed string is : ",end="")
print (reverse(s))

OUTPUT:

Enter the string to reverse:python


The original string is : python
The reversed string is : nohtyp
7(b). Palindrome of a String

AIM:

To write a python program to implement palindrome of a string using string functions.

ALGORITHM:

Step 1: Get the input string from the user.


Step 2: Check whether string is equal to the reverse of the same string using slicing operation
in an if condition.
Step 3: If the condition is satisfied, then the string is a palindrome.

PROGRAM:

string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")

OUTPUT:

Enter a letter: mom


The letter is a palindrome
7(c). Character Count using String functions

AIM:

To write a python program to implement character count using string functions.

ALGORITHM:

Step 1: Get the string from the user.


Step 2: Get the character to be counted in the string from the user.
Step 3: For loop is executed until the last character is checked in the string.
Step 4:Using the if condition, the character entered and the characters in the string is
compared inside the for loop for each iteration.
Step 5: The number of times the entered character has been present in the string will be
returned as the total count.

PROGRAM:

test_str = input("Enter the String:")


character=input("Enter the Character:")
count = 0
for i in test_str:
if i == character:
count = count + 1
print ("Count is : "+ str(count))

OUTPUT:

Enter the String: programming


Enter the Character: m
Count is : 2
7(d). Replacing Character using String

AIM:
To write a python program to implement replacing characters using string functions

ALGORITHM:

Step 1: Read the String


Step 2: Replace the character in the string using replace() method.
Step 3: Display the replaced string.

PROGRAM:

string = " HI! HI! HI! WELCOME TO PYTHON PROGRAMMING"


print ("Original String:",string)
replace1=string.replace("HI", "HELLO")
print ("Replaced String 1:",replace1)
replace2=replace1.replace("HELLO", "Hello", 3)
print ("Replaced String 2:",replace2)

OUTPUT:

Original String: HI! HI! HI! WELCOME TO PYTHON PROGRAMMING


Replaced String 1: HELLO! HELLO! HELLO! WELCOME TO PYTHON
PROGRAMMING
Replaced String 2: Hello! Hello! Hello! WELCOME TO PYTHON PROGRAMMING

RESULT:

Thus, the python program to implement the strings was done successfully and the output was
verified.
EX.NO: 8 Implementing programs using written modules and Python
DATE: Standard Libraries

8(a). Simple Program using numpy.

AIM:
To write a python program to plot a simple python graph for a straight line.

ALGORITHM:
Step 1: Start the Program.
Step 2: Import the modules numpy, pyplot.
Step 3: Store the set of values in x, equation in y.
Step 4: Assign title, axis label for the graph.
Step 5: Show the graph.
Step 6: Stop.

PROGRAM:
In command prompt install this package –
pip install numpy
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(1,11)
y=2*x+7
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()

OUTPUT:
8(b). Program using pandas

AIM:
To create data frames using pandas in python.

ALGORITHM:
Step 1: Start the Program.
Step 2: Import numpy and pandas
Step 3: Create a dictionary with student name, marks of three subjects
Step 4: Convert the dictionary to a data frame
Step 5: Print the data frame
Step 6: Stop

PROGRAM:
import numpy as np
import pandas as pd
mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'], 'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],'algebra': [78, 88, 82, 87]}
#create dataframe using dictionary
df_marks = pd.DataFrame(mydictionary)
print(df_marks)

OUTPUT:
8(c). Using Scipy - Univariate Interpolation

AIM:
To implement a python Program to plot a univariate interpolation.

ALGORITHM:
Step 1: Start
Step 2: Import interpolate , pyplot
Step 3: Using x, y values arrange the graph area
Step 4: Using pyplot , print the graph
Step 5: Stop

PROGRAM:
import matplotlib.pyplot as plt
from scipy import interpolate
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
y1 = f(x1)
# use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()

OUTPUT:
8(d). Implementing programs using written modules and Python Standard Libraries–
numpy
AIM:
To Write a python program to implement numpy module in python.
ALGORITHM:
Step 1: Start the program.
Step 2: Create the package of numpy in python and using array index in numpy for numerical
calculation.
Step 3: Create the array index inside that index to assign the values in that dimension.
Step 4: Declare the method function of arrange statement can be used in that program.
Step 5: By using output statement, we can print the result.
PROGRAM:
In command prompt install this package-pip install numpy
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3],
[4, 5, 6, 7]], [[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
OUTPUT:

[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
array([[0, 1, 2, 3, 4, 5]])

RESULT:
Thus, the programs using written modules and Python Standard Libraries were
implemented in python.
EX.NO: 9 Implementing real-time/technical applications using File handling.
DATE:

9(a). Python program to copy the content of one file into another file

AIM:
To write a program to copy the content of one file into another file.
ALGORITHM:
Step 1: Start
Step 2:Open one file called test.txt in read mode.
Step 3:Open another file out.txt in write mode.
Step 4:Read each line from the input file and write it into the output file.
Step 5:Stop.
PROGRAM:

print("Enter the Name of Source File: ")


sourcefile = input()
print("Enter the Name of Target File: ")
targetfile = input()
fileHandle = open(sourcefile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(targetfile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("File Copied Successfully!")

OUTPUT:
Enter the Name of Source File: in.txt
Enter the Name of Target File: out.txt

File Copied Successful


9(b). Python program to copy the content of one file into another file.

AIM :
To write a Python Program to Count the Number of Words in a Text File.
ALGORITHM:
Step 1: Start.
Step 2: Open file “book.txt” in read mode and store contents of file in file object say fin
Step 3: Read each line from the file using read() function
Step 4: Split the line to form a list of words using split() function and store it in variable l.
Step 5:Initially set the value of count_words variable to zero in which we will store the
calculated result.
Step 6: Use for loop to read list of word stored in variable l.
Step 7: Find the length of words in the list and print it.
Step 8: Close the file using close()function.
Step 9: Stop.

PROGRAM:
fin = open("book.txt","r")

str = fin.read()
l = str.split()
count_words = 0
for i in l:
count_words = count_words + 1
print(count_words)
fin.close()

OUTPUT:
25
9(c). Python Program to find longest Word in a Text File.

AIM:
To write a Python Program to find longest Word in a Text File.

ALGORITHM:
Step 1: Start.
Step 2: Open text file say ‘name.txt’ in read mode using open function.
Step 3: Pass file name and access mode to open function.
Step 4: Read the whole content of text file using read function and store it in another variable ‘str’.
Step 5: Use split function on str object and store words in variable ‘words’.
Step 6: Find maximum word from words using len method.
Step 7: Iterate through word by word using for loop.
Step 8: Use if loop within for loop to check the maximum length of word.
Step 9: Store maximum length of word in variable ‘longest_word’.
Step 10: Display longst_word using print function.
Step 11: Stop.

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:
Encyclopedia

RESULT:
Thus, the program for real-time/technical applications using File handling was implemented
and executed successfully.
EX.NO:10 Implementing real-time/technical applications using Exception
DATE: handling

10(a). DIVIDE BY ZERO ERROR

AIM:
To write a python program to implement divide by zero error using Exception Handling.

ALGORITHM:
Step 1: Get the input for n, d and c.
Step 2: In the try block, calculate q=n/(d-c).
Step 3: If the denominator is non-zero, then the quotient gets printed.
Step 4: Otherwise, the exception Zero Division Error is executed.

PROGRAM:

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


d=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")

OUTPUT 1:
Enter the value of n:16
Enter the value of d:4
Enter the value of c:2
Quotient: 8.0

OUTPUT 2:
Enter the value of n:6
Enter the value of d:5
Enter the value of c:5
Division by Zero!
10(b). VOTERS AGE ELIGIBILITY

AIM:
To write a python program to check voter age eligibility using Exception Handling.

ALGORITHM:
Step 1: Get the age from the user.
Step 2: In the if block, check if the age is greater than 18, then print “Eligible to vote”.
Step 3: Otherwise, print “Not eligible to vote”
Step 4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()

OUTPUT 1:
Enter your age 24 Eligible to vote
OUTPUT 2:
Enter your age 14 Not eligible to vote
10 (c). STUDENT MARK RANGE VALIDATION

AIM:
To write a python program to validate students mark range using Exception Handling.

ALGORITHM:
Step 1: Get the number between the range(1 - 100)
Step 2: In the if block, check whether the number is between 1 to 100.
Step 3: Otherwise, print “Above 100, wrong”
Step 4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:
def input_number(min,max):
try:
while True:
n=int(input("Please enter a number between {} and {} :".format(min,max)))
n=int(n)
if(min<=n<=max):
print(n)
break
else:
print("Above 100, wrong")
break
except:
print("mark must be a valid number")
input_number(1,100)

OUTPUT:
Please enter a number between 1 and 100 :22
22
OUTPUT2:
Please enter a number between 1 and 100 :150
Above 100, wrong
OUTPUT 3:
Please enter a number between 1 and 100: ab

mark must be a valid number

RESULT:
Thus, the program for real-time / technical applications using Exception handling was
implemented and executed successfully.
EX. NO. 11 EXPLORING PYGAME TOOL
DATE:

Exploring Pygame Tool:


 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

Install pygame in Windows

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. The
command is the following:

py -m pip install -U pygame --user

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:

Open the File tab and click on the Settings option.

Select the Project Interpreter and click on the + icon.

It will display the search box. Search the pygame and click on the install package button.

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

import pygame
pygame.init()
screen = ygame.display.set_mode((400,500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
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.

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.
Pygame Surface
The pygame Surface is used to display any image. The Surface has a pre-defined
resolution and pixel format. The Surface color is by default black. Its size is defined by
passing the size argument.

Pygame Clock
Times are represented in millisecond (1/1000 seconds) in pygame. Pygame clock is
used to track the time. The time is essential to create motion, play a sound, or, react to
any event.

RESULT:

Thus the Pygame tool using Python is explored successfully.


EX.NO: 12 Developing a game activity using Pygame
DATE:

AIM:

To write a python program to implement bouncing ball using pygame tool.

ALGORITHM:

Step 1: Import Libraries: Import sys for system-level operations and pygame for the game
functionality.
Step 2: Initialize Pygame: pygame.init() sets up all the modules required for Pygame.
Step 3: Set Up Display: Create a window of size 800x600 pixels and set its title.
Step 4: Define Colors: Define some colors using RGB tuples.
Step 5: Main Game Loop:
Step 5.1: Check for events (like closing the window).
Step 5.2: Fill the screen with a color (white in this case).
Step 5.3: Update the display with pygame.display.flip().
Step 6: Quit Pygame: Exit the game loop and properly quit Pygame and Python.

PROGRAM:

import sys
import pygame
# Initialize Pygame
pygame.init()
# Set up the display
width, height = 800, 600
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame Window")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the screen with white
window.fill(WHITE)
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()
sys.exit()
Execution:

Run program in https://trinket.io/features/pygame

OUTPUT:

RESULT:

Thus, the python program to implement bouncing balls using pygame tool was
executed successfully and verified.

You might also like