Writing generated numbers in a text file in Python
So I tried looking through other posts and even asked a friend before resorting to actually asking here. I have a homework assignment that requires me to create a Python program that generates random numbers based on how many numbers the user enters. For example, if they enter that they want to generate 5 numbers ... the program will do just that. Now my problem is that I created the following:
import random
def main():
howMany = 0
numbers = 0
howMany = int(input('How many numbers would you like to generate?: '))
infile = open ('rand_write.txt', 'w')
for n in range(1,howMany):
numbers = random.randint(1,115)
infile.write(str(numbers))
infile.close()
main()
Everything works fine until it's time to get 5 numbers in a text file. I can't ... for the life of me ... figure out what I'm doing wrong. The program writes to a text file, but only writes a random number, not 5. I would really appreciate any guidance and advice on how to figure out what I should do to solve this problem. Thank you very much!
source to share
The problem is that you are rewriting numbers
in a loop for
:
for n in range(1,howMany):
numbers = random.randint(1,115)
Instead, you want to create a list named numbers
as such:
numbers = []
for n in range(1,howMany):
numbers.append(random.randint(1,115))
And then use '\n'.join(map(str, numbers))
to convert to string and then write it the same way as before: import random
def main():
howMany = 0
numbers = []
howMany = int(input('How many numbers would you like to generate?: '))
infile = open ('rand_write.txt', 'w')
for n in range(1,howMany):
numbers.append(random.randint(1,115))
infile.write('\n'.join(map(str, numbers)))
infile.close()
main()
source to share
Your indentation is wrong. You need to put a tab in front of infile.write(str(numbers))
it to make sure it runs on every loop. Otherwise, you just write down the last number.
You can also write a separator between the numbers.
Finally, you can only make one call to generate random numbers like this:
numpy.random.random_integers(1,115, howMany)
source to share