jeudi 29 novembre 2018

How to fix while loop within function?

My code works, and asks to name the file, and how many numbers. But it just keeps asking for numbers, and if I put zero then it does what it is suppose too. any help at all is appreciated very much. I just don't know how to fix the code, and it is really bugging me.

import random
    def generateRandomNumber(myfile):
        try:
            fileToBeWrittenTo = open(myfile,"w")
            numberOfRandomNumbers = int(input("How many numbers" + \
                                          " should the random file hold?:" ))
        except Exception as potentialError:
            print("An error has occured:", potentialError )
        else:
            for randomNumberCount in range(1, numberOfRandomNumbers + 1 ):
                randomNumber = generateRandomNumber(myfile)
                fileToBeWrittenTo.write(str( randomNumber ) + '\n' )
            print( numberOfRandomNumbers, "numbers have been written" + \
                   " to the file ")
        finally:
            fileToBeWrittenTo.close()
            print("\nEnd of program")
        displayNumber(myfile)
        randomNumber = random.randint(1,500)
        return randomNumber
    def main():
        myfile = str(input("Enter file name here "))
        with open(myfile, 'w+') as f:
            generateRandomNumber(myfile)

        return f
        myfile.close





    def displayNumber(myfile):
        try:
            myfile = open(myfile,'r')
            total = 0
            NORN = 0
            Avg = 0
            line = myfile.readline()
            while line != "":
                randomNumber = int(line)
                total += randomNumber
                NORN += 1
                Avg = total / NORN
                print( randomNumber )
            line = myfile.readline()
        except IOError:
            print("Problem with file being opened")
        else:
            print("The average of the numbers is " + str(Avg))
            print("The total of all the numbers is " + str(total)+\
              "\nThere are " + str(NORN)+\
              " in the file")
            myfile.close()
        finally:
            print("End of program")

    main()




Aucun commentaire:

Enregistrer un commentaire