SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:8 | ISBN:9780132576376 | Edition: 2

Question

Random Number File Reader
This exercise assumes you have completed Programming Exercise 7, Random Number File Writer. Write another program that reads the random numbers from the file, display the numbers, and then display the following data: 

  • The total of the numbers
  • The number of random numbers read from the file
TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Random Number File Reader Python code:

#Reads the random numbers from the file, display the numbers, 
#and then display the data: 
#The total of the numbers
#The number of random numbers read from the file
def readRandomNums(inputFile):
    with open(inputFile, 'r') as file:
        numbers = file.readlines()

    return numbers
inputFile = input("Enter the name of the file to read: ")
numbers = readRandomNums(inputFile)

# Display the numbers
print("Random Numbers:")
for number in numbers:
    print(number.strip())

total = sum(map(int, numbers))
count = len(numbers)

print(f"\nTotal of the numbers: {total}")
print(f"Number of random numbers read: {count}")

Data in "numbers.txt" file:

83
28
93
28
41
46
55
70
2
3
83
47
30
19
2

Executed Output:

Enter the name of the file to read: numbers.txt
Random Numbers:
83
28
93
28
41
46
55
70
2
3
83
47
30
19
2

Total of the numbers: 630
Number of random numbers read: 15

 

0 0

Discussions

Post the discussion to improve the above solution.