vendredi 30 octobre 2020

random integers reading and writing a file. Attempting to create multiple functions using a range 0,501

Im working on some python assignments for class and I cannot answer this question. I cannot find the error in my code. The error I receive is TypeError: 'function' object is not iterable. The question is:

a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file.

b. Random Number File Reader Function Write another function that reads the random numbers from the file "random.txt", displays the numbers, then displays the following data:

The total of the numbers

The number of random numbers read from the file

c. Main Function Write a main function that asks the user about how many random number the user wants to generate. It them calls the function in a. with the number the user wants as an argument and generates random numbers to write to the file. Next, it calls the function in b.

Here is my code:

import random
def random_Write(num):
# Open a file  for writing 
    file_w = open('random.txt', 'w')
       
    for i in range(0,num):
        rand = random.randrange(1,501)
        file_w.write(str(rand) + '\n')
        #closing file
    file_w.close()
        
def random_Read():
# Reading from file
    readFile = open('random.txt', 'r')
    count = 0
    total = 0
    for lines in random_Read:
        count +=1
        total += float(lines)

        print ('number count: ', str(count))
        print ('The numbers add up to: ', str(total))
        readFile.close()

def main():
    num = int(input("How many numbers would you like to generate?: "))
    random_Write(num)
    random_Read()

main()



Aucun commentaire:

Enregistrer un commentaire