использование try-except-else-finally
хорошо, но я вижу, что это сбивает вас с толку, попробуйте сначала узнать try-except
.
у вас нет завершающего цикла в
def generateRandomNumber(myfile):
....
randomNumber = generateRandomNumber(myfile)
и
while line != "":
....
print( randomNumber )
line = myfile.readline()
должно быть
while line != "":
....
print( randomNumber )
line = myfile.readline()
А вот ваш рабочий код
import random
def generateRandomNumber():
randomNumber = random.randint(1,500)
return randomNumber
def writeRandom(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()
fileToBeWrittenTo.write(str( randomNumber ) + '\n' )
print( numberOfRandomNumbers, "numbers have been written" + \
" to the file ")
fileToBeWrittenTo.close()
displayNumber(myfile)
finally:
print("\nEnd of program")
def main():
myfile = str(input("Enter file name here "))
writeRandom(myfile)
def displayNumber(myfile):
try:
my_file = open(myfile,'r')
total = 0
NORN = 0
Avg = 0
line = my_file.readline()
while line != "":
randomNumber = int(line)
total += randomNumber
NORN += 1
Avg = total / NORN
print( randomNumber )
line = my_file.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")
my_file.close()
finally:
print("End of program")
main()