Python random numbers multiple times
17,375
Solution 1
This will produce a list of random integers in range number1
to number2
rnumber = [random.randint(number1, number2) for x in range(times)]
For more information, look at List Comprehension.
Solution 2
Use generators and iterators:
import random
from itertools import islice
def genRandom(a, b):
while True:
yield random.randint(a, b)
number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
total = int(input('Put in how many numbers generated:'))
rnumberIterator = islice(genRandom(number1, number2), total)
Solution 3
Use a "for" loop. For example:
for i in xrange(times):
# generate random number and print it
Solution 4
I would recommend using a loop that simply adds to an existing string:
import random
from random import randint
list=""
number1=input("Put in the first number: ")
number2=input("Put in the second number: ")
total=input("Put in how many numbers generated: ")
times_run=0
while times_run<=total:
gen1=random.randint(number1, number2)
list=str(list)+str(gen1)+" "
times_run+=1
print list
Author by
user2832472
Updated on June 04, 2022Comments
-
user2832472 almost 2 years
import random def main(): uinput() def uinput(): times = int(input('How many numbers do you want generated?')) number1 = int(input('Put in the first number:' )) number2 = int(input('Put in the second number:')) rnumber = random.randint(number1, number2) print (rnumber) main()
I am messing around in Python, and I want my program to generate random numbers. As you can see I have already accomplished this. The next thing I want to do is have it generate multiple random numbers, depending on how many numbers the "user" wants generated. How would I go about doing this? I am assuming a loop would be required.
-
user2864740 over 10 yearsSo read about loops, write a loop, and report back!
-
Srinivas Reddy Thatiparthy over 10 yearsif number1>number2 you will get
ValueError
-
Eduardo Pignatelli over 4 yearsIf you know the range you want to pick from, you can also use
random.choices(range, k=n)
, wheren
is the number of numbers to yield.
-