Question

Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...

Write a class called TemperatureFile.
• The class has one data attribute: __filename
• Write getter and setter for the data attribute.
• Write a “calculateAverage” function (signature below) to calculate and
return average temperature of all temperatures in the file.
def calculateAverage(self):
• Handle possible exceptions

Write a main function:
• Create a file ('Temperatures.txt’) and then use “write” method to write
temperature values on each line.
• Create an object of the TemperaureFile with the filename
(‘Temperatures.txt’) just created.
• Use the object to call calcuateAverage function and print out the
returned average temperature.
• Handle possible exceptions in main function.

----------------------------------------------------------------------------------------------

# Create Class

class tempearutefile:

def __init__(self, filename):

self.__filename = filename

def set_filename(self, filename):

self.__filename = filename

def get_filename(self):

return self.__filename

def calculateAverage(self, num1,num2,num3):

try:

total = num1+ num2+ num3

average = total/3

return average

# exception errors

except ValueError as err:

print(err)

except IOError as err:

print(err)

except Exception as err:

print(err)

def main():

try:

#Getting input from the users

num1=float(input("Please enter your first value: "))

num2=float(input("Please enter your second value: "))

num3=float(input("Please enter your third value: "))

#Creating temperatue file

test_file= open('Temperatures.txt', 'w')

#writing input informatin to the file

test_file.write(str(num1) + '\n')

test_file.write(str(num2) + '\n')

test_file.write(str(num3) + '\n')

#closing file

test_file.close()

temp1 = tempearutefile(test_file)

average = temp1.calculateAverage (float(num1),float(num2),float(num3))

print("your average temperatue is:", average)

# exception errors

except ValueError as err:

print(err)

except IOError as err:

print(err)

except Exception as err:

print(err)

#Call to main

main()

*** I am getting this error: ( 'tempearutefile' object has no attribute 'calculateAverage' ) when trying to run the program. ***

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi

Your code is well written and I ran your code and it working fine, here is the output and the screenshot

==============================================================================================

# Create Class
class tempearutefile:
    def __init__(self, filename):
        self.__filename = filename
    def set_filename(self, filename):
        self.__filename = filename
    def get_filename(self):
        return self.__filename
    def calculateAverage(self, num1,num2,num3):
        try:
            total = num1+ num2+ num3
            average = total/3
            return average
        # exception errors
       
except ValueError as err:
            print(err)
        except IOError as err:
            print(err)
        except Exception as err:
            print(err)
def main():
    try:
        #Getting input from the users
       
num1=float(input("Please enter your first value: "))
        num2=float(input("Please enter your second value: "))
        num3=float(input("Please enter your third value: "))
        #Creating temperatue file
       
test_file= open('D:\\Temperatures.txt', 'w')
        #writing input informatin to the file
       
test_file.write(str(num1) + '\n')
        test_file.write(str(num2) + '\n')
       test_file.write(str(num3) + '\n')
        #closing file
       
test_file.close()
        temp1 = tempearutefile(test_file)
        average = temp1.calculateAverage (float(num1),float(num2),float(num3))
        print("your average temperature is:", average)
        # exception errors
   
except ValueError as err:
        print(err)
    except IOError as err:
        print(err)
    except Exception as err:
        print(err)
    #Call to main
main()

==================================================================================

# Create Class class tempearutefile: def init self, filename seif. filename= fiïename def set filename (self, filename): def

return average # exception errors except ValueError as err: except IOError as err: except Exception as err: print (err) print

Add a comment
Know the answer?
Add Answer to:
Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Your assignment this week is to make your fractionType class safe by using exception handling....

    C++ Your assignment this week is to make your fractionType class safe by using exception handling. Use exceptions so that your program handles the exceptions division by zero and invalid input. · An example of invalid input would be entering a fraction such as 7 / 0 or 6 / a · An example of division by zero would be: 1 / 2 / 0 / 3 Use a custom Exception class called fractionException. The class must inherit from exception...

  • Type up the GeometricObject class (code given on the back of the paper). Name this file Geometric...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • Hello, In Python Enhance the prior assignment by doing the following 1) Create a class that...

    Hello, In Python Enhance the prior assignment by doing the following 1) Create a class that contain all prior functions MyLib # This function adds two numbers def addition(a, b): return a + b # This function subtracts two numbers def subtraction(a, b): return a - b # This function multiplies two numbers def multiplication(a, b): return a * b # This function divides two numbers # The ZeroDivisionError exception is raised when division or modulo by zero takes place...

  • Python only please, thanks in advance. Type up the GeometricObject class (code given on the back...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • in python im trying to get this to print to the file i it created def...

    in python im trying to get this to print to the file i it created def calculateTotal(): filename = input("Enter a name for the file : ")#ask users for a name for file no_of_students = int(input("Enter the number of students in class : ")) data = [] with open(filename,"w+") as f: for index in range(no_of_students): grades = input("Enter Name of student plus grade :").split() # store the student data in array "data" data.append(grades) # store the total grades in "total"...

  • Create a CalculatorTest class that contains the main method. 1. Get two double numbers as input...

    Create a CalculatorTest class that contains the main method. 1. Get two double numbers as input and create an object of the ScientificCalculator Class with those two numbers. 2. Then call the 8 operations one by one sequentially and display the result. Code must be written in Java. (Sample input/output: Enter number 1: 2 Enter number 2: 3 Add() result is : 5 Sub() result is: -1 ……. Power() result is: 8 …… sqrtNum1 result is:) The Problem: Given the...

  • class FileUtility: def __init__ (self, filename): self.__filename = filename def displayFile(self): # use loop structure to...

    class FileUtility: def __init__ (self, filename): self.__filename = filename def displayFile(self): # use loop structure to read and print each line of the file def main(): #1. create a new file and write the follwing lines to it. # #I never saw a Purple Cow, #I never hope to see one, #But I can tell you, anyhow, #I’d rather see than be one! # #2. create an object of FileUtility class #3. call the object's displayFile method main()

  • (python) [30] Implement exception handling with ValueError here in the following code: There are three blanks...

    (python) [30] Implement exception handling with ValueError here in the following code: There are three blanks you need to fill in. Write the answers in the space given for you. class Area: def __init__(self): self.x = 0 def setX(self n): if n<=0: else: self.x = n #main code a = Areal) inputValue = int(input("Enter a Value that is greater than 0")) a.setX(inputValue) print("Invalid Input Value Entered")

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • Please write a code in python! Define and test a function named posterize. This function expects...

    Please write a code in python! Define and test a function named posterize. This function expects an image and a tuple of RGB values as arguments. The function modifies the image like the blackAndWhite function, but it uses the given RGB values instead of black. images.py import tkinter import os, os.path tk = tkinter _root = None class ImageView(tk.Canvas): def __init__(self, image, title = "New Image", autoflush=False): master = tk.Toplevel(_root) master.protocol("WM_DELETE_WINDOW", self.close) tk.Canvas.__init__(self, master, width = image.getWidth(), height = image.getHeight())...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT