0% found this document useful (0 votes)
9 views60 pages

Python Lab

The document outlines a series of programming exercises including basic arithmetic operations, Fibonacci series, FizzBuzz program, crowd computing, jumbled words game, and birthday paradox. Each exercise includes an aim, algorithm, program code, and a statement confirming successful execution. The programs are designed to demonstrate fundamental programming concepts and logic in Python.

Uploaded by

seojain2013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views60 pages

Python Lab

The document outlines a series of programming exercises including basic arithmetic operations, Fibonacci series, FizzBuzz program, crowd computing, jumbled words game, and birthday paradox. Each exercise includes an aim, algorithm, program code, and a statement confirming successful execution. The programs are designed to demonstrate fundamental programming concepts and logic in Python.

Uploaded by

seojain2013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

220282601105

EX NO:1
DATE:03/8/2023 ADDITION, SUBTRACTION, MULTIPLICATION AND DIVISION

1. Write a program for addition, subtraction, multiplication and division of


two numbers

AIM: Write a program for addition, subtraction, multiplication


and division of two numbers.

ALGORITHM:

STEP 1: Display choice of operation in screen, “Choice 1: Add,


2: Sub,3: Div, 4: Mul, 5:Quit “.
STEP 2: Receive input choice from the user.
STEP 3: Convert the input to integer (val= int (val1)).
STEP 4: If choice of option is 1 then receive input for num1
and num2, Initiate operation num3 =num1 + num2.
STEP 5: If choice of option is 2 then receive input for num1
and num2, Initiate operation num3 = num1 – num2.
STEP 6: If choice of option is 3 then receive input for num1
and num2, Initiate operation num3 =num1 / num2.
STEP 7: If choice of option is 4 then receive input for num1
and num2, Initiate operation num3 = num1 * num2.

1
220282601105

PROGRAM:
print("Choice 1: Add, 2: Sub, 3: Div, 4: Mul, 5: Quit")
val1 = input("Enter the choice of operation :")
val = int(val1)
if(val == 1):
print("You have chosen addition Option :")
n1 = input("Enter the value for n1 :")
n2 = input("Enter the value for n2 :")
num1 = int(n1)
num2 = int(n2)
num3 = num1 + num2
print("The Result:",num1,"+",num2,"=",num3)
elif (val == 2):
print("You have chosen subtraction Option :")
n1 = input("Enter the value for n1 :")
n2 = input("Enter the value for n2 :")
num1 = int(n1)
num2 = int(n2)
num3 = num1 - num2
print("The Result:",num1,"-",num2,"=",num3)
elif (val == 3):
print ("You have chosen division Option :")
n1 = input("Enter the value for n1 :")
n2 = input("Enter the value for n2 :")
num1 = int(n1)
num2 = int(n2)
num3 = num1/num2
print("The Result:",num1,"/",num2,"=",num3)
elif (val == 4):
print("You have chosen multiplication Option :")
n1 = input("Enter the value for n1 :")
n2 = input("Enter the value for n2 :")

2
220282601105

num1 = int(n1)
num2 = int(n2)
num3 = num1*num2
print("The Result:",num1,"*",num2,"=",num3)
elif (val==5):
print ("You have given a wrong option:", n)
exit ()

3
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and

verified.

4
220282601105

EX NO:2i)
DATE:10/8/2023 FIBONACCI SERIES

2i).Write a program to print Fibonacci number series

AIM: Write a program to print Fibonacci number series.

ALGORITHM:

“Fibonacci Series is a number series, where each number is a addition of


preceding two number” (ie . if n= 5 then Fibonacci number series are : 0,1,1,2,3.).

STEP 1: Display “ Fibonacci Series “

STEP 2: Prompt the user to enter the number (ie. 1 to i , any

integer number).

STEP 3: Since python accept any input in string format, change

the input n1 from string to integer n (ie. i = int(val)).

STEP 4: If received input is greater than zero then:Initialize f=0,

s=1, j =0 and next = 0( ie.f-means first value , s-means

second value & next means next value)

5
220282601105

STEP 5: While the value of j is in the range of 0 to i+1 then


Check whether j <=1 : if yes, then
Print the value of j (ie : 0).
If j is not less than 1 then
Next value is addition of f and s.
Swap the value for f and s (ie. f = s, s = next)
Print the value in next variable
Increment the j = j +1
Break.
STEP 6: If received input is not integer then display “You have
entered wrong input”.

6
220282601105

PROGRAM:

print ("Fibonacci Series")

val = input("Enter the number :")

i = int(val)

if (i>0):

f=0

s=1

j=0

next = 0

while (1):

print ("\n\n*******************************************")

for j in range (i+1):

if (j <= 1):

print(j)

else:

next = f + s

f=s

s = next

print (next)

7
220282601105

j=j+1

break

else:

print ("You have entered wrong input", i)

8
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and

verified.

9
220282601105

EX NO:2ii)
DATE:17/8/23 FIZZ BUZZ PROGRAM

2ii).Write a program to incorporate FIZZ for any number divisible by 3 and


Buzz for any number divisible for 5 and FIZZBUZZ for any number divisible
by 3 and 5 as well.

AIM: Write a program to incorporate FIZZ for any number

divisible by 3 and Buzz for any number divisible for 5

and FIZZBUZZ for any number divisible by 3 and 5

as well.

ALGORITHM:

STEP 1: Print “FizzBuzz Program”

STEP 2: Prompt for user input for value var1

STEP 3: Convert the received value var1 to integer value var

STEP 4: Create a loop which will execute from 0 to var+1 times.

If k modules 3 and I modules 5 is zero then

Print k value + “= FIZZBUZZ”

If k modules 3 is zero then

Print k value + “= FIZZ”

If k modules 5 is zero then

Print k value + “= Buzz”

else

Print k Value

10
220282601105

PROGRAM:

print ("Fizz Buzz Program :")

var1 = input("Enter the number : ")

var = int(var1)

k=0

for k in range (var+1):

if (k % 3 == 0 and k % 5 == 0):

print (str(k) + "= Fizz Buzz")

elif (k % 3 == 0):

print (str(k) + "= Fizz")

elif (k % 5 == 0):

print (str(k) + "= Buzz")

else:

print(k)

11
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and

verified.

12
220282601105

EX NO:3
DATE:24/8/23 CROWD COMPUTING

[Link] a program to collect approximate cost for a material or object and


store the same in the array. Remove first and last 10 % of the listed cost
from the array and compute the mean value of the array items.

AIM: Write a program to collect approximate cost for a material or object and
store the same in the array. Remove first and last 10 % of the listed cost from
the array and compute the mean value of the array items.

ALGORITHM:

STEP 1: Print “CROWD COMPUTING”

STEP 2: Create an array name “Predicted_values” and store list

of items.

STEP 3: Print the values stored in array elements

STEP 4: Use the library statistics and import mean “from

statistics import mean”

STEP 5: Remove first and last 10 % of the listed cost from the array

STEP 6: Print the values stored in array elements after removal

of the first and last 10% of the listed values.

STEP 7: Calculated the mean value of the array items.

13
220282601105

PROGRAM:

from statistics import mean

print ("CROWD COMPUTING")

print ("***************")

Predicted_Values=[200,100,250,375,300,500,800,900,200,100,600,2700,150,1
00,90,250,300,350,363,397,450,500,700,275,125,125,185,225,240,310,415,3
00,250,300,2000,2500]

k=0

for k in range (len(Predicted_Values)):

print (Predicted_Values[k])

Predicted_Values.sort()

print ("SORTED VALUES")

for k in range (len(Predicted_Values)):

print (Predicted_Values[k])

val = int (0.1 * len(Predicted_Values))

Predicted_Values = Predicted_Values [val:]

Predicted_Values = Predicted_Values [:len(Predicted_Values)-val]

print ("COMPUTER VALUES")

14
220282601105

for k in range (len(Predicted_Values)):

print (Predicted_Values[k])

print ("*********************************")

print ("\t",mean(Predicted_Values))

print ("*********************************")

15
220282601105

OUTPUT:

16
220282601105

17
220282601105

18
220282601105

RESULT: Thus, the program has been successfully executed and

verified.

19
220282601105

EX NO:4
DATE:31/8/23 JUMBLED WORDS

[Link] a program to create a play game called jumbled word.

AIM: Write a program to create a play game called jumbled word.

ALGORITHM:

STEP 1: Prompt the user to enter input for player name 1 & 2

STEP 2: Initialize the game points variable pp1 & pp2 = 0 for

player 1 & 2.

STEP 3: Initialize the game turn variable turn = 0

STEP 4: Create a while loop to run a set of code for infinite times.

STEP 5: pick a word to play, use call function choose ()

“def choose ():


#creates array variable ‘words’ and assigned a list of
words to be used in the game
#import random library to use [Link] operation
words=['rainbow','computer','water','ice','type','light',
'zebra','arab','atlanta','khan']
#Use [Link] function to pick a word from the
list of words stored in the array ‘words’ and assign to
the variable ‘pick’ & return the value of variable pick
to the called variable.
pick = [Link](words)
return pick”
STEP 6: After a random word is picked then use a call

20
220282601105

function jumble () and pass picked word along

with the call function to create a jumbled word for

the picked word.

“# Create a function called jumble with parameter variable word to


receive value from the calling function.
def jumble (word):
# Use [Link] function to shuffle the picked word and
return the shuffled word.
jumbled = "".join([Link](word,len(word)))
return jumbled”

STEP 7: Assign the jumbled or shuffled word to the variable

called qn.

STEP 8: If modulus of turn variable is 0 when divisible by 2

then player 2 will play else player 1 will play.

STEP 9: Prompt the qn variable as a question for the jumbled

word to the user and receive the input from the user

into ans variable.

STEP 10: Use if condition to check qn and ans are equal. If

equal then increase points of the concern player

and increase the turn variable to 1.

21
220282601105

PROGRAM:

import random
def choose()
words=['rainbow','computer','water','ice','type','light','zebra',
'arab','atlanta','khan']
pick = [Link](words)
return pick

def jumble (word):


jumbled = "".join([Link](word,len(word)))
return jumbled

def thank (p1n,p2n,p1,p2):


print (p1n, " Your Score is :", p1)
print (p2n," Your Score is :", p2)
print (" Thanks for Playing")

def play():
p1name = input("Enter the name of Player 1 :")
p2name = input("Enter the name of Player 2 :")
pp1 = 0
pp2 = 0
turn = 0

while (1):
picked_word = choose()
qn = jumble(picked_word)
print ("\n\n\t\t The question is :",qn)
#player 2
if (turn % 2 == 0):
print ("\n\n\t\t",p2name, "Your Turn")

22
220282601105

ans = input ("Enter the answer")


if (ans == picked_word):
pp2 = pp2 + 1
print (" The Question was :", qn)
print (" The Answer you Given : ", ans)
print (" You have given the right answer ! congratulation")
else:
print (" You have given the wrong answer ! Better
Luck Next Time")
c1 = input (" Press 1 to continue or 0 to quit")
c = int(c1)
if ( c == 0):
thank (p1name,p2name,pp1,pp2)
break
else:
print ("\n\n\t\t",p1name, "Your Turn")
ans = input ("Enter the answer")
if (ans == picked_word):
pp1 = pp1 + 1
print (" The Question was :", picked_word)
print (" The Answer you Given : ", ans)
print (" You have given the right answer ! congradulation")
else:
print (" You have given the wrong answer ! Better Luck Next Time")
c1 = input (" Press 1 to continue or 0 to quit")
c =int(c1)
if ( c == 0):
thank (p1name,p2name,pp1,pp2)
break
turn = turn + 1
play()

23
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and

verified.

24
220282601105

EX NO:5
DATE:7/9/23 BIRTHDAY PARADOX

[Link] a program to random generate 50 birth dates and find how many of
have same day of the year.

AIM: Write a program to random generate 50 birth dates and

find how many of have same day of the year.

ALGORITHM:

STEP 1: Create an array variable birthday without any

array elements

STEP 2: Create a while loop to execute 50 times and

generate year,month,day

STEP 3: Create a variable dd and store year,month and day

using [Link] function

STEP 4: Convert the birthdate stored in the dd variable to day of

the year using [Link]().tm_yday and store it in

the variable day_of_year

STEP 5: Append the day_of_year into the array birthday []

(i.e. [Link] [day_of_year])

25
220282601105

STEP 6: Similarly generate another 49 values for

Variable day_of_year and append the same

in the array birthday.

STEP 7: Sort the array elements using sort function

(i.e. [Link]())

STEP 8: Print all the elements in the birthday array. You can

easy notice elements having same day of the year.

26
220282601105

PROGRAM:
import random
import datetime
birthday = []
i=0
while (i < 50):
year = [Link](1875, 2019)
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
leap = 1
else:
leap = 0
month = [Link](1, 12)
if (month == 2 and leap == 1):
day = [Link](1, 29)
print(day)
elif (month == 2 and leap == 0):
day = [Link](1, 28)
elif (month ==7 and month ==8):
day = [Link](1, 31)
elif (month % 2 != 0 and month < 7):
day = [Link](1, 31)
elif (month % 2 != 0 and month < 7 and month<12):
day = [Link](1, 30)
else:
day = [Link](1, 30)
dd = [Link](year, month, day)
day_of_year = [Link]().tm_yday
i=i+1
[Link](day_of_year)

27
220282601105

[Link]()
i=0
while( i < 50):
print(birthday[i])
i=i+1

28
220282601105

OUTPUT:

29
220282601105

RESULT: Thus, the program has been successfully executed and


verified.

30
220282601105

EX NO:6
DATE:14/9/23 LISTS

[Link] a program for the following:


i) Display of list with elements.
ii) Finding the range of the lists.
iii) Indexing in the lists(including negative indexing)
iv) Use of loop in the lists.
v) Adding,removing and joining two lists.

PROGRAM:

i) Display of list with elements.

thislist=["Blockchain","Bigdata","Java"]
print(thislist)

OUTPUT:

ii) Finding the range of the lists.

thislist=["Blockchain","Bigdata","Java","Python","Fullstack","Crm",
"Maths"]
print(thislist[2:5])

31
220282601105

OUTPUT:

iii) Indexing in the lists(including negative indexing)

A) Positive indexing:

thislist=["Blockchain","Bigdata","Java"]
print(thislist[1])

OUTPUT:

B) Negative indexing:

thislist=["Blockchain","Bigdata","Java"]
print(thislist[-1])

OUTPUT:

iv) Use of loop in the lists.

thislist=["Blockchain","Bigdata","Java"]
for x in thislist:
print(x)

32
220282601105

OUTPUT:

v) Adding,removing and joining two lists.

A) Adding lists:

thislist=["Blockchain","Bigdata","Java"]
[Link]("Python")
print(thislist)

OUTPUT:

B) Removing lists:

thislist=["Blockchain","Bigdata","Java"]
[Link]("Bigdata")
print(thislist)

OUTPUT:

C) Joining two lists:

list1=["i","j","k"]
list2=[100,101,102]
list3=list1+list2
print(list3)

33
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and


verified.

34
220282601105

EX NO:7
DATE:21/9/23 TUPLES

[Link] a program for the following:


i) Creation of tuple with values.
ii) Finding the range of the tuple.
iii) Indexing in the tuple(including negative indexing)
iv) Use of loop in the tuple.
v) Adding,removing and joining two tuple.

PROGRAM:
i) Creation of tuple with values.
my_tuple=3,4.6,"dog"
print(my_tuple)
a,b,c=my_tuple
print(a)
print(b)
print(c)

OUTPUT:

ii) Finding the range of the tuple.


my_tuple=('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:5])
print(my_tuple[:-7])
print(my_tuple[7:])
print(my_tuple[:])

35
220282601105

OUTPUT:

iii) Indexing in the tuple(including negative indexing)

Positive indexing:

my_tuple=('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
n_tuple=("mouse",[8,4,6],(1,2,3))
print(n_tuple[0][3])
print(n_tuple[1][1])
OUTPUT:

Negative indexing:

my_tuple=('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])

OUTPUT:

36
220282601105

iv) Use of loop in the tuple.

thistuple=("Java","Python","Html")
for x in thistuple:
print(x)

OUTPUT:

v) Adding,removing and joining two tuple.

A) Adding tuple:

a=('2',)
items=['o','k','d','o']
l=list(a)
for x in items:
[Link](x)
print(tuple(l))

OUTPUT:

37
220282601105

B) Removing tuple:

tuple1 = ("apple", "banana", "cherry")


del tuple1
print(tuple1)

OUTPUT:

C) Joining two tuple:

tuple1=("a","b","c")
tuple2=(1,2,3)
tuple3=tuple1+tuple2
print(tuple3)

OUTPUT:

RESULT: Thus, the program has been successfully executed and


verified.

38
220282601105

EX NO:8
DATE:5/10/23 DICTIONARY

[Link] a program for the following:


i) Display of unordered elements.
ii) Accessing the elements in the dictionary.
iii) Use of loop in the dictionary.
iv) Adding,removing and joining two dictionary.

PROGRAM:

i) Display of unordered elements.

d={}
d['b']='beta'
d['g']='gamma'
d['a']='alpha'

for k,v in [Link]():


print(k)

OUTPUT:

39
220282601105

ii) Accessing the elements in the dictionary.

country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}

print(country_capitals["United States"])

print(country_capitals["England"])

OUTPUT:

iii) Use of loop in the dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)

OUTPUT:

40
220282601105

iv) Adding, removing and joining two dictionary.


A) Adding dictionary:
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# add an item with "Germany" as key and "Berlin" as its value
country_capitals["Germany"] = "Berlin"

OUTPUT:

B) Removing dictionary:
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Dictionary =")
print(Dict)
#Deleting some of the Dictionar data
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)

OUTPUT:

41
220282601105

C) Joining two dictionary:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z=x|y
print(z)

OUTPUT:

RESULT: Thus, the program has been successfully executed


and verified.

42
220282601105

EX NO:9
DATE:12/10/23 SPEECH TO TEXT

[Link] a python program to convert speech to text.

AIM: Write a python program to convert speech to text.

ALGORITHM:

STEP 1: Install Speech Recognition API of Google using


anaconda command prompt type the command
“pip install SpeechRecognition”
STEP 2: Import speech_recognition library as sr
STEP 3: Create a audio file with WAV extension and assign
the audio file to a source variable
STEP 4: Intitialize recognizer
STEP 5: Read the audio file using the [Link](source_
file _name)
STEP 6: print the audio file using print statement.

43
220282601105

PROGRAM:
import speech_recognition as sr
AUDIO_FILE = "[Link]"
# Initialize Recognizer
r = [Link]()
# Use the audio file as the source
with [Link](AUDIO_FILE) as source:
audio = [Link](source) # Read the audio file
try:
# Try to recognize speech using Google Speech Recognition
print("Audio file contains: " + r.recognize_google(audio))
except [Link]:
# Handle the case where Google Speech Recognition could not understand
the audio
print("Google Speech Recognition did not understand the file uploaded")
except [Link]:
# Handle the case where there's an issue with the Google Speech
Recognition service
print("Couldn't get the result from Google Recognition")

44
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and


verified.

45
220282601105

EX NO:10
DATE:19/10/23 MONTE HALL_3 - DOORS AND A TWIST

[Link] a program to create a game “MONTE HALL _ 3 - DOORS AND A


TWIST”. This comprises of three doors. In which two doors contain GOAT
and one door contain BMW. User has to pick his/her choice of door. If the
choice of door contains BMW then user WINS otherwise LOST.

AIM: Write a program to create a game “MONTE HALL _ 3 - DOORS AND A


TWIST”. This comprises of three doors. In which two doors contain GOAT and
one door contain BMW. User has to pick his/her choice of door. If the choice of
door contains BMW then user WINS otherwise LOST.

ALGORITHM:

STEP 1: Importing random library as we are using random.


choice in the program
STEP 2: Create an array doors [0] * 3(Initializing the array as
doors [0] = 0, doors [1] = 0, doors [2] = 0
STEP 3: Create an array goatdoors= []
STEP 4: Initializing a variable swap = 0 , don’t_swap= 0 & j =0
STEP 5: Create a while loop to execute the loop instructions for
10 times
STEP 6: Declaring a variable x and initializing with random
number from 0 to 2
STEP 7: Passing the value of x as an array item number to
array variable doors[] and store “BMW” i.e doors[0
or 1 or 2]=”BMW

46
220282601105

STEP 8: Create a for loop with variable i to execute three times


( for I in range (0,3))and check if i equals to x
then continue, otherwise store “Goat” in array doors[]
(i.e doors[i]=”Goat”)
STEP 9: Accept user choice of input to the variable choice,
user input choice to be 0 or 1 or 2
STEP 10: Open a door that comprises of goat by creating a
variable door_open and apply [Link]
function to select a random item from array
goatdoor[] and store it in door_open variable. i.e
door_open=[Link](goatdoor)
STEP 11: Accept user choice of swap to the variable ch as either
Y or n, i.e yes or no.
STEP 12: If user choice for swap is yes (i.e ch== ‘y’), then
check user given choice door contain “Goat”. If
user door choice contains “Goat” then declare
user “Players wins”. Increment swap variable with 1.
STEP 13: If user choice for swap is no (i.e ch== ‘n’), then check
user given choice door contain “Goat”. If user
door choice contains “Goat” then declare user
“Players wins”. Increment swap variable with 1.
STEP 14: Increment j = J +1
STEP 15: Print “no of swap wins” and “ no of don’t swap wins”.

47
220282601105

PROGRAM:
import random
doors = [0]*3
goatdoor = [] * 2
swap = 0 # No of swap wins
dont_swap = 0 # No of don't swap wins
j=0
while j < 5:
x = [Link](0, 2) # xth door will comprise of BMW
doors[x] = "BMW"
for i in range(0, 3):
if i == x:
continue
else:
doors[i] = "Goat"
[Link](i)

choice = int(input("Enter your choice 0, 1, 2: "))


door_open = [Link](goatdoor) # open a door that comprises of goat

while(door_open == choice):
door_open = [Link](goatdoor)

ch = input("Do you want to swap? y/n: ")

if ch == 'y':
if doors[choice] == 'Goat':
print("Player wins")
swap = swap + 1
else:
print("Player lost")
else:

48
220282601105

if doors[choice] == 'Goat':
print("Player lost")
else:
print("Player wins")
dont_swap = dont_swap + 1

j=j+1

print("No of swap wins", swap)


print("No of don't swap wins", dont_swap)

49
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and


verified.

50
220282601105

EX NO:11
DATE:26/10/23 PLOTS

[Link] a program to plot values in chart with x-axis and y-axis.


AIM: Write a program to plot values in chart with x-axis
and y-axis.
ALGORITHM:
STEP 1: Import plotting library <[Link]>as plt
STEP 2: print “ * PLOTTING VALUES IN CHART WITH X-AXIS
AND Y-AXIS *”
STEP 3: Plot values X-Axis (1,2,3,4) and Y-Axis ( 10,13,20,25)
with blue Square symbol

51
220282601105

PROGRAM:

import [Link] as plt


print("*******************************************************************")
print("* *")
print("* PLOTTING VALUES IN CHART WITH X-AXIS AND Y-AXIS *")
print("* *")
print(“*******************************************************************")
[Link]([1,2,3,4],[10,13,20,25],'bs')

52
220282601105

OUTPUT:

RESULT: Thus, the program has been successfully executed and


verified.

53
220282601105

EX NO:12
DATE:2/11/23 PANDAS DATAFRAME

[Link] a python program using pandas library to Perform


the following operation.
• Create DataFrame
• Manipulate the values in DataFrame
• Barcharts
• Pie Charts
• Scatter Plots

AIM: Write a python program using pandas library to Perform


the following operation.
• Create DataFrame
• Manipulate the values in DataFrame
• Barcharts
• Pie Charts
• Scatter Plots

ALGORITHM:

STEP 1: Import the Pandas library and Matplotlib for plotting.


STEP 2: Create a dictionary with data for the DataFrame,
including 'Age,' 'Weight,' and 'Blood pressure.'
STEP 3: Manipulate the values in the dataframe ( Split the
Blood Pressure column into two columns and
Calculate BMI)
STEP 4: Display the modified Dataframe

54
220282601105

STEP 5: Generate a bar chart for BMI, a pie chart for


Systolic Blood Pressure, and a scatter plot for
BMI vs Systolic Blood Pressure
GDP growth.
STEP 6: Display the plots using [Link]().

55
220282601105

PROGRAM:
import pandas as pd
import [Link] as plt
# Create a DataFrame
data = {'Patient': ['John Doe', 'Jane Doe', 'Peter Parker', 'Mary Jane Watson',
'Bruce Wayne'],
'Age': [35, 25, 20, 18, 45],
'Weight': [80, 60, 70, 55, 90],
'Systolic Blood Pressure': [120, 110, 130, 100, 140],
'Diastolic Blood Pressure': [80, 70, 90, 60, 100]}
df = [Link](data)

# Display the Original DataFrame


print("Original DataFrame:")
print(df)
print("\n")

# Split the Blood Pressure column into two columns


df['Systolic Blood Pressure'] = pd.to_numeric(df['Systolic Blood Pressure'])
df['Diastolic Blood Pressure'] = pd.to_numeric(df['Diastolic Blood Pressure'])

# Calculate BMI
df['Height'] = 1.75 # Assume all patients are 1.75 meters tall
df['BMI'] = df['Weight'] / (df['Height'] * df['Height'])

# Display the modified DataFrame


print("Modified DataFrame:")
print(df)
print("\n")

56
220282601105

# Create a bar chart for BMI


[Link](kind='bar', x='Patient', y='BMI', title='BMI Bar Chart')
[Link]('Patient')
[Link]('BMI')
[Link]()

# Create a pie chart for Systolic Blood Pressure


[Link](y='Systolic Blood Pressure', labels=df['Patient'], autopct='%1.1f%%',
title='Systolic Blood Pressure Pie Chart')
[Link]()

# Create a scatter plot for BMI vs. Systolic Blood Pressure


[Link](kind='scatter', x='BMI', y='Systolic Blood Pressure', title='BMI vs.
Systolic Blood Pressure Scatter Plot')
[Link]('BMI')
[Link]('Systolic Blood Pressure')
[Link]()

57
220282601105

OUTPUT:

58
220282601105

59
220282601105

RESULT: Thus, the program has been successfully executed and


verified.

60

You might also like