Question
i need help using python ( spyder)
only use files , loops if needed
is statement
do not use , def function or any other.
Exercise 1: Daily temperature is recorded for some weeks in files (templ.txt, temp2.txt, and temp3.txt; provided in the MOOD
0 0
Add a comment Improve this question Transcribed image text
Answer #1

NOTE: I have completed answer for your question. Please check and let me know if you have any queries. I will get back to you within 24 hours. Thanks for your patience.

Before running the program you should actually create temp1.txt, temp2.txt and temp3.txt files like below. Otherwise program will throw errors.

Unix Terminal> cat temp1.txt

3

1 20 22 23 21 24 20 25

2 21 25 26 - 24 21 22

3 28 2a 30 31 25 27 24

4 23 22 20 26 30 28 29

Unix Terminal> cat temp2.txt

3

1 20 22 23 21 24 20 25

2 21 25 26 25 24 21 22

3 28 26 30 31 25 27 24

4 23 22 20 26 30 28 29

Unix Terminal> cat temp3.txt

3

1 20 22 23 21 24 20 25

2 21 25 26 25 24 21 22

3 28 26 30 31 25 27 24

Unix Terminal>

Code:

#!/usr/local/bin/python3

def main():
   # reading file name from the user
   print('Enter input file? ')
   file_name = input().strip()

   # flag variable to determine if prog failed or successful
   is_prog_failed = False

   try:
       # reading the file contents into file_cont list
       file_cont = list()
       fp = open(file_name)
       for each_line in fp:
           fields = each_line.strip().split(' ')
           file_cont.append(fields)
       weeks = int(file_cont[0][0])
       no_of_recs = 0
       wk = []

       # iterating through each line in file
       for each_rec in file_cont[1:]:
           # validation on whether data is correct
           if len(each_rec) != 8:
               raise RuntimeError
           if no_of_recs > weeks:
               raise RuntimeError

           sum = 0
           for fields in each_rec[1:]:
               num = int(fields)
               sum += num  
           # calculating the average temperature
           avg = sum / (len(each_rec) - 1)
           no_of_recs += 1

           if no_of_recs > weeks:
               raise RuntimeError
          
           wk.append(avg)
   except IOError as e:
       is_prog_failed = True
       print('File does not exist it seems. please check')
       print(str(e))

   except ValueError as e:
       is_prog_failed = True
       print('=' * 20)
       print('Week\tAvg-Temp')
       print('=' * 20)
       for indx, value in enumerate(wk):
           print('%5d\t%.2f' % (indx+1, value))
       print('File contents invalid')
       print(str(e))

   except RuntimeError as e:
       is_prog_failed = True
       print('=' * 20)
       print('Week\tAvg-Temp')
       print('=' * 20)
       for indx, value in enumerate(wk):
           print('%5d\t%.2f' % (indx+1, value))
       print('Error: End of file expected.')
       print(str(e))

   # when program successfully executes without any failures
   if not is_prog_failed:
       print('=' * 20)
       print('Week\tAvg-Temp')
       print('=' * 20)
       for indx, value in enumerate(wk):
           print('%5d\t%.2f' % (indx+1, value))

if __name__=='__main__':
   main()

Code screenshot:

#1 /usr/local/bin/python3 def main(): # reading file name from the user print (Enter input file? file_name-input().strip) #except IOError as e: is_prog_failed True print(File does not exist it seems. please check) print(str(e)) except ValueErrorCode output screenshot:

Unix Terminal> python3 temp_process.py Enter input file? temp1.txt Week Avg-Temp 1 22.14 File contents invalid invalid litera

Add a comment
Know the answer?
Add Answer to:
I need help using python ( spyder) only use files , loops if needed is statement do not use , def...
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++] Using Files—Total and Average Rainfall Write a program that reads in from a file a...

    [C++] Using Files—Total and Average Rainfall Write a program that reads in from a file a starting month name, an ending month name, and then the monthly rainfall for each month during that period. As it does this, it should sum the rainfall amounts and then report the total rainfall and average rainfall for the period. For example, the output might look like this: During the months of March–June the total rainfall was 7.32 inches and the average monthly rainfall...

  • Therefore, for this program you will read the data in the file named weatherdata_2.txt into arrays...

    Therefore, for this program you will read the data in the file named weatherdata_2.txt into arrays for the wind speed and for the temperature. You will then use the stored data to calculate and output the average wind speed and the average temperature. Create a constant with a value of 30 and use that to declare and loop through your arrays and as a divisor to produce your averages. Here is the data file (below). 1. 14 25 2. 12...

  • on 13 of 18> The Department of Energy provides fuel economy ratings for all cars and...

    on 13 of 18> The Department of Energy provides fuel economy ratings for all cars and light trucks sold in the United States. The table contains the estimated miles per gallon for city driving for the 186 cars classified as midsize in 2016, arranged in increasing order. 16 16 16 16 16 16 16 16 16 16 16 16 1617 17 17 17 17 18 18 1818 18 18 18 18 18 19 19 19 19 19 19 19 19...

  • in java by using the loop Write a program that finds all students who score the...

    in java by using the loop Write a program that finds all students who score the highest and lowest average marks of the first two homework in CS (I). Your program should read the data from a file called "hw2.dat" and displays the output to another file called “hw2.out” and on the screen. The first line of the input file contains the number of students, N. The next N lines contain information about the students. Each data line contains student...

  • Use while loops, for loops, and if statements only- python 3 In order to pass time...

    Use while loops, for loops, and if statements only- python 3 In order to pass time during your vacation, you decided to go on a hike to visit a scenic lake up in the mountains. Hiking to the lake will take you a full day, then you will stay there for a day to rest and enjoy the scenery, and then spend another day hiking home, for a total of three days. However, the accursed weather this summer is ridiculously...

  • Python Help Please! This is a problem that I have been stuck on.I am only suppose...

    Python Help Please! This is a problem that I have been stuck on.I am only suppose to use the basic python coding principles, including for loops, if statements, elif statements, lists, counters, functions, nested statements, .read, .write, while, local variables or global variables, etc. Thank you! I am using python 3.4.1. ***( The bottom photo is a continuation of the first one)**** Problem statement For this program, you are to design and implement text search engine, similar to the one...

  • In this lab you will convert lab5.py to use object oriented programming techniques. The createList and...

    In this lab you will convert lab5.py to use object oriented programming techniques. The createList and checkList functions in lab5.py become methods of the MagicList class, and the main function of lab6.py calls methods of the MagicList class to let the user play the guessing game.                              A. (4pts) Use IDLE to create a lab6.py. Change the 2 comment lines at the top of lab6.py file: First line: your full name Second line: a short description of what the program...

  • Solve using Minitab. The table is observations on weekly operational downtime on a critical equipment (order...

    Solve using Minitab. The table is observations on weekly operational downtime on a critical equipment (order read top to bottom and left to right). The target value for the mean is 25. (a) Estimate the process standard deviation. (b) Set up and apply a tabular cusum chart for this process using standardized values h 5 and k = 2. (c) Interpret the cusum chart - 27 24 22 27 25 27 23 20 28 29 24 28 20 29 21...

  • A soft drink manufacturer uses fire agents to handle premium distribution for is various products. The marketing director desired to study the timeliness with which the premiums are distributed. Twent...

    A soft drink manufacturer uses fire agents to handle premium distribution for is various products. The marketing director desired to study the timeliness with which the premiums are distributed. Twenty transactions for each agent were selected at random and the time lapse (in days) for handling each transaction was determined. The results follow: Agent 1 Agent 2 Agent 3 Agent 4 Agent 5 24 18 10 15 33 24 20 11 13 22 29 20 8 18 28 20 24...

  • You must download the file "Assn3Ou#2W19" to use the required data. Ît gives the number of city-b...

    You must download the file "Assn3Ou#2W19" to use the required data. Ît gives the number of city-bus users (Ridership) on a public transportation system of a large city in 3 given working days chosen at random in units of hundreds. It gives this data separately for the 4 busy bus routes and for 5 time slots. Here, TSlotl: from start of day to 9:30 am, TSlot2: 9:30-12:30, TSlot3: 12:30 -15:30, TSlot4: 15:30 - 18:30 and Time-Slot5: 18:30 to end of...

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