Reputation: 71
This is my current code:
import random
while True:
try:
num = int(input("Enter the total number of digits you want to generate:"))
upper = int(input("Enter your highest number:"))
lower = int(input("Enter your lowest number:"))
if upper < 1 or lower < 1 or upper <= lower:
print ("Sorry, invalid. Make sure your upper bound is higher than lower bound, make sure all numbers are integers greater than 0.")
continue
if num < 1:
print ("Sorry, invalid. Try again.")
continue
**mylist = [0] * num
for x in range (lower, upper):**
The part directly above here is the part that I am not quite sure how to go forward on. I want to generate random numbers depending on the number the user enters and within the upper and lower bounds that the user enters into a list that displays here. Can someone guide me through this? thank you!
except:
print ("Sorry, invalid. Try again.")
else:
print ("Thank you.")
break
Upvotes: 0
Views: 440
Reputation: 3215
If you wanted a random subset of the numbers between lower and upper, inclusive, you could use:
random.sample(num, xrange(lower, upper + 1))
http://docs.python.org/2/library/random.html#random.sample
But I think you wanted duplicates to be possible, in which case use one of the other answers.
Upvotes: 0
Reputation: 1959
you probably need:
print [random.randint(lower, upper) for n in range(num)]
which displays a list of num random integers with minimum lower and maximum upper (inclusive).
Upvotes: 1
Reputation: 9853
You can use the randint
to generate numbers in the given range.
Return a random integer x such that a <= x <= b.
import random
print random.randint(a, b)
So to generate N numbers in the range a and b
numbers = [random.randint(a, b) for i in range(N)]
print numbers
Upvotes: 0
Reputation: 50185
If you replace your **
lines with the following, using random.randint(lower, upper)
, you'll display the list you want:
mylist = []
for _ in range(num):
mylist.append(random.randint(lower, upper))
print mylist
You could also do this with a list comprehension:
mylist = [random.randint(lower, upper) for _ in range(num)]
print mylist
Upvotes: 2