Python Lab (1) 2
Python Lab (1) 2
PANDUR, THIRUVALLUR
CERTIFICATE
Certified to be bonafide record of work done by _______________ on 1ST Semester
BE/B.TECH ( ) in the GE3171-PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY during the academic year 2024-2025.
Page
S. No. Date Name of the Experiment Sign
No.
1a.
1b.
1c.
1d.
1e
1f.
2a.
2b.
2c.
3a.
3b.
3c.
Page
S. No. Date Name of the Experiment Sign
No.
4a.
4b.
4c.
5a.
5b.
5c.
6a.
6b.
6c.
7a.
7b.
7c.
7d.
8a.
Page
S. No. Date Name of the Experiment Sign
No.
8b.
8c.
8d.
9a.
9b.
9c.
10a.
10b.
10c.
11.
12a.
12b.
1a. ELECTRICITY BILLING FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read consumer details
Step 3: Read previous month reading
Step 4: Read current month reading
Step 5: Calculate the units consumed by subtracting the current month reading from the
previous month reading
Step 6: Calculate the bill amount by splitting the units consumed based on the tariff
Step 7: Add all the unit prices based on the tariff slabs to get the total amount
Step 8: Print the consumer details
Step 9: Print the total bill amount
Step 10: Stop
PSEUDOCODE:
1
FLOW CHART:
RESULT:
The flowchart for generating electricity bill for consumers was successfully designed.
2
1b. RETAIL SHOP BILLING FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Declare item1’s unit price
Step 3: Get the unit price of item1 from the consumer
Step 4: Calculate total price of unit1 by multiplying unit price of item1 and its quantity
Step 5: Declare item2’s unit price
Step 6: Get the unit price of item2 from the consumer
Step 7: Calculate total price of unit2 by multiplying unit price of item1 and its quantity
Step 8: Declare item3’s unit price
Step 9: Get the unit price of item3 from the consumer
Step 10: Calculate total price of unit3 by multiplying unit price of item1 and its quantity
Step 11: Calculate the total amount by adding up all the total price of the items
Step 12: Display the total amount
Step 13: Stop
PSUEDOCODE
3
FLOW CHART
RESULT:
The flowchart for generating retail shop bill was successfully designed.
4
1c. PRINTING SINE SERIES FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Store the initial value of the sine series
Step 3: Store the ending value of the sine series
Step 4: Store the increment value for the next sine series to be calculated
Step 5: Start from the initial value
Step 6: Increase each count by the increment value
Step 7: Calculate the sine value for each number by converting them into radians
Step 8: Display the sine value for the current number
Step 9: Repeat steps 6, 7 & 8 till the ending value is reached
Step 10: Stop
PSEUDOCODE
x1 x3 x5 x7
CALCULATE sin(x) = ...
1! 3! 5! 7!
DISPLAY sin(x)
END LOOP
5
FLOW CHART
RESULT:
The flowchart for generating printing sine series was successfully designed.
6
1d. CALCULATE WEIGHT OF A MOTORCYCLE FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the cc of the motorcycle from the user
Step 3: Based upon the cc of the motorcycle, assign the weight of the motorcycle
Step 4: Display the weight in kilogram, of the motorcycle
Step 5: Stop
PSEUDOCODE:
READ cc
IF cc < 300 THEN weight = 350
ELSE
IF cc >= 300 and cc < 500 THEN weight = 410
ELSE
IF cc >= 500 and cc < 900 THEN weight = 430
ELSE
IF cc >= 900 and cc < 1100 THEN weight = 500
ELSE
IF cc >= 1100 THEN weight = 610
END IF
DISPLAY weight
7
FLOW CHART
RESULT:
The flowchart for generating the weight of a motorcycle was successfully designed.
8
1e. CALCULATING THE WEIGHT OF A STEEL BAR FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the diameter of the steel bar in mm from the user
Step 3: Get the length of the steel bar in meters
Step 4: Calculate the weight of the steel bar
Step 5: Display the weight of the steel bar
Step 6: Stop
PSEUDOCODE:
9
FLOW CHART
RESULT:
The flowchart for calculating the weight of a steel bar was successfully designed.
10
1f. THREE PHASE CURRENT CALCULATION FLOWCHART
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the line to line voltage
Step 3: Get the power factor value
Step 4: Calculate the current in the circuit
Step 5: Display the current value
Step 6: Stop
PSEUDOCODE:
11
FLOW CHART
RESULT:
The flowchart for calculating current in a 3 phase supply was successfully designed.
12
2a. PYTHON PROGRAM TO EXCHANGE THE VALUES OF TWO VARIABLES
Date:
AIM:
To write a write a Python program using simple statements and expressions to exchange the
value of two variables.
ALGORITHM:
Step 1: Start
Step 2: Get the first number (num1) from the user
Step 3: Get the second number (num2) from the user
Step 4: Use a temporary variable (temp) to store the value of num1
Step 5: Store the value of num2 in num1
Step 6: Store the value of temp in num2
Step 7: Print the swapped values of num1 and num2
Step 8: Stop
PROGRAM:
13
OUTPUT:
RESULT:
The Python program to exchange the values of two variables was successfully executed.
14
2b. CIRCULATE THE VALUES OF n VARIABLES
Date:
AIM:
To write a Python program using simple statements and expressions to circulate the values
of n variables
ALGORITHM:
Step 1: Start
Step 2: Get the number of elements ‘n; from the user
Step 3: Initialize a list
Step 4: Get the values for all the ‘n’ elements from the user and store them in the list
Step 5: Repeat the loop for ‘n’ times
Step 5.1: Pop the first element from the list
Step 5.2: Add this element to the end of the list
Step 5.3: Display the contents of the list
Step 6: Stop
PROGRAM:
for x in range(count):
elements = int(input("Enter the elements : "))
list_nos.append(elements)
15
for x in range(count):
pop_element = list_nos.pop(0)
list_nos.append(pop_element)
print(list_nos)
OUTPUT:
RESULT:
The Python program to circulate the values of ‘n’ variables was successfully executed.
16
2c. CALCULATE THE DISTANCE BETWEEN TWO POINTS
Date:
AIM:
To write a Python program using simple statements and expressions to calculate the
distance between two points
ALGORITHM:
Step 1: Start
Step 2: Get the coordinate values of the first point (x1, y1)
Step 3: Get the coordinate values of the second point (x2, y2)
Step 4: Calculate the distance between the two points using the formula:
(x2 x1 ) 2 (y2 y1 )2
PROGRAM:
import math
17
OUTPUT:
RESULT:
The Python program to calculate the distance between two points was successfully executed.
18
3a. PYTHON PROGRAM TO PRINT NUMBER SERIES
Date:
AIM:
To write a Python program using conditionals and iterative loops to print a number series
ALGORITHM:
Step 1: Start
Step 2: Get the starting value of the number series
Step 3: Get the number of terms in the series
Step 4: Get the difference between two consecutive terms in the number series
Step 5: Calculate the end term of the series using the formula:
end = start number + number of terms + difference
Step 6: Loop till the end term by adding the difference to each consecutive terms generated
Step 7: Display the number series
Step 8: Stop
PROGRAM:
19
OUTPUT:
RESULT:
The Python program to calculate the number series was successfully executed.
20
3b. PYTHON PROGRAM TO PRINT NUMBER PATTERN
Date:
AIM:
To write a Python program using conditionals and iterative loops to print a number pattern
ALGORITHM:
Step 1: Start
Step 2: Get the height of the number pattern
Step 3: Repeat until the height of the pattern
Step 3.1: For each loop start from 1
Step 3.2: Add terms one more than the previous term by incrementing each previous
number in the pattern by 1
Step 4: Stop
PROGRAM:
21
OUTPUT:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
RESULT:
The Python program to print the number pattern was successfully executed.
22
3c. PYTHON PROGRAM TO PRINT PYRAMID PATTERN
Date:
AIM:
To write a Python program using conditionals and iterative loops to print a pyramid pattern
ALGORITHM:
Step 1: Start
Step 2: Get the height of the pyramid
Step 3: Repeat until the height of the pyramid is reached, starting from 1
Step 3.1: Print the pattern in each row
Step 3.2: For each successive row align and print the pattern with one count more than
the previous row count
Step 4: Stop
PROGRAM:
print()
k = 2 * pyramid_ht - 2
for i in range(0, pyramid_ht):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("*", end=" ")
print()
23
OUTPUT:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
RESULT:
The Python program to print the pyramid pattern was successfully executed.
24
4a. IMPLEMENTING ITEMS PRESENT IN A LIBRARY USING LISTS
Date:
AIM:
To write a Python program to implement real time applications using Lists to implement the
items present in a library
ALGORITHM:
Step 1: Start
Step 2: Create an empty list
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the name of the new book and add it to the list
Step 5: If choice is 2, then remove the last added book from the list
Step 6: If choice is 3, then display all the books present in the list
Step 7: If choice is 0, then exit
Step 8: Stop
PROGRAM:
book_list = []
choice = True
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
25
if (choice == 1):
book_name = input("Enter the name of the Book : ")
book_list.append(book_name)
print(book_list)
elif (choice == 2):
if (len(book_list) > 0):
book_list.pop()
print(book_list)
else:
print ("The Book List is EMPTY")
elif (choice == 3):
print(book_list)
elif (choice == 0):
print("Thank You!")
OUTPUT:
26
['Python Programming', 'C++ Unleashed']
RESULT:
The Python program to implement items present in a library using lists was successfully
executed.
27
4b. IMPLEMENTING COMPONENTS PRESENT IN A CAR USING LISTS
Date:
AIM:
To write a Python program to implement technical applications using Lists to implement the
components present in a car
ALGORITHM:
Step 1: Start
Step 2: Create an empty list
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the name of the new part and add it to the end of the list
Step 5: If choice is 2, then get the position from the user and remove the part present at
that position
Step 6: If choice is 3, then remove the last added part added to the list
Step 7: If choice is 4, then sort all the parts present in the list
Step 8: If choice is 5, then display all the parts present in the list
Step 9: If choice is 6, then count all the parts present in the list
Step 10: If choice is 0, then exit
Step 11: Stop
PROGRAM:
parts_list = []
28
print ("5. Display Parts")
print ("6. Count Parts")
print ("0. Exit")
choice = True
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
car_part = input("Enter the name of the Part : ")
parts_list.append(car_part)
print(parts_list)
elif (choice == 2):
car_part = input("Enter the name of the Part : ")
position = int(input("Enter the position of the Part : "))
parts_list.insert(position-1, car_part)
print(parts_list)
elif (choice == 3):
if (len(parts_list) > 0):
parts_list.pop()
print(parts_list)
else:
print ("The Parts List is EMPTY")
elif (choice == 4):
parts_list.sort()
print(parts_list)
elif (choice == 5):
print(parts_list)
elif (choice == 6):
29
print(f"The number of {car_part} available is : {available}")
elif (choice == 0):
print("Thank You!")
OUTPUT:
Components of a Car
30
Enter your Choice : 1
Enter the name of the Part : Brake
['Engine', 'Transmission', 'Clutch', 'Gear', 'Brake']
RESULT:
The Python program to implement components present in a car using lists was successfully
executed.
31
4c. IMPLEMENTING MATERIALS REQUIRED FOR CONSTRUCTION OF A
BUILDING USING TUPLES
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create a tuple containing the materials required for constructing a building
Step 3: Get the choice from the user
Step 4: If choice is 1, then display the construction materials from the tuple
Step 5: If choice is 2, then display the total materials that are present
Step 6: If choice is 3, then get the name of the material and print its position in the tuple
Step 7: If choice is 4, then get the name of the material and print whether the material is
available or not
PROGRAM:
choice = True
32
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
print ("\nMaterials used in construction are :")
for x in materials:
print(x)
elif (choice == 2):
print("\nThe total number of materials :", len(materials))
elif (choice == 3):
choice = input("\nEnter the name of the material : ")
material_position = materials.index(choice) + 1
print (f"The material - {choice} is at position :
{material_position}")
elif (choice == 4):
choice = input("\nEnter the name of the material : ")
if(choice) in materials:
print (choice, "is Available")
else:
print (choice, "is Not Available")
elif (choice == 0):
print("Thank You!")
OUTPUT:
Construction Materials
33
Enter your Choice : 1
34
RESULT:
The Python program to implement materials required for construction of a building was
successfully executed.
35
5a. IMPLEMENTING LANGUAGE OPERATONS USING SETS
Date:
AIM:
To write a Python program for real time implementation of language operations using sets
ALGORITHM:
Step 1: Start
Step 2: Create and populate two sets containing names of programming languages
Step 3: Perform various set operations between these two sets
Step 4: Display the results
Step 5: Stop
PROGRAM:
36
#All Languages present in both the sets
print("\nThe Set Union of both the languages are:")
print(oop_languages | funct_languages)
#Languages present in both the sets, but without any common elements
print("\nThe Set Symmetric Difference between both the languages are:")
print(oop_languages ^ funct_languages)
OUTPUT:
37
The Set Intersection of both the languages are:
{'Python'}
RESULT:
The Python program to implement language operations between two sets was successfully
executed.
38
5b. IMPLEMENTING COMPONENTS OF AN AUTOMOBILE USING DICTIONARIES
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create a dictionary containing the key-value pairs of the automobile components
and their corresponding price
Step 3: Perform various dictionary operations
Step 4: Display the results
Step 5: Stop
PROGRAM:
39
print("\nThe Values in the Dictionary are :")
x=components_dict.values()
print(x)
OUTPUT:
40
Enter the name of the New Part : Transmission
Enter the price of the New Part : 15000
RESULT:
The Python program to implement the components of an automobile using dictionaries was
successfully executed.
41
5c. IMPLEMENTING ELEMENTS OF A CIVIL STRUCTURE USING DICTIONARIES
Date:
AIM:
To write a Python program for technical applications to implement the elements requires for
constructing a civil structure by using dictionaries
ALGORITHM:
Step 1: Start
Step 2: Create a dictionary containing the key-value pairs of the civil structural elements
and their corresponding IDs
Step 3: Perform various dictionary operations
Step 4: Display the results
Step 5: Stop
PROGRAM:
42
print(x)
OUTPUT:
43
The Items in the Dictionary are :
dict_items([('Foundation', 1), ('Basement', 2), ('1 Floor', 3), ('Walls', 4),
('Doors', 5)])
RESULT:
The Python program to implement the elements of a civil structure using dictionaries was
successfully executed.
44
6a. FACTORIAL OF A NUMBER USING FUNCTIONS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the number from the user
Step 3: Define a function to calculate the factorial of the number
Step 4: If the number is either a 0 or a 1 return 1 as the factorial
Step 5: Else calculate the factorial recursively by calling the function and multiplying each
factorial together
Step 6: Display the factorial
Step 7: Stop
PROGRAM:
def factorial(number):
return 1 if (number == 0 or number == 1) else number * factorial (number -
1)
answer = factorial(number)
45
OUTPUT:
RESULT:
The Python program to calculate the factorial of a number using functions was successfully
executed.
46
6b. LARGEST NUMBER IN A LIST USING FUNCTIONS
Date:
AIM:
To write a Python program to find the largest number in a list by using functions
ALGORITHM:
Step 1: Start
Step 2: Create an empty list to store the numbers
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the inputs from the user and store the numbers in the list
Step 5: If choice is 2, then call the function to find the largest number
Step 6: Pass the list as an argument to the function and iterate till the largest number in the
list is found
Step 7: Return the largest number in the list
Step 8: Print the largest number
Step 9: Stop
PROGRAM:
number_list = []
def find_largest(numbers):
largest = number_list[0]
for x in numbers:
47
if x > largest:
largest = x
return (largest)
choice = True
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
number = int(input("Enter the Number : "))
number_list.append(number)
print(number_list)
elif (choice == 2):
largest_number = find_largest(number_list)
print(largest_number)
OUTPUT:
1. Add Numbers
2. Find Largest Number
0. Exit
48
[20, 30]
RESULT:
The Python program to find the largest number in a list using functions was successfully
executed.
49
6c. CALCULATING AREA OF SHAPES USING FUNCTIONS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the choice from the user
Step 3: If choice is 1, get the measure of sides and calculate the area of the square. Print
the resultant area as output
Step 4: If choice is 2, get the measure of length & breadth and calculate the area of the
rectangle. Print the resultant area as output
Step 5: If choice is 3, get the measure of the base & height and calculate the area of the
triangle. Print the resultant area as output
Step 6: If choice is 4, get the measure of radius and calculate the area of the circle. Print
the resultant area as output
Step 7: Stop
PROGRAM:
50
def square_area():
side = float(input("Enter the measure of the side : "))
area = side ** 2
print ("Area of the Square is : " , area, " sq. units")
def rectangle_area():
length = float(input("Enter the measure of the length : "))
breadth = float(input("Enter the measure of the breadth : "))
area = length * breadth
def triangle_area():
base = float(input("Enter the measure of the base : "))
height = float(input("Enter the measure of the height : "))
area = 0.5 * base * height
print ("Area of the Triangle is : " , area, " sq. units")
def circle_area():
radius = float(input("Enter the measure of the radius : "))
area = 3.14 * (radius ** 2)
print ("Area of the Circle is : " , area, " sq. units")
choice = True
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
square_area()
51
elif (choice == 3):
triangle_area()
OUTPUT:
1. Area of a Square
2. Area of a Rectangle
3. Area of a Triangle
4. Area of a Circle
0. Exit
52
Enter your Choice : 4
Enter the measure of the radius : 10
Area of the Circle is : 314.0 sq. units
RESULT:
The Python program to calculate the area of different shapes by using functions was
successfully executed.
53
7a. IMPLEMENTING REVERSING STRINGS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the input string to be reversed from the user
Step 3: Write a function to reverse the string
Step 4: Read the string character by character
Step 5: For each character read, add the next character in front of the previous character
Step 6: Repeat till the end of string is reached
Step 7: Print the reversed string as the output
Step 8: Stop
PROGRAM:
def reverse(s):
str = ""
for i in s:
str = i + str
return str
54
print("The reversed string is : ", end="")
print(reverse(string))
OUTPUT:
RESULT:
The Python program to reverse the given string was successfully executed.
55
7b. IMPLEMENTING PALINDROME CHECK ON STRINGS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the input string to be reversed from the user
Step 3: Write a function to reverse the string
Step 4: Read the string character by character
Step 5: For each character read, add the next character in front of the previous character
Step 6: Repeat till the end of string is reached
Step 7: Store the reversed string
Step 8: Write a function that checks if the original string is the same as the reversed string
Step 9: If both string are same, print that the string is a palindrome, else print that the string
is not a palindrome
Step 10: Stop
PROGRAM:
def reverse(s):
reverse_word = ""
for i in s:
reverse_word = i + reverse_word
return reverse_word
56
print ("The given word is a Palindrome")
else:
print ("The given word is Not a Palindrome")
OUTPUT:
RESULT:
57
7c. IMPLEMENTING COUNTING CHARACTERS IN A STRING
Date:
AIM:
To write a Python program to count the number of occurrences of a given character in a string
ALGORITHM:
Step 1: Start
Step 2: Get the input string from the user
Step 3: Get the character to be counted
Step 4: Read the string character by character, till end of string is reaches
Step 5: Compare each character of the string with the character to be counted, supplied by
the user
Step 6: If the character matches, increment the counter by 1
Step 7: Print the value of the counter
Step 8: Stop
PROGRAM:
count = 0
for i in input_string:
if i == character:
count = count + 1
58
OUTPUT:
RESULT:
The Python program to count the number of occurrences of a given character in a string
was successfully executed.
59
7d. IMPLEMENTING REPLACING CHARACTERS IN STRINGS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the input string from the user
Step 3: Get the character to be replaced
Step 4: Get the replacement character
Step 5: Use the replace function in Python to replace the original character with the given
replacement character
Step 6: Print the new string
Step 7: Stop
PROGRAM:
60
OUTPUT:
RESULT:
The Python program to replace a given character in a string was successfully executed.
61
8a. IMPLEMENTING PYTHON STANDARD LIBRARIES - PANDAS
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import the pandas library
Step 3: Create three Series in pandas and assign them values
Step 4: Combine the Series into a Python dictionary
Step 5: Create a pandas DataFrame using the created dictionary
Step 6: Print the contents of the DataFrame
Step 7: Stop
PROGRAM:
import pandas as pd
# Define series 1
s1 = pd.Series([1, 3, 4, 5, 6, 2, 9])
# Define series 2
s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3])
# Define series 3
s3 = pd.Series(['a', 'b', 'c', 'd', 'e'])
62
# Define Data
Data = {'first':s1, 'second':s2, 'third':s3}
# Create DataFrame
dfseries = pd.DataFrame(Data)
print (dfseries)
OUTPUT:
RESULT:
The Python program to implement the Pandas library was successfully executed.
63
8b. IMPLEMENTING PYTHON STANDARD LIBRARIES - NUMPY
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import the numpy library
Step 3: Create a numpy array with floats from a given list
Step 4: Create an array from tuples
Step 5: Create a 3x4 matrix with all zeros
Step 6: Create a constant value array with complex types
Step 7: Create an array with random values
Step 8: Create a sequence of integers from 0 to 30 with steps of 5
Step 9: Create a sequence of 10 values in range 0 to 5
Step 10: Reshaping 3x4 array to a 2x2x3 array
Step 11: Flatten a given array
Step 12: Stop
PROGRAM:
import numpy as np
64
# Creating array from tuple
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
newarr = arr.reshape(2, 2, 3)
65
print ("\nOriginal array:\n", arr)
print ("Reshaped array:\n", newarr)
# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flarr = arr.flatten()
OUTPUT:
A random array:
[[0.21291071 0.35294952]
[0.12338574 0.67235312]]
66
A sequential array with steps of 5:
[ 0 5 10 15 20 25]
Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]
Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]
RESULT:
The Python program to implement the Numpy library was successfully executed.
67
8c. IMPLEMENTING PYTHON STANDARD LIBRARIES - MATPLOTLIB
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import the pyplot module from the matplotlib library
Step 3: Draw bar graphs using the supplied data
Step 4: Provide legends, x label, y label and title to the bar graph
Step 5: Display the bar graph
Step 6: Stop
PROGRAM:
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="Car", color='plum',width=.5)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Bus", color='lightgreen',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance Travelled (kms)')
plt.title('Travel Information')
plt.show()
68
OUTPUT:
RESULT:
The Python program to implement the Matblotlib library was successfully executed.
69
8d. IMPLEMENTING PYTHON STANDARD LIBRARIES - SCIPY
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import the linalg module from the scipy library
Step 3: Import the numpy library
Step 4: Define a 2x2 numpy array
Step 5: Call the eigen function from the scipy library on the numpy array
Step 6: Print the eigen values and the eigen vectors
Step 7: Stop
PROGRAM:
#Get eigenvalues
print ("Eigen Values are : \n")
print(eg_val)
70
#Get eigenvectors
print ("\nEigen Vectors are : \n")
print(eg_vect)
OUTPUT:
[6.+0.j 1.+0.j]
[[ 0.9701425 -0.70710678]
[ 0.24253563 0.70710678]]
RESULT:
The Python program to implement the Scipy library was successfully executed.
71
9a. IMPLEMENTING FILE COPYING
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Open the first file to be read in the read mode
Step 3: Create the second file to be written to in the write mode
Step 4: Read the contents of the first file line by line and write it to the second file
Step 5: When all contents are copied, print that the file was successfully copied
Step 6: Stop
PROGRAM:
secondfile.write(line)
OUTPUT:
72
Ex 09\ReadFileEx09a.txt
Where the mind is without fear and the head is held high;
Where knowledge is free;
Where the world has not been broken up into fragments by narrow domestic
walls;
Where words come from the depths of truth;
Where tireless striving stretches its arms towards perfection;
Where the clear stream of reason has not lost its way into the dreary desert
sands of dead habit;
Where the mind is led forward by thee into ever-widening thought and action;
Into that heaven of freedom, my father, let my country awake.
Ex 09\WriteFileEx09a.txt
Where the mind is without fear and the head is held high;
Where knowledge is free;
Where the world has not been broken up into fragments by narrow domestic
walls;
Where words come from the depths of truth;
Where tireless striving stretches its arms towards perfection;
Where the clear stream of reason has not lost its way into the dreary desert
sands of dead habit;
Where the mind is led forward by thee into ever-widening thought and action;
Into that heaven of freedom, my father, let my country awake.
RESULT:
The Python program to copy the contents of one file to another was successfully executed.
73
9b. IMPLEMENTING WORD COUNT ON A FILE
Date:
AIM:
To write a Python program to count the number of occurrences of each word in a given file
ALGORITHM:
Step 1: Start
Step 2: Import the required Python libraries
Step 3: Open the file in read mode
Step 4: Using regular expressions split the individual words in the file
Step 5: Count the instances of each word using a counter
Step 6: Print each word followed by its occurrence count
Step 7: Stop
PROGRAM:
import re
from collections import Counter
import sys
with open(filename) as f:
passage = f.read()
74
word_counts = Counter(cap_words)
for k, v in word_counts.items():
print (k, '-->' ,v)
OUTPUT:
Ex 09\QuoteFileEx09b.txt
Try to be a rainbow in someones cloud. Do not fear the storm , for the rainbow
is never far behind. If you want to enjoy the rainbow , be prepared to endure
the storm.
TRY --> 1
TO --> 3
BE --> 2
A --> 1
RAINBOW --> 3
IN --> 1
SOMEONES --> 1
CLOUD --> 1
DO --> 1
NOT --> 1
FEAR --> 1
THE --> 4
STORM --> 2
FOR --> 1
IS --> 1
NEVER --> 1
FAR --> 1
BEHIND --> 1
IF --> 1
YOU --> 1
WANT --> 1
75
ENJOY --> 1
PREPARED --> 1
ENDURE --> 1
RESULT:
The Python program to count the number of occurrences of each word in a given file was
successfully executed.
76
9c. IMPLEMENTING FINDING LONGEST WORDS IN FILE
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Open the given file in read mode
Step 3: Read the contents of the file and split each individual words
Step 4: Add the words in a list
Step 5: Find the length of all the words in the list
Step 6: Find the longest words present in the list
Step 7: Print all the longest words
Step 8: Stop
PROGRAM:
filedata.close()
77
OUTPUT:
Ex 09\TextFileEx09c.txt
At the stroke of the midnight hour, when the world sleeps, India will awake to
life and freedom. A moment comes, which comes but rarely in history, when we
step out from the old to the new, when an age ends, and when the soul of a
nation, long suppressed , finds utterance . It is fitting that at this solemn
moment we take the pledge of dedication to the service of India and her people
and to the still larger cause of humanity.
['suppressed', 'dedication']
RESULT:
The Python program to find the longest words present in a file was successfully executed.
78
10a. IMPLEMENTING EXCEPTION HANDLING – DIVIDE BY ZERO
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Get the numerator from the user
Step 3: Get the denominator from the user
Step 4: Divide the numerator by the denominator using a try catch block
Step 5: If the denominator is non-zero, display the result to the user
Step 6: If the denominator is zero, catch the exception and print the message
Step 7: Stop
PROGRAM:
try:
result = numerator / denominator
print ("The result is : ", result)
except ZeroDivisionError as e:
print ("Exception Caught : ", e)
79
OUTPUT:
RESULT:
The Python program to handle exceptions when a number is divided by zero was successfully
executed.
80
10b. IMPLEMENTING EXCEPTION HANDLING – VOTER AGE VALIDATION
Date:
AIM:
To write a Python program to validate the age of a voter using exception handling
ALGORITHM:
Step 1: Start
Step 2: Get the age of the voter
Step 3: Using a try catch block, check if the age is less than 18 and if true, raise an
exception
Step 4: Catch the raised exception and print the output that the voter is not eligible
Step 5: If age > 18, print that the voter is eligible to vote
Step 6: Stop
PROGRAM:
try:
if (age < 18):
raise ValueError()
except ValueError:
print("You must be 18 years or more to vote!")
else:
print("You are eligible to vote")
81
OUTPUT:
RESULT:
The Python program to validate the age of a voter using exception handling was successfully
executed.
82
10c. IMPLEMENTING EXCEPTION HANDLING – STUDENT MARK RANGE
VALIDATION
Date:
AIM:
To write a Python program to validate the subject marks of a student using exception
handling
ALGORITHM:
Step 1: Start
Step 2: Get 3 subject marks of the student
Step 3: Using a try catch block, check if the marks are within the range 0 t0 100
Step 4: If the marks are out of range, raise an exception.
Step 5: Catch the raised exception and print that the marks are out of range
Step 6: Else, print the subject marks of each subject
Step 7: Stop
PROGRAM:
marks = []
marks.append(mark1)
marks.append(mark2)
marks.append(mark3)
83
for count, mark in enumerate(marks):
try:
if (mark < 0 or mark > 100):
raise ValueError()
except ValueError:
print("Your Subject" , count+1, "marks must be in the range 0 - 100")
else:
print("Your Subject" , count+1, "mark is : ", mark)
OUTPUT:
RESULT:
The Python program to validate the subject marks of a student using exception handling was
successfully executed.
84
11. EXPLORING THE PYGAME TOOL
Date:
AIM:
INTRODUCTION:
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.
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.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.
85
ALGORITHM:
Step 1: Start
Step 2: Import the pygame library
Step 3: Initialize the pygame module
Step 4: Set the screen size
Step 5: Loop till events are received
Step 6: If the event type is Quit, exit the window
Step 7: Display the pygame window
Step 8: Stop
PROGRAM:
import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
86
OUTPUT:
RESULT:
The Python program to create a basic Pygame window was successfully executed.
87
12a. IMPLEMENTING BOUNCING BALL ANIMATION USING PYGAME
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import and initialize the Pygame library
Step 3: Set the drawing mode and the window size as appropriate
Step 4: Set the speed of the moving ball in x & y co-ordinates
Step 5: Load the image of the ball, which needs to be animated
Step 6: Set the rectangular boundaries inside which the ball needs to be moved
Step 7: Move the ball with the assigned speed till it hits any boundary edge
Step 8: If the ball collides with any of the four edges, then change the direction of the ball
Step 9: Update the display
Step 10: Continue the animation till the user quits the program
Step 11: Stop
PROGRAM:
screen = pygame.display.set_mode(size)
88
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
89
OUTPUT:
RESULT:
The Python program to implement a bouncing ball animation using pygame was successfully
executed.
90
12b. IMPLEMENTING CAR RACING GAME USING PYGAME
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Initialize the pygame modules
Step 3: Load the game assets
Step 4: Map the left and right keys to the user car
Step 5: Generate and move police cars at random and move it from top towards the user
car
Step 6: Evade the user car from colliding with the oncoming cars
Step 7: If a collision is detected, end the game
Step 8: Stop
PROGRAM:
#import for the random library to randomize the car coming from the opposite
side.
import random
#initiate package
pygame.init()
91
#color code in RGB form
gray=(60,60,60)
#color code in RGB form
black=(255,0,0)
#set width & height of the display
display=pygame.display.set_mode((830,600))
#set name of the game window
pygame.display.set_caption("Car Racing Game")
#define police car functions that are coming from the opposite side.
def policecar(police_startx,police_starty,police):
if police==0:
#for police car no 2
police_come=pygame.image.load("Ex 12/Car Game/car2.png")
if police==1:
#for police car no 3
police_come=pygame.image.load("Ex 12/Car Game/car3.png")
if police==2:
#for police car no 1
92
def background():
#defining the position of background image for left side in x axis & y
axis
display.blit(backgroundleft,(0,0))
#defining the position of background image for right side in x axis & y
axis
display.blit(backgroundright,(700,0))
#creating the function that will display the game over message
def crash():
message_display("Game Over")
#This function will display the message after the car has crashed.
def text_object(text,font):
#set color of the message
text_surface=font.render(text,True,black)
#after that restart the game & ready to give some input
93
return text_surface,text_surface.get_rect()
94
#defining the input of the game
for event in pygame.event.get():
#if quit input is given
if event.type==pygame.QUIT:
# bumped=True #game will stop
pygame.quit()
quit()
95
#if the car goes out of range(side wall of the road)
if x<130 or x>700-car_width:
#bumped=True #game is over
#call crash function
crash()
#if the police car does not cross the road then crash the car
if y<police_starty+police_height:
if x > police_startx and x < police_startx + police_width or x +
car_width > police_startx and x + car_width < police_startx +
police_width :
crash()
96
OUTPUT:
RESULT:
The Python program to implement a car racing game using pygame was successfully
executed.
97
98