I am writing a program in which the user inputs a lower and higher limit for random numbers to be generated as well as an amount of random numbers to generate. After that, the program is to write to a new file, "randomnum.txt". I have all aspects working in my program except for the writing to the file. When the program is completed, there are no values written into the "randomnum.txt". Any help is appreciated! #Import random directory import random
#Import randint function
from random import randint
#Create and open the new file
new_file = open("/Users/masonadrales/Desktop/Python
Assignments/Randomwrite:read/randomnum.txt","w")
#Get input for the amount of numbers
while (True):
try:
number_random = float(input("How many random numbers would
you like? "))
if (number_random < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Ask for the lower limit of the random range
while (True):
try:
lower_limit = float(input("What is the lowest the random
number should be: "))
if (lower_limit < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Ask for the higher limit of the random range
while (True):
try:
high_limit = float(input("What is the highest the random
number should be: "))
if (high_limit < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Attempt #1 to generate (number_random) amount of random numbers
between lower and high limit
try:
for randomNumber in range(int(number_random)):
line = str(random.randint(lower_limit, high_limit))
new_file.write(line)
print(line)
except ValueError:
new_file.close()
#Print where the numbers were written to
print("The random numbers were written to randomnum.txt.")
Aucun commentaire:
Enregistrer un commentaire