Python Programming: Guru Nanak Dev Engg College
Python Programming: Guru Nanak Dev Engg College
Practical File
Python Programming
LPCIT-105
Code: -
#getting the value of the mass in float
mass = float(input("mass(kg) : "))
#getting the value of the velocity in float
velocity = float(input("velocity(m/s) : "))
#implementing the values of the mass and velocity in the formula
momentum = mass*velocity
#Display the momentum
print("the object's momentum in (kg.m/s) is : ",momentum)
Output: -
2 Five Star Retro Video rents VHS tapes and DVDs to the same
connoisseurs who like to buy LP record albums. The store
rents new videos for $3.00 a night, and oldies for $2.00 a
night. Write a program that the clerks at Five Star Retro
Video can use to calculate the total charge for a customer’s
video rentals. The program should prompt the user for the
number of each type of video and output the total Cost.
Code: -
# Request the input
videos=int(input("enter no. of new : "))
oldies=int(input("enter no. of oldie : "))
# Calculate the result
result=(videos*3)+(oldies*2)
# Display the total cost
print("the total cost is","$",result)
Output: -
3 (A). Write a program that calculates and displays the value of
a light-year.
(B). Write a program that takes as input a number of
kilometers and prints the corresponding number of nautical
miles. Use the following approximations:
• A kilometer represents 1/10,000 of the distance between the North Pole and
the equator.
• There are 90 degrees, containing 60 minutes of arc each, between the North
Pole and the equator.
• A nautical mile is 1 minute of an arc.
(A)
Code: -
Output: -
(B)
Code: -
Output: -
4 Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is an equilateral triangle.
Code: -
Output: -
5 Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is a right triangle. Recall from the
Pythagorean theorem that in a right triangle, the square of
one side equals the sum of the squares of the other two sides.
Code: -
if C^2 == ((A^2)+(B^2)):
print("IT IS A RIGHT TRIANGLE")
# otherwise it is not a right triangle
else:
print("IT IS NOT A RIGHT TRIANGLE")
Output: -
6 The greatest common divisor of two positive integers, A and
B, is the largest number that can be evenly divided into both
of them. Euclid’s algorithm can be used to find the greatest
common divisor (GCD) of two positive integers. You can use
this algorithm in the following manner:
(a). Compute the remainder of dividing the larger number by the smaller
number.
(b). Replace the larger number with the smaller number and the smaller
number with the remainder.
(c). Repeat this process until the smaller number is zero. The larger number
at this point is the GCD of A and B.
Write a program that lets the user enter two integers and then prints each
step in the process of using the Euclidean algorithm to find their GCD.
Code: -
# Request input
small = int(input("Enter the smaller number: "))
large = int(input("Enter the larger number: "))
# Calculate
for i in range(1, small+1):
if (small % i == 0) and (large % i == 0):
gcd = i
print("\nThe greatest common divisor is {}" .format(gcd))
Output: -
7 Write a script named dif.py. This script should prompt the
user for the names of two text files and compare the contents
of the two files to see if they are the same. If they are, the
script should simply output "Yes". If they are not, the script
should output "No", followed by the first lines of each file
that differ from each other. The input loop should read and
compare lines from each file. The loop should break as soon
as a pair of different lines is found.
Code: -
Code: -
Output: -
9 A bit shift is a procedure whereby the bits in a bit string are
moved to the left or to the right. For example, we can shift the
bits in the string 1011 two places to the left to produce the
string 1110. Note that the leftmost two bits are wrapped
around to the right side of the string in this operation. Define
two scripts, shiftLeft.py and shiftRight.py, that expect a bit
string as an input. The script shiftLeft shifts the bits in its
input one place to the left, wrapping the leftmost bitto the
rightmost position. The script shiftRight performs the inverse
operation. Each script prints the resulting string.
Code: -
Shift right
bits = input("Enter a string of bits: ")
if len(bits) > 1:
bits = bits[-1] + bits[:-1]
print(bits)
Output: -
Shift left
bits = input("Enter a string of bits: ")
if len(bits) > 1:
bits = bits[1:] + bits[0]
print(bits)
Output: -
10 Write a program that inputs a text file. The program should
print the unique words in the file in alphabetical order.
Code: -
Code: -
Code: -
Output: -
13 A list is sorted in ascending order if it is empty or each item
except the last one is less than or equal to its successor. Define
a predicate isSorted that expects a list as an argument and
returns True if the list is sorted, or returns False otherwise.
Code: -
def isSorted(lyst):
"""Returns True if lyst is sorted in ascending
order or False otherwise."""
if len(lyst) == 0 or len(lyst) == 1:
return True
else:
for index in range(len(lyst) - 1):
if lyst[index] > lyst[index + 1]:
return False
return True
def main():
lyst = []
print(isSorted(lyst))
lyst = [1]
print(isSorted(lyst))
lyst = list(range(10))
print(isSorted(lyst))
lyst[9] = 3
print(isSorted(lyst))
main()
Output: -
14 Define and test a function myRange. This function should
behave like Python’s standard range function, with the
required and optional arguments, but it should return a list.
Do not use the range function in your implementation!
Code: -
def myRange(start, stop = None, step = None):
lyst = []
if stop == None and step == None:
stop = start
start = 0
step = 1
if start < stop:
if step == None:
step = 1
elif step <= 0:
return lyst
while start < stop:
lyst.append(start)
start += step
else:
if step == None or step > -1:
return lyst
while start > stop:
lyst.append(start)
start += step
return lyst
def main():
print(myRange(10))
print(myRange(1, 10))
print(myRange(1, 10, 2))
print(myRange(10, 1, -1))
main()
Output: -
15 Write a program that computes and prints the average of the
numbers in a text file. You should make use of two higher-
order functions to simplify the design.
Code: -
if __name__=='__main__':
main()
Output: -
16 Write GUI-based program that implements the tax calculator
program
Code: -
from breezypythongui import EasyFrame
class TaxCodeDemo(EasyFrame):
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
EasyFrame.__init__(self, title = "Tax Calculator")
# Label and field for the income
self.addLabel(text = "Income",
row = 0, column = 0)
self.incomeField = self.addFloatField(value = 0.0,
row = 0,
column = 1)
# Label and field for the number of dependents
self.addLabel(text = "Dependents",
row = 1, column = 0)
self.depField = self.addIntegerField(value = 0,
row = 1,
column = 1)
# The command button
self.addButton(text = "Compute", row = 3, column = 0,
columnspan = 2, command = self.computeTax)
# Label and field for the tax
self.addLabel(text = "Total tax",
row = 4, column = 0)
self.taxField = self.addFloatField(value = 0.0,
row = 4,
column = 1,
precision = 2)
# The event handler method for the button
def computeTax(self):
"""Obtains the data from the input fields and uses
them to compute the tax, which is sent to the
output field."""
income = self.incomeField.getNumber()
numDependents = self.depField.getNumber()
tax = (income - numDependents) * .15
self.taxField.setNumber(tax)
#Instantiate and pop up the window.
TaxCodeDemo().mainloop()
Output: -
17 Write a GUI-based program that allows the user to convert
temperature values between degrees Fahrenheit and degrees
Celsius. The interface should have labeled entry fields for
these two values. These components should be arranged in a
grid where the labels occupy the first row and the
corresponding fields occupy the second row. At start-up, the
Fahrenheit field should contain 32.0, and the Celsius field
should contain 0.0. The third row in the window contains two
command buttons, labeled >>>> and <<< When the user
presses the first button, the program should use the data in
the Fahrenheit field to compute the Celsius value, which
should then be output to the Celsius field. The second button
should perform the inverse function
Code: -
from tkinter import *
class ConvertGUI(Frame):
def __init__(self):
"""Set up the window and widgets."""
Frame.__init__(self)
self.master.title("Temperature Converter")
self.grid()
self._fahrVar = DoubleVar()
self._celsiusVar = DoubleVar()
self._fahrVar.set(32.0)
self._celsiusVar.set(0.0)
self._fahrLabel = Label(self, text = "Fahrenheit")
self._fahrLabel.grid(row = 0, column = 0)
self._fahrEntry = Entry(self, textvariable = self._fahrVar)
self._fahrEntry.grid(row = 1, column = 0)
self._celsiusLabel = Label(self, text = "Celsius")
self._celsiusLabel.grid(row = 0, column = 1)
self._celsiusEntry = Entry(self, textvariable = self._celsiusVar)
self._celsiusEntry.grid(row = 1, column = 1)
self._toCelsiusButton = Button(self, text = ">>>>",
command = self._toCelsius)
self._toCelsiusButton.grid(row = 2, column = 0)
self._toFahrButton = Button(self, text = "<<<<",
command = self._toFahr)
self._toFahrButton.grid(row = 2, column = 1)
def _toCelsius(self):
"""Event handler for the toCelsius button."""
fahr = self._fahrVar.get()
celsius = (fahr - 32) * 5 / 9
self._celsiusVar.set(celsius)
def _toFahr(self):
"""Event handler for the toFahr button."""
celsius = self._celsiusVar.get()
fahr = celsius * 9 / 5 + 32
self._fahrVar.set(fahr)
def main():
ConvertGUI().mainloop()
main()
Output: -
18 Write a GUI-based program that implements an image
browser for your computer’s file system. The look, feel, and
program logic should be like those of the simple text file
bowser developed in this chapter. The file dialog should filter
for GIF image files, and create and open a PhotoImage when
a file is accessed.
Code: -
from tkinter import *
import os
import os.path
class ImageBrowser(Frame):
def __init__(self):
"""Sets up the window and the widgets."""
Frame.__init__(self)
self.master.title("Image Browser")
self.master.rowconfigure(0, weight = 1)
self.master.columnconfigure(0, weight = 1)
self.grid(sticky = W+E+N+S)
# Set up the pane and add the list box and its
# scroll bar
self._listPane = Frame(self)
self._listPane.grid(row = 0, column = 0,
sticky = N+S)
self._yScroll = Scrollbar(self._listPane,
orient = VERTICAL)
self._yScroll.grid(row = 0, column = 1,
sticky = N+S)
self._listBox = Listbox(self._listPane,
width = 20,
height = 10,
selectmode = SINGLE,
yscrollcommand = \
self._yScroll.set)
self._listBox.grid(row = 0, column = 0,
sticky = N+S)
self._yScroll["command"] = self._listBox.yview
# Set up the input field, image label, and button
self._pathVar = StringVar()
self._input = Entry(self,
textvariable = self._pathVar,
width = 70)
self._input.grid(row = 0, column = 1,
sticky = N)
self._imageLabel = Label(self, text = "")
self._imageLabel.grid(row = 1, column = 1)
self._goButton = Button(self,
text = "Go",
command = self._go)
self._goButton.grid(row = 1, column = 0)
# Configure the list pane to expand
self.rowconfigure(0, weight = 1)
self._listPane.rowconfigure(0, weight = 1)
self._getPathAndFiles()
def _getPathAndFiles(self):
"""Sets the field and the list box with the path of the cwd
and the directories and the .gif files in that directory,
respectively."""
self._path = os.getcwd()
self._pathVar.set(self._path)
fileList = filter(lambda f: ".gif" in f or os.path.isdir(f),
os.listdir(self._path))
index = self._listBox.size() - 1
while self._listBox.size() > 0:
self._listBox.delete(index)
index -= 1
self._listBox.insert(END, "..")
for f in fileList:
self._listBox.insert(END, f)
self._listBox.activate(0)
def _go(self):
"""Moves to a directory or shows an image."""
(index) = self._listBox.curselection()
item = self._listBox.get(index)
if os.path.isfile(item):
# It's a file, so load the image
self._image = PhotoImage(file = item)
self._imageLabel["image"] = self._image
else:
# It's a directory, so move to it and refresh the view
os.chdir(item)
self._getPathAndFiles()
self._imageLabel["image"] = None
self._image = None
def main():
"""Instantiate and pop up the window."""
ImageBrowser().mainloop()
main()
Output: -
19 Add three methods to the Student class that compare two
Student objects. One method should test for equality. A
second method should test for less than. The third method
should test for greater than or equal to. In each case, the
method returns the result of the comparison of the two
students’ names. Include a main function that tests all of the
comparison operators.
Code: -
"""Resources to manage a student's name and test scores.
Includes methods for comparisons and testing for equality."""
from functools import reduce
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""All scores are initially 0."""
self._name = name
self._scores = []
for count in range(number):
self._scores.append(0)
def getName(self):
"""Returns the student's name."""
return self._name
def setScore(self, i, score):
"""Resets the ith score, counting from 1."""
self._scores[i - 1] = score
def getScore(self, i):
"""Returns the ith score, counting from 1."""
return self._scores[i - 1]
def getAverage(self):
"""Returns the average score."""
sum = reduce(lambda x, y: x + y, self._scores)
return sum / len(self._scores)
def getHighScore(self):
"""Returns the highest score."""
return reduce(lambda x, y: max(x, y), self._scores)
def __str__(self):
"""Returns the string representation of the student."""
return "Name: " + self._name + "\nScores: " + \
" ".join(map(str, self._scores)
def __lt__(self, other):
"""Returns self < other, with respect
to names."""
return self._name < other._name
def __gt__(self, other):
"""Returns self > other, with respect
to names."""
return not (self == other or self < other)
def __le__(self, other):
"""Returns self <= other, with respect
to names."""
return self == other or self < other
def __ge__(self, other):
"""Returns self >= other, with respect
to names."""
return self == other or self > other
def __eq__(self, other):
"""Tests for equality."""
if self is other:
return True
elif type(self) != type(other):
return False
else:
return self._name == other._name
def main():
"""Tests equality and comparisons."""
s1 = Student("Ken", 10)
s2 = Student("Mary", 10)
s3 = Student("Ken", 10)
print("False:", s1 == s2)
print("True:", s1 == s3)
print("True:", s1 == s1)
print("False:", s1 is s3)
print("True:", s1 < s2)
print("True:", s2 > s1)
print("True:", s2 >= s1)
print("True:", s1 >= s3)
print("True:", s1 <= s2)
print("True:", s1 <= s3)
main()
Output: -
20 This project assumes that you have completed Project 1. Place
several Student objects into a list and shuffle it. Then run the
sort method with this list and display all of the students’
information
Code: -
"""Resources to manage a student's name and test scores.
Includes methods for comparisons and testing for equality.
Tests the class by putting students into random order in a list
and then sorting them."""
from functools import reduce
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""All scores are initially 0."""
self._name = name
self._scores = []
for count in range(number):
self._scores.append(0)
def getName(self):
"""Returns the student's name."""
return self._name
def setScore(self, i, score):
"""Resets the ith score, counting from 1."""
self._scores[i - 1] = score
def getScore(self, i):
"""Returns the ith score, counting from 1."""
return self._scores[i - 1]
def getAverage(self):
"""Returns the average score."""
sum = reduce(lambda x, y: x + y, self._scores)
return sum / len(self._scores)
def getHighScore(self):
"""Returns the highest score."""
return reduce(lambda x, y: max(x, y), self._scores)
def __str__(self):
"""Returns the string representation of the student."""
return "Name: " + self._name + "\nScores: " + \
" ".join(map(str, self._scores))
def __lt__(self, other):
"""Returns self < other, with respect
to names."""
return self._name < other._name
def __gt__(self, other):
"""Returns self > other, with respect
to names."""
return not (self == other or self < other)
def __le__(self, other):
"""Returns self <= other, with respect
to names."""
return self == other or self < other
def __ge__(self, other):
"""Returns self >= other, with respect
to names."""
return self == other or self > other
def __eq__(self, other):
"""Tests for equality."""
if self is other:
return True
elif type(self) != type(other):
return False
else:
return self._name == other._name
import random
def main():
"""Tests sorting."""
# Create the list and put 5 students into it
lyst = []
for count in range(5):
s = Student("Name" + str(count + 1), 10)
lyst.append(s)
# Shuffle and print the contents
random.shuffle(lyst)
print("Unsorted list of students:")
for s in lyst:
print(s)
# Sort and print the contents
lyst.sort()
print("\nSorted list of students:")
for s in lyst:
print(s)
main()
Output: -
21 Geometric shapes can be modeled as classes. Develop classes
for line segments, circles, and rectangles. Each shape object
should contain a Turtle object and a color that allow the
shape to be drawn in a Turtle graphics window . Factor the
code for these features (instance variables and methods) into
an abstract Shape class. The Circle, Rectangle, and Line
classes are all subclasses of Shape. These subclasses include
other information about the specific types of shapes, such as a
radius or a corner point and a draw method. Write a script
that uses several instances of the different shape classes to
draw a house and a stick figure.
Code: -
Shapes.py
"""
Defines classes for line segments, circles, and rectangles using a turtle
object to draw them.
"""
import math
class Shape(object):
"""Represents a shape with a color and a turtle."""
def __init__(self, turtle, color):
self._turtle = turtle
self._color = color
def getColor(self):
return self._color
def setColor(self, color):
self._color = color
class Line(Shape):
"""Represents a line segment."""
def __init__(self, x1, y1, x2, y2, turtle, color):
Shape.__init__(self, turtle, color)
self._x1 = x1
self._x2 = x2
self._y1 = y1
self._y2 = y2
def draw(self):
"""Draws a line."""
(r, g, b) = self._color
self._turtle.up()
self._turtle.goto(self._x1, self._y1)
self._turtle.pencolor(r, g, b)
self._turtle.down()
self._turtle.goto(self._x2, self._y2)
class Circle(Shape):
"""Represents a circle."""
def __init__(self, x, y, radius, turtle, color):
Shape.__init__(self, turtle, color)
self._x = x
self._y = y
self._radius = radius
def draw(self):
"""Draws a circle."""
(r, g, b) = self._color
amount = 2.0 * math.pi * self._radius / 120.0
self._turtle.up()
self._turtle.goto(self._x + self._radius, self._y)
self._turtle.setheading(90)
self._turtle.down()
self._turtle.pencolor(r, g, b)
for count in range(120):
self._turtle.left(3)
self._turtle.forward(amount)
class Rectangle(Shape):
"""Represents a rectangle."""
def __init__(self, x, y, width, height, turtle, color):
Shape.__init__(self, turtle, color)
self._x = x
self._y = y
self._width = width
self._height = height
def draw(self):
"""Draws a rectangle."""
(r, g, b) = self._color
self._turtle.up()
self._turtle.goto(self._x, self._y)
self._turtle.setheading(0)
self._turtle.down()
self._turtle.pencolor(r, g, b)
self._turtle.forward(self._width)
self._turtle.left(-90)
self._turtle.forward(self._height)
self._turtle.left(-90)
self._turtle.forward(self._width)
self._turtle.left(-90)
self._turtle.forward(self._height)
main.py
"""
output:
Draws a stick figure and a house using shape classes.
"""
from shapes import Circle, Line, Rectangle
from turtle import Turtle
def main():
"""Draws a house and stick figure."""
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
turtle = Turtle()
turtle.hideturtle()
# Draw the stick figure
face = Circle(100, 0, 10, turtle, black)
body = Line(100, -10, 100, - 80, turtle, black)
arms = Line(80, -40, 120, -40, turtle, black)
leftLeg = Line(100, -80, 80, -100, turtle, black)
rightLeg = Line(100, -80, 120, -100, turtle, black)
face.draw()
body.draw()
arms.draw()
leftLeg.draw()
rightLeg.draw()
# Draw the house
front = Rectangle(-180, 0, 120, 60, turtle, black)
door = Rectangle(-100, -30, 15, 30, turtle, blue)
roof1 = Line(-180, 0, -160, 20, turtle, red)
roof2 = Line(-160, 20, -80, 20, turtle, red)
roof3 = Line(-80, 20, -60, 0, turtle, red)
front.draw()
door.draw()
roof1.draw()
roof2.draw()
roof3.draw()
main()
Output: -