16.
Write a program to add a new key-value pair to
existing dictionary. Aim:To write a program to add a
new key-value pair to existing dictionary
Description:
Add a key value pair using update():The code initializes a
dictionary dict and adds another dictionary dict1 using the
update() method, merging their key-value pairs.
Then, it adds a new key-value pair ( newkey1='portal' ) to the
dictionary by directly assigning it via update() . Add a key
value pair using update()
Program:
my_dict = {'name': 'Alice',
'age': 30} new_key = 'city'
my_dict[new_key] =
new_value print(my_dict)
Output: {'name':'Alice','age':30,'city':'Newyork'}
Result: The python program to add a new key-value pair to
existing dictionary was successfully executed.
18. Aim:To Write a program to sort words in a file and put
them in another file.The output file should have only lower-
case words, so any upper case words from source must be
lowered.
Description:
In this article, we are going to write a Python program
to copy all the content of one file to another file in
uppercase. In order to solve this problem, let’s see the
definition of some important functions which will be
used:
open() – It is used to open a file
in various modes like reading,
write, append, both read and
write.
write() – It is used to write a specified text to a file.
upper() – It is used to convert all
the lowercase letters to uppercase
letters of a string and finally returns
it.
Program:
# To open the first file in
read mode f1 =
open("sample file 1.txt",
"r")
# To open the second file in
write mode f2 =
open("sample file 2.txt", "w")
# For loop to traverse
through the file for line in f1:
# Writing the content of
the first # file to the
second file
# Using upper()
function to #
capitalize the letters
f2.write(line.upper())
Output:
Result: The program to sort words in a file and put them in
another file.The output file should have only lower-case
words, so any upper case words from source must be
lowered was successfully executed.
23. Aim:To Write a python program to create a class that
represents a shape, Include methods to calculate its area
and perimeter.Implement subclasses for different
shapes like circle,triangle,and square.
Description:
In this program, We will ask the user to input the shape’s
name. If it exists in our program then we will proceed to
find the entered shape’s area according to their respective
formulas. If that shape doesn’t exist then we will print
“Sorry! We cannot find this shape.” message on the screen.
we define a base class called Shape that provides the
blueprint for other shapes. It includes two methods,
calculate_area and calculate_perimeter, which are
overridden by subclasses.
The Circle class is a subclass of Shape and includes logic
designed to calculate the area and perimeter of a circle
using the provided radius.
Rectangles, another subclass of Shape, include length
and width attributes that enable them to calculate their
area and perimeter.
The Triangle class is also a subclass of Shape and
includes the necessary attributes (base, height, and
side lengths) to calculate a triangle's area and
perimeter.
In the example usage section, we create instances of each
subclass and call the calculate_area and
calculate_perimeter methods to obtain the area and
perimeter values. The results are then printed.
Program:
# Import the math module to access mathematical
functions like pi import math
# Define a base class called Shape to represent a generic shape
with methods for calculating area and perimeter
class Shape:
# Placeholder method for calculating area (to be
implemented in derived classes)
def
calculate_area(self
): pass
# Placeholder method for calculating perimeter (to be
implemented in derived classes)
def
calculate_perimeter(s
elf): pass
# Define a derived class called Circle, which inherits
from the Shape class class Circle(Shape):
# Initialize the Circle object with a
given radius def _init_(self,
radius):
self.radius = radius
# Calculate and return the area of the circle using
the formula: π * r^2 def calculate_area(self):
return math.pi * self.radius**2
# Calculate and return the perimeter of the circle using
the formula: 2π * r def calculate_perimeter(self):
return 2 * math.pi * self.radius
# Define a derived class called Rectangle, which inherits
from the Shape class class Rectangle(Shape):
# Initialize the Rectangle object with given
length and width def _init_(self, length,
width):
self.length = length
self.width = width
# Calculate and return the area of the rectangle using the
formula: length * width def calculate_area(self):
return self.length * self.width
# Calculate and return the perimeter of the rectangle using the
formula: 2 * (length + width)
def calculate_perimeter(self):
return 2 * (self.length + self.width)
# Define a derived class called Triangle, which inherits
from the Shape class class Triangle(Shape):
# Initialize the Triangle object with a base, height, and
three side lengths def _init_(self, base, height, side1,
side2, side3):
self.base = base
self.height =
height self.side1
= side1
self.side2 =
side2 self.side3
= side3
# Calculate and return the area of the triangle using the
formula: 0.5 * base * height def calculate_area(self):
return 0.5 * self.base * self.height
# Calculate and return the perimeter of the triangle by adding
the lengths of its three sides
def calculate_perimeter(self):
return self.side1 + self.side2
+ self.side3 # Example usage
# Create a Circle object with a given radius and calculate
its area and perimeter r = 7
circle = Circle(r)
circle_area =
circle.calculate_area()
circle_perimeter =
circle.calculate_perimeter() #
Print the results for the Circle
print("Radius of the circle:", r)
print("Circle Area:",
circle_area) print("Circle
Perimeter:", circle_perimeter)
# Create a Rectangle object with given length and width and
calculate its area and perimeter
l=5
w=7
rectangle = Rectangle(l, w)
rectangle_area =
rectangle.calculate_area()
rectangle_perimeter =
rectangle.calculate_perimeter() # Print
the results for the Rectangle print("\
nRectangle: Length =", l, " Width =",
w) print("Rectangle Area:",
rectangle_area)
print("Rectangle Perimeter:", rectangle_perimeter)
# Create a Triangle object with a base, height, and three side
lengths, and calculate its area and perimeter
base = 5
height = 4
s1 = 4
s2 = 3
s3 = 5
# Print the results for the Triangle
print("\nTriangle: Base =", base, " Height =", height, " side1
=", s1, " side2 =", s2, " side3 =", s3)
triangle = Triangle(base, height, s1,
s2, s3) triangle_area =
triangle.calculate_area()
triangle_perimeter =
triangle.calculate_perimeter()
print("Triangle Area:",
triangle_area) print("Triangle
Perimeter:", triangle_perimeter)
Output:
Radius of the circle: 7
Circle Area: 153.93804002589985
Circle Perimeter:
43.982297150257104
Rectangle: Length = 5 Width
= 7 Rectangle Area: 35
Rectangle Perimeter: 24
Triangle: Base = 5 Height = 4 side1 = 4 side2 = 3 side3 = 5
Triangle Area: 10.0
Triangle Perimeter: 12
Result: The python program to create a class that
represents a shape, Include methods to calculate its area
and perimeter.Implement subclasses for different shapes
like circle,triangle,and square was successfully completed.
24. Aim:To Write a python program to check whether a
JSON string contains complex object or not.
Description:
To read JSON data, you can use the built-in json module
(JSON Encoder and Decoder) in Python. The json module
provides two methods, loads and load, that allow you to
parse JSON strings and JSON files, respectively, to convert
JSON into Python objects such as lists and dictionaries.
Program:
import json
def
is_complex_num(
objct): if '
complex '
in objct:
return complex(objct['real'],
objct['img']) return objct
complex_object =json.loads('{" complex ": true, "real": 4,
"img": 5}', object_hook
= is_complex_num)
simple_object =json.loads('{"real": 4, "img": 3}', object_hook
= is_complex_num) print("Complex_object:
",complex_object)
print("Without complex object:
Complex_object: (4+5j)
Without complex object: {'real': 4,
'img':3}
",simple_object) Output:
Result: The python program to check whether a JSON
string contains complex object or not was successfully
completed.
27. Aim:To Write a python program to demonstrate
basic slicing,integer and Boolean indexing.
Description:
Python basic concept of slicing is extended in basic slicing
to n dimensions. As with python slice object which is
constructed by giving a start, stop & step parameters to slice
function. To get specific output, the slice object is passed to
the array to extract a part of an array.
Indexing can be done in NumPy by
using an array as an index.
Numpy arrays can be indexed with other arrays or any
other sequence with the exception of tuples. The last element
is indexed by -1 second last by -2 and so on.
In the case of slicing, a view or
shallow copy of the array is returned
but in an index array, a copy of the
original array is returned.
Program:
import numpy as npB =
np.array([[42,56,89,65],
[99,88,42,12],
[55,42,17,18]])
print(B>=42
) Output:
[[ True True True
True] [ True True
True False] [ True
True False False]]
Result: The python program to demonstrate basic
slicing,integer and Boolean indexing was successfully
completed.
29a)Aim:To create dictionary with atleast five keys
and each key represent value as a list where this list
contains at least ten values and convert this dictionary
as a pandas data frame and explore the data through
the data frame
a)Apply head() function to the pandas data frame
Description:
Pandas DataFrame is a 2-dimensional labeled data
structure like any table with rows and columns. The size
and values of the dataframe are mutable, i.e., can be
modified. It is the most commonly used pandas object.
Creating pandas data- frame from lists using dictionary can
be achieved in multiple ways. Let’s discuss different ways
to create a DataFrame one by one.
Program:
# importing pandas
as pd import pandas
as pd
# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
'degree': ["MBA", "BCA", "M.Tech",
"MBA"], 'score':[90, 40, 80, 98]}
df =
pd.DataFrame(dict)
Output:
As is evident from the output, the
keys of a dictionary is converted
into columns of a dataframe
whereas the elements in lists are
converted into rows.
Ressult: To Apply head() function to the pandas
data frame was successfully completed.
29.b)Aim: To create dictionary with atleast five keys
and each key represent value as a list where this list
contains at least ten values and convert this dictionary
as a pandas data frame and explore the data through the
data frame
b)Perform various data selection operations on Data
Frame.
Description;
Creating a DataFrame.
1. Accessing rows and columns.
2. Selecting the subset of the data frame.
3. Editing dataframes.
4. Adding extra rows and columns to the data frame.
5. Add new variables to dataframe based on existing ones.
6. Delete rows and columns in a data frame.
Program:
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
Output:
Result: Perform various data selection operations on
Data Frame was successfully completed.