You are on page 1of 63

Ex: No: 1 ELECTRICITY BILLING

Date:

AIM:

To write a program to generate electricity bill preparation using python language.

ALGORITHM:

Step 1: Start the Program.

Step 2: Read srlno, rcptno, billmonth, date

Step 3: Read Present and Previous meter Reading

Step 4: Consumed=Present-Previous

Step 5: Check if consumed >=200

Step 5.1: Total=Consumed*2.50 else

Step 5.2: Total=Consumed*1.50

Step 6: Print srlno, rcptno, billmonth, date

Step 7: Stop the execution.

PROGRAM:

print(“Enter Serial Number and Receipt Number:”)

srlno=int(input())

rcptno=input()

print(“Enter the Bill Month and Date:“)

billmonth=input()

date=input()

print(“Present and Previous Readings:”)

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(“\n\t ELECTRICITY BILL”)

print(“\t\t______________”)

print(“Serial Number”, srlno, “Receipt Number”, rcpt no)

print(“Bill Month:”, billmonth, “Date:”, date)

print(“Total cost for consumed”, consumed, “Unit is Rs.:”,total)


OUTPUT:

Enter Serial Number and Receipt Number:

9293

M1308

Enter Bill Month and Date:

07/2021

13/08/2021

Previous and Present Readings:

3000

1500

Consumed: 1500

ELECTRICITY BILL

Serial Number: 9293 Receipt Number: M1308

Bill Month: 07/2017 Date: 13/08/2021

Total cost for consumed 1500 Unit is Rs.: 3750.0

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:

x=int(input(“Read value for x:”))


y= int(input(“Read value for y:”))
print(“Values for x and y before swapping:”, x,y)
temp = x
x=y
y = temp
print("Values of x and y after swapping:", x,y)

OUTPUT:
Read value for x: 50

Read value for y: 10

Values for x and y before swapping: 50, 10

Values for x and y before swapping: 10, 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:

n = int(input("Enter number of values : "))

list1 = []

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

x = int(input("Enter integer : "))

list1.append(x)

print("Circulating the elements of list: ", list1)

for val in range(0,n,1):

x = list1.pop(0)

list1.append(x)

print(list1)
OUTPUT

Enter number of values: 3

Enter integer: 1

Enter integer: 2

Enter integer: 3

Circulating the elements of list: [1.2.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:

x1, y1=eval(input("enter x1 and y1 for point 1: "))


x2,y2 =eval(input("enter x2 and y2 for point 2: "))
distance= ((x1 – x2 )* (x1 – x2 ) + (y1-y2)* (y1-y2)) **0.5
print("The distance between the two points is : ",distance)

OUTPUT :

enter x1 and y1 for point 1: 1,2

enter x2 and y2 for point 2: 2,4

The distance between the two points is: 2.23606797749979

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: Let iand j be an integer numbers.

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.

Step 6: Stop the algorithm

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

extend() adds all elements of a list to another list

insert() inserts an item at the defined index

remove() removes an item from the list

pop() returns and removes an element at the given index

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

Python Expression Results Description

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

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

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

In Returns True if a sequence with the specified value x in y


is present in the object

not in Returns True if a sequence with the specified value x not in y


is not present in the object

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

Create and print a dictionary


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
clear():Remove all elements from the car list

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Output:
{}

copy():Copy the car dictionary


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

fromkeys():Create a dictionary with 3 keys, all with the value 0


x = ('key1', 'key2', 'key3')
y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Output:
['key1': 0, 'key2': 0, 'key3': 0]

get():Get the value of the "model" item


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)
Output:
Mustang

items():Return the dictionary's key-value pairs


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
Output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

keys():Return the keys


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Output:
dict_keys(['brand', 'model', 'year'])

pop():Remove "model" from the dictionary


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Output:
{'brand': 'Ford', 'year': 1964}

popitem():Remove the last item from the dictionary


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)

Output:
{'brand': 'Ford', 'model': 'Mustang'}

setdefault():Get the value of the "model" item


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Output:
Mustang
update():Insert an item to the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}

values():Return the values


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)

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:

To write a program to find the factorial of a number using functions in python.

ALGORITHM:

Step 1: Start the program.

Step 2: Set initial value to fact=1, i=1

Step 3: Read the value of n

Step 4: while (i<=n) then

Step 5: fact = fact * i

Step 6: i = i + 1

Step 7: Repeat the step 4,5,6 until the condition became false

Step 8: Print the value of fact

Step 9: Stop the program


PROGRAM:
def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

# take input from the user

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

# check is the number is negative

if num < 0:

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

elif num == 0:

print("The factorial of 0 is 1")

else:

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

OUTPUT:
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 1- Declare a function that will 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 or take input

Step 5- Call the function and print the value returned by it

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:

Enter size of list 6


Enter element of list 4
Enter element of list 8
Enter element of list 9
Enter element of list 2
Enter element of list 3
Enter element of list 1
Largest in [4,8,9,2,3,1] is 9

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

Step 3: Give the formula for area.

Step 3: Print the value of area.

Step 4:.Call the function and print the value returned by it

Step 5: Stop the algorithm

PROGRAM:
def AreaofRectangle(width, height):

Area = width * height

print("Area of a Rectangle is: %.2f" %Area)

AreaofRectangle(8, 6)

OUTPUT:

Area of a Rectangle is: 48.00

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.

Step 5:It printed the result to the screen.

Step 6: Stop the algorithm

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

str = "JavaTpoint" # Given String


print("The original string is: ",str)
print("The reverse string is",reverse_string(str)) # Function call

OUTPUT:

('The original string is: ', 'JavaTpoint')


('The reverse string is', 'tniopTavaJ')

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 original string


print("The original string is : " + str(test_str))

# isalpha() to computation of Alphabets


res = len([ele for ele in test_str if ele.isalpha()])

# printing result
print("Count of Alphabets : " + str(res))

OUTPUT:

The original string is :geeksforgeeks !!$ is best 4 all Geeks 10-0


Count of Alphabets : 27

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

and new character is the Modified String.

Step 4: Display the values of original and modified strings.

Step 5: Stop the algorithm.

PROGRAM:
str1 = input("Please Enter your Own String : ")

ch = input("Please Enter your Own Character : ")

newch = input("Please Enter the New Character : ")

str2 = str1.replace(ch, newch)

print("\nOriginal String : ", str1)

print("Modified String : ", str2)


OUTPUT:

Please Enter your Own String : hacking

Please Enter your Own Character: h

Please Enter the New Character: J

Original String: Hacking

Modified String: Jacking

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

To implement a python program using modules and libraries in Pandas.

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

Change the index Change the index values in a dataframe

Change the Column Change the headers of column


Headers

Data Munging Convert a particular data into a different format

PROGRAM

Slicing the Data Frame


import pandas as pd
XYZ_web= {'Day':[1,2,3,4,5,6], "Visitors":[1000, 700,6000,1000,400,350], "Bounce_Rate":[20,20,
23,15,10,34]}
df= pd.DataFrame(XYZ_web)
print(df.head(2))
print(df.tail(2))
Output
Bounce_Rate Day Visitors
0 20 1 1000
1 20 2 700

Bounce_Rate Day Visitors


4 10 5 400
5 34 6 350

Merging

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])
merged= pd.merge(df1,df2,on ="HPI")
print(merged)

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

Change the Column Headers

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:

Output in HTML Format

RESULT:

Thus, the python program using modules and libraries in Pandas was executed and verified
successfully.
Ex No: 8B NUMPY

Date:

AIM

To implement a python program using modules and libraries in Numpy..

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]

Adding new dimensions

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

To implement a python program using modules and libraries in Matplotlib.

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:

# importing the required module


import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('My first graph!')

# function to show the plot


plt.show()
OUTPUT:

RESULT:

Thus, the python program using modules and libraries in Matplotlib was executed and verified
successfully.
Ex No: 8D SCIPY

Date:

AIM

To implement a python program using modules and libraries in SciPy.

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:

array([[ 1., 1., 1., 1.],


[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
RESULT:

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:

9A) COPY FROM ONE FILE TO ANOTHER

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:

A) DIVIDE BY ZERO ERROR


AIM:
To write a python program to implement divide by zero error using exception handling.
ALGORITHM:
Step 1: Start the Algorithm
Step 2: Read the values of n, d and c

Step 3:The try block test a block of code for errors and the except block handles the error.

Step 4:Assign q=n/(d-c) in try block.


Step 5: Display the value of quotient.
Step 6: If error occurs, then print division by zero.
Step 7: Stop the algorithm.
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:

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.

Step 4: Read the value of age in try block.


Step 5: If the age is greater than 18, then print eligible to vote. Otherwise, print not eligible to
vote.
Step 6: If the age is given as invalid, then Value Error Occurs.
Step 7: Stop the algorithm.
PROGRAM:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
#display exception's default error message
except ValueError as err:
print(err)
else:
# code to be executed when there is no exception
print("Thank you, you have successfully checked the voting eligibility")
main()
OUTPUT:
Enter your age 24
Eligible to vote
Thank you, you have successfully checked the voting eligibility

Enter your age thirty


invalid literal for int() with base 10: ' thirty'

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:

To write a program to validate students mark range using python.

ALGORITHM:

Step 1: Start the 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.

Step 4: Display the total and average values.

Step 5: Stop the algorithm.

PROGRAM:

class Student:

marks = []

def getData(self, rn, name, m1, m2, m3):

Student.rn = rn

Student.name = name

Student.marks.append(m1)

Student.marks.append(m2)

Student.marks.append(m3)
def displayData(self):

print ("Roll Number is: ", Student.rn)

print ("Name is: ", Student.name)

print ("Marks in subject 1: ", Student.marks[0])

print ("Marks in subject 2: ", Student.marks[1])

print ("Marks in subject 3: ", Student.marks[2])

print ("Marks are: ", Student.marks)

print ("Total Marks are: ", self.total())

print ("Average Marks are: ", self.average())

def total(self):

return (Student.marks[0] + Student.marks[1] +Student.marks[2])

def average(self):

return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

rn = int (input("Enter the roll number: "))

name = input("Enter the name: ")

m1 = int (input("Enter the marks in the first subject: "))

m2 = int (input("Enter the marks in the second subject: "))

m3 = int (input("Enter the marks in the third subject: "))

s1 = Student()

s1.getData(r, name, m1, m2, m3)

s1.displayData()
OUTPUT:

Enter the roll number: 10

Enter the name: Mahesh Kumar

Enter the marks in the first subject: 20

Enter the marks in the second subject: 30

Enter the marks in the third subject: 25

Roll Number is: 10

Name is: Mahesh Huddar

Marks are: [20, 30, 25]

Total Marks are: 75

Average Marks are: 25.0

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

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 (which is what python uses
to install packages). 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

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

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

pygame.display.flip()
Output:

After successful execution it will give the following window as an output:

The basic syntax of the above program line by line:

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 3: To set the caption of the window, call pygame.display.set_caption() function..

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.

Step 7:. flip() method is used to to make all image visible.

Step 8:.Stop the algorithm.


PROGRAM:
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import sys, pygame
from pygame.locals
import *
pygame.init()
speed = [1, 1]
color = (255, 250, 250)
width = 550
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame bouncing ball")
ball = pygame.image.load("ball.png")
rect_boundry = ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left< 0 or rect_boundry.right> width:
speed[0] = -speed[0]
if rect_boundry.top< 0 or rect_boundry.bottom> height:
speed[1] = -speed[1]
screen.fill(color)
screen.blit(ball, rect_boundry)
pygame.display.flip()
if event.type == QUIT:
pygame.quit()
sys.exit()
OUTPUT:

RESULT:

Thus, the bouncing ball game using Pygame was developed and executed successfully.

You might also like