Question

Is there another way to write this code in python? def processFile(): inFile = open("inputFile.txt") sumOfNumbers...

Is there another way to write this code in python?

def processFile():
inFile = open("inputFile.txt")
sumOfNumbers = 0
count = 0
minimum = 0
maximum = 0
for line in inFile:
n = int(line)
if count == 0:
minimum = n
maximum = n
else:
if n > maximum:
maximum = n
if n < minimum:
minimum = n
count = count + 1
sumOfNumbers = sumOfNumbers + n
inFile.close()
avg = (int)(sumOfNumbers / count)
avg = sumOfNumbers / count
outFile = open("outputFile.txt",'w')
outFile.write("There are " + (str) (count) + " numbers in this file.\n")
outFile.write("The minimum number is = " + (str) (minimum) +".\n")
outFile.write("The maximum number is = " + (str) (maximum) +".\n")
outFile.write("The average is = " + (str) (avg) +".")
outFile.close()

processFile()

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

`Hey,

Note: If you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

Note: Brother sometimes while uploading on HomeworkLib the indentations change. So, I request you to verify it with screenshot once. This is the link where I have saved the code too

https://trinket.io/python3/7111f5b331

I have changed the whole way of how it was working. Now, it uses List to append it then at the end together it uses min and max function

def processFile():
inFile = open("inputFile.txt")
sumOfNumbers = 0
count = 0
minimum = 0
maximum = 0
L1=[];
for line in inFile:
n = int(line)
L1.append(n);
count = count + 1
sumOfNumbers = sumOfNumbers + n
inFile.close()
maximum=max(L1);
minimum=min(L1);
avg = (int)(sumOfNumbers / count)
avg = sumOfNumbers / count
outFile = open("outputFile.txt",'w')
outFile.write("There are " + (str) (count) + " numbers in this file.\n")
outFile.write("The minimum number is = " + (str) (minimum) +".\n")
outFile.write("The maximum number is = " + (str) (maximum) +".\n")
outFile.write("The average is = " + (str) (avg) +".")
outFile.close()

processFile()

M Inbox - gurkaranpreet.singh.m X Trinket X CIs There Another Way To Write x C My Q&A | Chegg.com * Ellie Goulding - Love Me

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
Is there another way to write this code in python? def processFile(): inFile = open("inputFile.txt") sumOfNumbers...
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
  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • Python Problem Hello i am trying to finish this code it does not save guesses or...

    Python Problem Hello i am trying to finish this code it does not save guesses or count wrong guesses. When printing hman it needs to only show _ and letters together. For example if the word is amazing and guess=a it must print a_a_ _ _ _ not a_ _ _ _ and _a_ _ _ separately or with spaces. The guess has a maximum of 8 wrong guesses so for every wrong guess the game must count it if...

  • Python Error: Writing a program to complete the following: Prompt the user for the name of...

    Python Error: Writing a program to complete the following: Prompt the user for the name of an input file. Open that file for input. (reading) Read the file using a "for line in a file" loop For each line,  o print the line and compute and print the average word length for that line. Close the input file Sample output: MY CODE IS WRONG AND NEED HELP CORRECTING IT!!! ------------------------------------------------------------------------------------------------------------------------ DESIRED OUTPUT: Enter input file name: Seasons.txt Thirty days hath September...

  • Open read a text file “7NoInputFileResponse.txt” that contains a message “There were no arguments on the...

    Open read a text file “7NoInputFileResponse.txt” that contains a message “There were no arguments on the command line to be tested for file open.” Append to the program to output to the text log file a new line starting with day time date followed by the message "SUCCESSFUL". Append that message to a file “7Error_Log_File.txt” . ?newline Remember to be using fprintf using stderr using return using exit statements. Test for file existence, test 7NoInputFileResponse.txt file not null (if null...

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

  • i have my code all the way complete except one syntax error code( import math f=open("101primes.txt")...

    i have my code all the way complete except one syntax error code( import math f=open("101primes.txt") primes=[] for line in f: primes.append(int(line)) thelist=[2692493, 2692503, 4632703, 8767843, 7982119, 7983121, 13065521 , 11505341 ,11505343 ,14123649 ,14123651] for i in thelist: oof=1 TV=int(math.sqrt(i)) for x in primes: if(x>TV): break elif(i%x == 0): oof=0 break if(oof): print str(i)+ "is a prime number" else: print str(i)+ "is not a prime number" )

  • // Retire.cpp : Defines the entry point for the console application. // program to convery years...

    // Retire.cpp : Defines the entry point for the console application. // program to convery years to retire // sumin Kang // 9/26/17 #include "stdafx.h" #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; int main() { //declare files ifstream inFile; ofstream outFile; // declare constants and variables string name; int age; int ageInRetire; // open files inFile.open("D:\\retire"); outFile.open("D:\\retire"); // get input from user cout << "What is your name?"; getline(inFile, name); cout << "How old are you?";...

  • I need python help .. I need to know if a user were to input 3...

    I need python help .. I need to know if a user were to input 3 commands to a program and run it such as specify: Usage: ./filemaker INPUTCOMMANDFILE OUTPUTFILE RECORDCOUNT (./filemaker is the program)( (INPUTCOOMANDFUILE= a text file that contains key words that need to be searched through then decided what to do ) (RECORDCOUNT= number) Given an input file that contains the following: That specifies the text, then the output, and the number of times to be repeated...

  • Convert Python to Java def read_fsm(filename): fh = open('fsm.txt','r') contents = fh.readlines() sigma...

    Convert Python to Java def read_fsm(filename): fh = open('fsm.txt','r') contents = fh.readlines() sigma = list(contents[0].rstrip().split(' ')) table = {} n = int(contents[1]) for i in range(n): table[i] = {} final = list(map(int,contents[2].rstrip().split(' ')))    for line in contents[3:]: fro,ip,to = line.split(' ') fro = int(fro) to = int(to) table[fro][ip] = to print(table) fh.close() return table,final    def runString(table,final,string): current = 0 for i in string: current = table[current][i] if current in final: print(string,'--> ACCEPT') else: print(string,'--> REJECT')    def readInput(table,final): fh = open('Strings.txt','r')...

  • Python: 1) Consider the following code segment: try : inputFile = open("lyrics.txt", "r") line = inputFile.readline()...

    Python: 1) Consider the following code segment: try : inputFile = open("lyrics.txt", "r") line = inputFile.readline() print(line) _____________________ print("Error") What should be placed in the blank so that the program will print Error instead of crashing if an exception occurs while opening or reading from the file? Group of answer choices a- except RuntimeError : b- except EnvironmentError : c- except IOError : d- except IndexError : 2) Consider the following code segment: line = "hello world!" parts = line.split()...

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