- Write a program that reads a list of temperatures from a file called temps.txt, converts
those temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
fo = open("temps.txt")
f1= open("ftemps.txt","w+")
for i in fo:
c=float(i)
F=(9*c + (32*5))/5
f1.write(str(F)+"\n")
f1.close()
fo.close()
- Write a class called Product. The class should have fields called name, amount, and price, holding the product's name, the number of items of that product in stock, and
the regular price of the product. There should be a method get_price that receives the
number of items to be bought and returns a the cost of buying that many items, where
the regular price is charged for orders of less than 10 items, a 10% discount is applied
for orders of between 10 and 99 items, and a 20% discount is applied for orders of
100 or more items. There should also be a method called make_purchase that receives
the number of items to be bought and decreases amount by that much.
class Product:
def __init__(self,name,amount,price):
self.name=name
self.amount=amount
self.price=price
def get_price(self,number_items):
if number_items<10:
return self.price*number_items
elif 10 <=number_items < 100:
return 0.9*self.price*number_items
else:return 0.8*self.price*number_items
def make_purchase(self, quantity):
self.amount -= quantity
name, amount, price = 'shoes', 200, 1200
shoes = Product(name, amount, price)
q1 = 4
print(f'cost for {q1} {shoes.name} = {shoes.get_price(q1)}')
shoes.make_purchase(q1)
print(f'remaining stock: {shoes.amount}\n')
q2 = 12
print(f'cost for {q2} {shoes.name} = {shoes.get_price(q2)}')
shoes.make_purchase(q2)
print(f'remaining stock: {shoes.amount}\n')
q3 = 112
print(f'cost for {q3} {shoes.name} = {shoes.get_price(q3)}')
shoes.make_purchase(q3)
print(f'remaining stock: {shoes.amount}\n')
- Write a class called Time whose only field is a time in seconds. It should have a
method called convert_to_minutes that returns a string of minutes and seconds
formatted as in the following example: if seconds is 230, the method should return
'5:50'. It should also have a method called convert_to_hours that returns a string of
hours, minutes, and seconds formatted analogously to the previous method.
class Time():
# constructor
def __init__(self, seconds):
self.seconds = seconds
# function to convert and return a string of minutes and seconds
def convert_to_minutes(self):
mins = self.seconds//60 # get the total minutes in the given seconds
secs = self.seconds - (mins*60) # get the remaining seconds
print("{}:{} minutes".format(self.seconds//60,self.seconds%60))
# return the string of minutes:seconds
return "%d:%d minutes" %(mins,secs)
# function to convert and return string of hours, minutes, and seconds
def convert_to_hours(self):
secs = self.seconds
hours = secs//3600 # get the total hours in the given seconds
secs = secs - (hours*3600) # get the remaining seconds
mins = secs//60 # get the total minutes in the remaining seconds
secs = secs - (mins*60) # get the remaining seconds
print("{:.2f} Hors".format(self.seconds/3600))
# return the string of hours:minutes:seconds
return "%d:%d:%d" %(hours,mins,secs)
time = Time(365)
print(time.convert_to_minutes())
time = Time(4520)
print(time.convert_to_hours())
- Write a class called Converter. The user will pass a length and a unit when declaring
an object from the class for example, c = Converter(9,'inches'). The possible units
are inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For
each of these units there should be a method that returns the length converted into
those units. For example, using the Converter object created above, the user could call
c.feet() and should get 0.75 as the result.
class Converter:
def __init__(self, n,name):
self.value = n
self.name=name
def FeettoInches(self):
Inches=self.value*12
print("Feet to Inches value is ", Inches)
def milestokm(self):
km=self.value/0.62137
print("miles to KM is ", km)
def FeettoYards(self):
Yards= self.value * 0.3333
print("Feet to Yards value is ", Yards)
def FeettoMiles(self):
Miles= self.value * 0.00018939
print("Feet to Miles value is ", Miles)
n=float(input("enter feet/inches/cm/mm/km/miles: "))
x=Converter(n,'inches')
x.FeettoInches()
x.milestokm()
x.FeettoYards()
x.FeettoMiles()
- Write a Python class to implement pow(x, n).
class power:
def pow1(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow1(x,-n)
val = self.pow1(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
x=power()
print(x.pow1(2, -2))
print(x.pow1(3, 5))
print(x.pow1(100, 0))
- Write a Python class to reverse a string word by word.
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
print(py_solution().reverse_words('hello .py'))
or
string = "I am a python programmer"
words = string.split()
words = list(reversed(words))
print(" ".join(words))
- Write a program that opens a file dialog that allows you to select a text file. The
program then displays the contents of the file in a textbox.
from tkinter import *
from tkinter.filedialog import *
from tkinter.scrolledtext import ScrolledText
#lab program 2 type
root = Tk()
root.title('File dialog')
textbox = ScrolledText()
textbox.grid()
filename=askopenfilename(initialdir='C:\Python_Code\examples',filetypes=[('Text files', '.txt'),('All files', '*')])
s = open(filename).read()
textbox.insert(1.0, s)
mainloop()
or
from tkinter import *
from tkinter.filedialog import *
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
#lab program 1 type
master = Tk()
master.title('File dialog')
textbox = ScrolledText()
textbox.grid()
def callback():
filename=askopenfilename()
s = open(filename).read()
textbox.insert(1.0, s)
errmsg = 'Error!'
bt=Button(text='File Open', command=callback)
bt.grid(column=1, row=0)
mainloop()
- Write a program to demonstrate Try/except/else
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
- Write a program to demonstrate try/finally and with/as.
try/finally
try:
print('try block')
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
print ("Out of try, except, else and finally blocks." )
Output1:
try block
Enter a number:100
Enter another number:10
else block
Division = 10.0
finally block
Out of try, except, else and finally blocks.
Output2:
try block
Enter a number:100
Enter another number:0
except ZeroDivisionError block
Division by not accepted
finally block
Out of try, except, else and finally blocks.
with/as
# file handling
#1)without using with statement
file=open('123.txt','w')
file.write('hello world')
file.close()
#2)with try and finally
file=open('123.txt','w')
try:
file.write('hello world')
finally:
file.close()
#3)using with statement
with open('123.txt','w') as file:
file.write('hello world')
fo = open("temps.txt") f1= open("ftemps.txt","w+") for i in fo: c=float(i) F=(9*c + (32*5))/5 f1.write(str(F)+"\n") f1.close() fo.close()
class Product: def __init__(self,name,amount,price): self.name=name self.amount=amount self.price=price def get_price(self,number_items): if number_items<10: return self.price*number_items elif 10 <=number_items < 100: return 0.9*self.price*number_items else:return 0.8*self.price*number_items def make_purchase(self, quantity): self.amount -= quantity name, amount, price = 'shoes', 200, 1200 shoes = Product(name, amount, price) q1 = 4 print(f'cost for {q1} {shoes.name} = {shoes.get_price(q1)}') shoes.make_purchase(q1) print(f'remaining stock: {shoes.amount}\n') q2 = 12 print(f'cost for {q2} {shoes.name} = {shoes.get_price(q2)}') shoes.make_purchase(q2) print(f'remaining stock: {shoes.amount}\n') q3 = 112 print(f'cost for {q3} {shoes.name} = {shoes.get_price(q3)}') shoes.make_purchase(q3) print(f'remaining stock: {shoes.amount}\n')
class Time(): # constructor def __init__(self, seconds): self.seconds = seconds # function to convert and return a string of minutes and seconds def convert_to_minutes(self): mins = self.seconds//60 # get the total minutes in the given seconds secs = self.seconds - (mins*60) # get the remaining seconds print("{}:{} minutes".format(self.seconds//60,self.seconds%60)) # return the string of minutes:seconds return "%d:%d minutes" %(mins,secs) # function to convert and return string of hours, minutes, and seconds def convert_to_hours(self): secs = self.seconds hours = secs//3600 # get the total hours in the given seconds secs = secs - (hours*3600) # get the remaining seconds mins = secs//60 # get the total minutes in the remaining seconds secs = secs - (mins*60) # get the remaining seconds print("{:.2f} Hors".format(self.seconds/3600)) # return the string of hours:minutes:seconds return "%d:%d:%d" %(hours,mins,secs) time = Time(365) print(time.convert_to_minutes()) time = Time(4520) print(time.convert_to_hours())
class Converter: def __init__(self, n,name): self.value = n self.name=name def FeettoInches(self): Inches=self.value*12 print("Feet to Inches value is ", Inches) def milestokm(self): km=self.value/0.62137 print("miles to KM is ", km) def FeettoYards(self): Yards= self.value * 0.3333 print("Feet to Yards value is ", Yards) def FeettoMiles(self): Miles= self.value * 0.00018939 print("Feet to Miles value is ", Miles) n=float(input("enter feet/inches/cm/mm/km/miles: ")) x=Converter(n,'inches') x.FeettoInches() x.milestokm() x.FeettoYards() x.FeettoMiles()
class power: def pow1(self, x, n): if x==0 or x==1 or n==1: return x if x==-1: if n%2 ==0: return 1 else: return -1 if n==0: return 1 if n<0: return 1/self.pow1(x,-n) val = self.pow1(x,n//2) if n%2 ==0: return val*val return val*val*x x=power() print(x.pow1(2, -2)) print(x.pow1(3, 5)) print(x.pow1(100, 0))
class py_solution: def reverse_words(self, s): return ' '.join(reversed(s.split())) print(py_solution().reverse_words('hello .py'))
or
string = "I am a python programmer" words = string.split() words = list(reversed(words)) print(" ".join(words))
from tkinter import * from tkinter.filedialog import * from tkinter.scrolledtext import ScrolledText #lab program 2 type root = Tk() root.title('File dialog') textbox = ScrolledText() textbox.grid() filename=askopenfilename(initialdir='C:\Python_Code\examples',filetypes=[('Text files', '.txt'),('All files', '*')]) s = open(filename).read() textbox.insert(1.0, s) mainloop()
or
from tkinter import * from tkinter.filedialog import * from tkinter import filedialog from tkinter.scrolledtext import ScrolledText #lab program 1 type master = Tk() master.title('File dialog') textbox = ScrolledText() textbox.grid() def callback(): filename=askopenfilename() s = open(filename).read() textbox.insert(1.0, s) errmsg = 'Error!' bt=Button(text='File Open', command=callback) bt.grid(column=1, row=0) mainloop()
try: x=int(input('Enter a number upto 100: ')) if x > 100: raise ValueError(x) except ValueError: print(x, "is out of allowed range") else: print(x, "is within the allowed range")
try/finally
try: print('try block') x=int(input("Enter a number:")) y=int(input("Enter another number:")) z=x/y except ZeroDivisionError: print("except ZeroDivisionError block") print("Division by not accepted") else: print("else block") print("Division = ", z) finally: print("finally block") print ("Out of try, except, else and finally blocks." ) Output1: try block Enter a number:100 Enter another number:10 else block Division = 10.0 finally block Out of try, except, else and finally blocks. Output2: try block Enter a number:100 Enter another number:0 except ZeroDivisionError block Division by not accepted finally block Out of try, except, else and finally blocks.
with/as
# file handling #1)without using with statement file=open('123.txt','w') file.write('hello world') file.close() #2)with try and finally file=open('123.txt','w') try: file.write('hello world') finally: file.close() #3)using with statement with open('123.txt','w') as file: file.write('hello world')
very informative, thanks for sharing. Java Course In Amravati
ReplyDeletenice post. Python Training In Amravati
ReplyDeletenice post. Python Training In Amravati
ReplyDeleteEmbark on your journey to becoming a proficient Python developer with APTRON Solutions in Noida. Our Python Training Course in Noida is meticulously crafted to empower you with the skills that employers demand. Don't miss this opportunity to shape a successful career in the ever-evolving field of programming. Enroll now and take the first step towards a brighter future!
ReplyDeleteThanks for sharing the valuable information.
ReplyDeleteJava Job Support
IT Jobs Support
Python Job Support
APTRON stands as a beacon of excellence in the realm of Java Full Stack Institute in Gurgaon. The institute prides itself on its holistic approach, equipping students with both the theoretical knowledge and practical skills necessary to thrive in the competitive IT landscape.
ReplyDelete