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...

  • 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...

  • 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...

  • (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...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • class Leibniz:    def __init__(self):        self.total=0               def calculate_pi(self,n):       ...

    class Leibniz:    def __init__(self):        self.total=0               def calculate_pi(self,n):        try:            self.total, sign = 0, 1            for i in range(n):                term = 1 / (2 * i + 1)                self.total += term * sign                sign *= -1                self.total *= 4            return self.total        except Exception as e:   ...

  • Python3, write a program, specific information is in the graphs, I got 7 marks out of...

    Python3, write a program, specific information is in the graphs, I got 7 marks out of 10, you may change my codes to let it gives correct output,restrications are also on the graph, for loop, in key word, enumerate,zip,slices, with key word can't be used. All the information is on the graph, is_shakespeare_play(line) may be a function given that can check whether is Shakespeare play Question 2- 10 marks Write the function keep titles short (filename, max charactars) which takes...

  • // 2. Practice debugging this program. It has approximately 22 compiler errors, 1 logic error and...

    // 2. Practice debugging this program. It has approximately 22 compiler errors, 1 logic error and //1 usability error. Identify them all. import java.util.scanner; //This program finds the average of three input values. public class Arithmeticx { public static void main( String [] args ) // declare variables double number1, number2, number3; // input data scanner in = newscanner( ); System.out.print( "Number 1? " ); System.out.print( "Number 2? " ); System.out.print( "Number 3? " ); number 1 = in.nextDouble; number...

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
ADVERTISEMENT