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

Nte Python Cycle 1

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

Nte Python Cycle 1

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

Experiment No:34

BUILT-IN PACKAGES
Page no:57
Date: / /20
Aim : Work with Built-in packages.
Algorithm :
Step 1:START
Step 2:Use math module to import.
Step 3:Write a function called ‘area’ to calculate the area of circle.
Step 4: Write a function called ‘perimeter’ to calculate the perimeter
of circle .
Step 5: Call the area function with radius of 5 and print the result.
Step 6: Call the perimeter function with radius of 10 and print the
result.
Step 7: STOP
Source code :
import math def
area(r):
return math.pi*r*r
def perimeter(r):
return 2*math.pi*r
print("Area of a circle: ", area(5))
print("Perimeter of a circle: ", perimeter(10))
Output :
Area of circle:78.53981633974483
Perimeter of a circle:62.83185307179586
Result : The program has executed successfully and output has
obtained.
Experiment No : 35
PACKAGE WITH MODULES
Page no:59
Date: / /20
Aim : Create a package with modules rectangle, circle and sub-
package 3D-graphice with modules cuboid and sphere. Include
methods to find the area and perimeter of respective figures in each
module. Write programs that finds area and perimeter of figures by
different importing statements. (Include selective import of modules
and import * statements).
Algorithm :
Step 1: START
Step 2: Import modules needed for the program.
Step 3: Calculate and print the area and perimeter of a circle using
the circle module.
Step 4: Calculate and print the area and perimeter of a rectangle
using the rectangle module.
Step 5: Calculate and print the area and perimeter of a cuboid
using the cuboid module.
Step 6: Calculate and print the area and perimeter of a sphere
using the sphere module.
Step 6: STOP
Source code :
import graphics.circle
import graphics.rectangle
import graphics.graphics3d.cuboid
import graphics.graphics3d.sphere
print("Area of circle is:",graphics.circle.area(2))
print("Perimeter if circle is:",graphics.circle.perimeter(5))
print("Area of Rectangle is:",graphics.rectangle.area(2,7))
print("Perimeter of Rectangle is:",graphics.rectangle.perimeter(3,4))
print("Area of Cuboid is :",graphics.graphics3d.cuboid.area(3,2,1))
print("Perimeter of Cuboid is:",
graphics.graphics3d.cuboid.perimeter(5,2,3))
print("Area of Sphere is :",graphics.graphics3d.sphere.area(3))
print("Perimeter of sphere is:",
graphics.graphics3d.sphere.perimeter(7))
Graphics(package)
Circle.py
import math
def area(r):
return math.pi*r*r
def perimeter(r):
return 2*math.pi*r
Rectangle.py
def area(length,breadth):
return (length*breadth)
def perimeter(length,breadth):
return 2*(length+breadth)
Graphics 3d(package inside Graphics)
Cuboid.py
def area(length,width,height):
return 2*(length*width)+(length*height)+(width*height)
def perimeter(length,width,height):
return 4*(length+width+height)
Sphere.py
import math
def area(r):
return 4*math.pi*r
def perimeter(r):
return 2*math.pi*r
Output :
Area of circle:12.566370614359172
Perimeter of circle:18.84955592153876
Area of rectangle:6
Perimeter of rectangle:12
Area of cuboid:4
Perimeter of cuboid:12
Area of sphere:37.69977784307752
Perimeter of sphere:12.566370614359172
Result : The program has executed successfully and output has
obtained.
Experiment No:36
RECTANGLE CLASS
Page no:63
Date: / /20
Aim : Create Rectangle class with attributes length and breadth and
methods to find area and perimeter.Compare two rectangle objects
by their area.
Algorithm :
Step 1:START
Step 2: Create a rectangle class with an area and a perimeter
initialised to zero.
Step 3: Initialize the rectangles length and width by defining a
constructor method..
Step 4: Define a method to calculate the area of a rectangle.
Step 5: Compare the areas of two rectangles using the less than
operator by defining a special method "lt".
Step 6: Take input from the user for the length and width of two
rectangles.
Step 7: Create two rectangle objects using the input values and call
the "calc_area".
Step 8: Compare the areas of the two rectangle objects and print a
message indicating which rectangle has a larger area.
Step 9: STOP
Source code :
class rectangle:
area = 0
perimeter = 0
def __init__(self, length, width):
self.__length = length
self.__width = width
def calc_area(self):
self.__area = self.__length * self.__width
print("Area is :", self.__area)
def __lt__(self, second):
if self.__area < second.__area:
return True
else:
return False
length1 = int(input("Enter length of the rectangle 1 : "))
width1 = int(input("Enter width of the rectangle 1 : "))
length2 = int(input("Enter length of the rectangle 2 : "))
width2 = int(input("Enter width of the rectangle 2 : "))
obj1 = rectangle(length1, width1)
obj2 = rectangle(length2, width2)
obj1.calc_area()
obj2.calc_area()
if obj1 < obj2:
print("Rectangle two is large")
else:
print("Rectangle one is large ")
Output :
Enter length of the rectangle 1 : 18
Enter width of the rectangle 1 : 6
Enter length of the rectangle 2 : 12
Enter width of the rectangle 2 : 5
Area is : 108
Area is : 60
Rectangle one is large.
Result : The program has executed successfully and output has
obtained.
Experiment No:37
CONSTRUCTOR AND METHOD
Page no:66
Date: / /20
Aim : Create a Bank account with members account number, name,
type of account and balance. Write constructor and methods to
deposit at the bank and withdraw an amount from the bank.
Algorithm :
Step 1:START
Step 2:
Step 3:
Step 4:
Step 5:
Step 6:
Step 7: STOP
Source code :
class bank:
def __init__(self, accno, name, accty, bal):
self.accno = accno
self.name = name
self.accty = accty
self.bal = 0
def showamt(self):
print("Account Holder Name:", self.name)
print("Account Number:", self.accno)
print("Account Type:", self.accty)
print("Your Balance Amount:", self.bal)
def depo(self, d1):
self.bal = self.bal + d1
return self.bal
def withd(self, w1):
self.bal = self.bal - w1
return self.bal
n = input("Enter your name: ")
a = int(input("Enter your Account number: "))
t = input("Enter your account type: ")
o = bank(a, n, t, bal=0)
o.showamt()
while (True):
print("\nMenu")
print("\n1.Deposit")
print("\n2.Withdraw")
c = int(input("Enter your choice:"))
if (c == 1):
d = int(input("Enter the amount to deposit"))
print("Your total balance is :", o.depo(d))
elif(c==2):
w = int(input("Enter the amount to be withdrawn:"))
if (w > d):
print("INSUFFICIENT BALANCE")
else:
print("Your total balance Amount is", o.withd(w))
else:
print("Enter a valid choice.")
Output :
Enter your account type: savings
Account Holder Name: Parvathy G
Account Number: 12121212
Account Type: savings
Your Balance Amount: 0
Menu
1.Deposit
2.Withdraw
Enter your choice:1
Enter the amount to deposit:1000
Your total balance is : 1000
Menu
1.Deposit
2.Withdraw
Enter your choice:2
Enter the amount to be withdrawn:900
Your total balance Amount is 100
Result : The program has executed successfully and output has
obtained.
Experiment No:38
OVERLOAD ‘<’ OPERATOR
Page no:70
Date: / /20
Aim : Create a class Rectangle with private attributes length and
width. Overload ‘<’ operator to compare the area of 2 rectangles.
Algorithm :
Step 1:START
Step 2:Define a class named "Rectangle".
Step 3:Define a constructor function inside the Rectangle class that
asks the user to enter the length and breadth of the
rectangle, and calculates its area.
Step 4:Define a function named "greaterThan" inside the Rectangle
class that takes another Rectangle object as an argument and
compares the areas of the two rectangles.
Step 5:If the area of the current rectangle is less than the area of the
rectangle passed as an argument, print "Area of rectangle 1 is
Greater", else print "Area of rectangle 2 is Greater".
Step 6:Enter the dimensions of two rectangles by creating two
instances of the Rectangle class, and store them in r1 and r2
respectively.
Step 7:Call the greater than function on r2 with r1 as an argument to
compare the areas of the two rectangles.
Step 8:Print the result of the comparison.
Step 7: STOP
Source code :
class rectangle:
def __init__(self):
self._length = int(input("Enter the Length:"))
self._breadth = int(input("Enter the Breadth:"))
self.area = self._length * self._breadth
def greaterThan(self, rectangle):
if self.area < rectangle.area: print("Area of rectangle 1 is Greater")
else:
print("Area of rectangle 2 is Greater")
print("Rectangle 1:")
r1 = rectangle()
print("Rectangle 2:")
r2 = rectangle()
print("Comparing Rectangles:")
r2.greaterThan(r1)
Output :
Rectangle 1:
Enter the Length:20
Enter the Breadth:25
Rectangle 2:
Enter the Length:24
Enter the Breadth:15
Comparing Rectangles:
Area of rectangle 1 is Greater
Result : The program has executed successfully and output has
obtained.
Experiment No:39
OVERLOAD ‘+’ OPERATOR
Page no:73
Date: / /20
Aim : Create a class Time with private attributes hour, minute and
second. Overload ‘+’ operator to find the sum of 2 time.
Algorithm :
Step 1:START
Step 2:Add the seconds of both instances, and store the result in
‘total_seconds’.
Step 3:Calculate the number of minutes represented by the
‘total_seconds’, and divide it into a carry value (the number of
minutes that exceed 60) and a new value for the seconds (the
remainder of dividing by 60).
Step 4:Add the minutes of both instances, along with the carry value
from step 2, and store the result in total_minutes.
Step 5:Calculate the number of hours represented by the
total_minutes,and divide it into a carry value and a new value
for the minutes.
Step 6:Add the hours of both instances, along with the carry value
from step 5,and return a new ‘Time’ instance with the
resulting hours,minutes, and seconds.’
Step 7: STOP
Source code :
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def __add__(self, other):
return self.hour + other.hour,self.minute+other.minute,self.second+
other.second
o1 = Time(2, 40, 10)
o2 = Time(4, 20, 50)
print(o1 + o2)
Output :
(6, 60, 60)
Result : The program has executed successfully and output has
obtained.
Experiment No:40
CONSTRUCTOR AND METHOD OVERLOADING
Page no:75
Date: / /20
Aim : Create a class Publisher(name) .Derive class Book from
Publisher with attributes title and author. Derive class Python from
Book from Publisher with attributes price and no_of_pages. Write a
program that displays information about a Python book. Use base
class constructor invocation and method overloading.
Algorithm :
Step 1:START
Step 2:Define a ‘Book’ class that contains attributes for the book's
title and author, and a method to set those attributes.
Step 3:Define a ‘Python’ class that inherits from the Book class and
adds private attributes for the book's price and number of
pages,and methods to set and display those attributes.
Step 4:Create an instance of the Python class with a given publisher
name.
Step 5:Call the book details method to set the book's title and
author.
Step 6:Call the details method to prompt the user to input the book's
price and number of pages.
Call the display method to print the book's details, including
the publisher name, title, author, price, and number of
pages.
Step 7: STOP
Source code :
class Python(Book):
def __init__(self, pname):
Book.__init__(self, pname)
def details(self):
self.__price = int(input("Book Price :"))
self.__pages = int(input("Book Pages :"))
def display(self):
print("Publisher :", self.pname)
print("Title :", self.title)
print("Author :", self.author)
print("Price :", self.__price)
print("Pages :", self.__pages)
obj = Python("DC BOOKS")
obj.bookdetails()
obj.details()
print("___________________________________________")
obj.display()
Output :
Book Name :Wings of Fire
Book Author :APJ Abdul Kalam
Book Price :179
Book Pages :180
___________________________________________
Publisher : DC BOOKS
Title : Wings of Fire
Author : APJ Abdul Kalam
Price : 179
Pages : 180
Result : The program has executed successfully and output has
obtained.
Experiment No:41
READ A FILE LINE
Page no:78
Date: / /20
Aim : Write a Python program to read a file line by line and store it
into a list.
Algorithm :
Step 1:START
Step 2: Define a function called file_read that takes one argument
fname.
Step 3: Open the file fname.
Step 4: Read all the lines in the file and store them in a list called
content_list.
Step 5: Print the contents of content_list to the console.
Step 6: Call the file_read function and pass it the filename
'demo2.txt'.
Step 7: STOP
Source code :
def file_read(fname):
with open(fname)as f:
content_list=f.readlines()
print(content_list)
file_read('demo2.txt')
DEMO2.TEXT
HELLO WORLD
THIS IS A PYTHON PROGRAM
Output :
['HELLO WORLD\n', 'THIS IS A PYTHON PROGRAM\n']
Result : The program has executed successfully and output has
obtained.
Experiment No:42
COPY ODD LINES OF FILE
Page no:80
Date: / /20
Aim : Python program to copy odd lines of one file to other
Algorithm :
Step 1:START
Step 2:Open 'file1.txt' in read mode and 'file2.txt' in write mode.
Step 3:Read all the lines from file1 and store them in a list called
'lines'.
Step 4:Create a loop that iterates through each line in 'lines' using a
for loop and the range function.
Step 5:If the line number is odd (i.e., i % 2 != 0), write that line to
'file2.txt'.
Step 6:Close both 'file1.txt' and 'file2.txt'.
Step 7:Re-open 'file1.txt' and 'file2.txt' in read mode.
Step 8:Read the entire contents of 'file1.txt' and store it in a string
called 'str1'.
Step 9:Read the entire contents of 'file2.txt' and store it in a string
called 'str2'.
Step 10:Print 'str1' and 'str2' to display the contents of both files.
Step 11:Close both 'file1.txt' and 'file2.txt'.
Step 12: STOP
Source code :
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'w')
lines = file1.readlines()
type(lines)
for i in range(0, len(lines)):
if(i % 2 != 0):
file2.write(lines[i])
file1.close()
file2.close()
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
str1 = file1.read()
str2 = file2.read()
print("file1 content...")
print(str1)
print()
print("file2 content...")
print(str2)
file1.close()
file2.close()
FILE1.TEXT
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
FILE2.TEXT
This is line 2.
This is line 3.
Output :
file1 content...
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
file2 content...
This is line 2.
This is line 4.
Result : The program has executed successfully and output has
obtained.
Experiment No:43
READ EACH ROW
Page no:83
Date: / /20
Aim : Write a Python program to read each row from a given csv file
and print a list of strings.
Algorithm :
Step 1:START
Step 2:Import the csv module.
Step 3:Open the file "departments.csv" and store it in a variable
called csvfile.
Step 4:Use the csv.reader() function to read the data in csvfile, using
a space as the delimiter and a pipe (|) as the quote character.
Store the result in a variable called data.
Step 5:Use a for loop to iterate over each row in data.
Step 6:For each row, use the join() function to combine the elements
of the row into a single string, separated by commas.
Step 7:Print the resulting string.
Step 8: STOP
Source code :
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
print(', '.join(row))
DEPARTMENTS.CSV
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
100,Finance,108,1700
110,Accounting,205,1700
120,Treasury,,1700
130,Corporate Tax,,1700
140,Control And Credit,,1700
150,Shareholder Services,,1700
160,Benefits,,1700
170,Manufacturing,,1700
180,Construction,,1700
190,Contracting,,1700
200,Operations,,1700
210,IT Support,,1700
220,NOC,,1700
230,IT Helpdesk,,1700
240,Government Sales,,1700
250,Retail Sales,,1700
260,Recruiting,,1700
270,Payroll,,1700
Output :
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
100,Finance,108,1700
110,Accounting,205,1700
120,Treasury,,1700
130,Corporate Tax,,1700
140,Control And Credit,,1700
150,Shareholder Services,,1700
160,Benefits,,1700
170,Manufacturing,,1700
180,Construction,,1700
190,Contracting,,1700
200,Operations,,1700
210,IT Support,,1700
220,NOC,,1700
230,IT Helpdesk,,1700
240,Government Sales,,1700
250,Retail Sales,,1700
260,Recruiting,,1700
270,Payroll,,1700
Result : The program has executed successfully and output has
obtained.
Experiment No:44
READ SPECIFIC COLUMNS
Page no:87
Date: / /20
Aim : Write a Python program to read specific columns of a given
CSV file and print the content of the columns.
Algorithm :
Step 1:START
Step 2:Open the 'department.csv' file and read its contents.
Step 3:Print the column headings 'ID', 'Department Name' to the
console.
Step 4:Print a line of dashes to separate the headings from the data.
Step 5:For each row in the data, print the department ID and name
to the console.
Step 6: STOP
Source code :
import csv
with open('department.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
print("ID Department Name")
print("---------------------------------")
for column in data:
print(column['department_id'], column['department_name'])
DEPARTMENT.CSV
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
100,Finance,108,1700
110,Accounting,205,1700
120,Treasury,,1700
130,Corporate Tax,,1700
140,Control And Credit,,1700
150,Shareholder Services,,1700
160,Benefits,,1700
170,Manufacturing,,1700
180,Construction,,1700
190,Contracting,,1700
200,Operations,,1700
210,IT Support,,1700
220,NOC,,1700
230,IT Helpdesk,,1700
240,Government Sales,,1700
250,Retail Sales,,1700
260,Recruiting,,1700
270,Payroll,,1700

Output :
ID Department Name
---------------------------------
10 Administration
20 Marketing
30 Purchasing
40 Human Resources
50 Shipping
60 IT
70 Public Relations
80 Sales
90 Executive
100 Finance
110 Accounting
120 Treasury
130 Corporate Tax
140 Control And Credit
150 Shareholder Services
160 Benefits
170 Manufacturing
180 Construction
190 Contracting
200 Operations
210 IT Support
220 NOC
230 IT Helpdesk
240 Government Sales
250 Retail Sales
260 Recruiting
270 Payroll
Result : The program has executed successfully and output has
obtained.
Experiment No:45
PYTHON DICTIONARY TO CSV FILE
Page no:91
Date: / /20
Aim : Write a Python program to write a Python dictionary to a csv
file. After writing the CSV file read the CSV file and display the
content.
Algorithm :
Step 1:START
Step 2:Define a list csv_columns to store the column names for the
CSV file.
Step 3:Define a list of dictionaries dict_data to store the data for the
CSV file.
Step 4:Open a CSV file named temp.csv in write mode using with
statement and the csv.DictWriter function to write data to the file.
Step 5:Write the headers to the CSV file using writer.writeheader()
function.
Step 6:Iterate through the data in the dict_data list and write each
dictionary to the CSV file using writer.writerow(data) function.
Step 7:Open the temp.csv file in read mode using the csv.DictReader
function to read the data from the file.
Step 8:Iterate through each row of the CSV file using a for loop, and
print each row as a dictionary.
Step 9: STOP
Source code :
import csv

csv_columns = ['country_id', 'country_name', 'region_id']


dict_data = [
{'country_id': 'AR', 'country_name': 'Argentina', 'region_id': 2},
{'country_id': 'AU', 'country_name': 'Australia', 'region_id': 3},
{'country_id': 'BE', 'country_name': 'Belgium', 'region_id': 1},
{'country_id': 'BR', 'country_name': 'Brazil', 'region_id': 2},
{'country_id': 'CA', 'country_name': 'Canada', 'region_id': 2}
]
csv_file = "temp.csv"
try:
with open(csv_file, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns,
delimiter='|')
writer.writeheader()
for data in dict_data:
writer.writerow(data)
except IOError:
print("I/O error")
with open(csv_file, 'r') as csvfile:
data = csv.DictReader(csvfile, delimiter='|')
print("CSV file as a dictionary:\n")
for row in data:
print(row)
Output :
CSV file as a dictionary:
{'country_id': 'AR', 'country_name': 'Argentina', 'region_id': '2'}
{'country_id': 'AU', 'country_name': 'Australia', 'region_id': '3'}
{'country_id': 'BE', 'country_name': 'Belgium', 'region_id': '1'}
{'country_id': 'BR', 'country_name': 'Brazil', 'region_id': '2'}
{'country_id': 'CA', 'country_name': 'Canada', 'region_id': '2'}
Result : The program has executed successfully and output has
obtained.

You might also like