Thomas Bengtsson
Thomas Bengtsson

Reputation: 399

Loop an answer Python

I have a an answer which I want to loop 10 times. The code looks like this right now:

top = int(input("Please tell us the highest number in the range: "))
bottom = int(input("Tell us the lowest number in the range: "))
print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)

This leaves me with the answer:
Please tell us the highest number in the range: 100
Tell us the lowest number in the range: 10
Batman picks the number 57 from the range between 10 and 100

Now I want to let Batman pick 10 random number from the range. I was thinking in the ways of this:

print("Batman picks the number",random.sample((bottom,top), 10),"from the range between",bottom,"and",top)

The problem is I get an error message saying: ValueError: Sample larger than population
What do I have to populate? Do I need another variable? Thanks in advance. Regards Thomas

Upvotes: 1

Views: 123

Answers (4)

CrazyCasta
CrazyCasta

Reputation: 28362

I'm assuming what you want is:

print("Batman picks the number",random.sample(range(bottom,top), 10),"from the range between",bottom,"and",top)

That is to say, I'm assuming you're looking to sample without replacement. If you want to print one line per number you could do:

for number in random.sample(range(bottom,top):
    print("Batman picks the number", number, 10),"from the range between",bottom,"and",top)

Upvotes: 1

pvkcse
pvkcse

Reputation: 99

I think you need to use xrange(bottom,top) instead of just (bottom,top) this would populate the population starting from bottom to top and then the random.sample(xrange(bottom,top),10) would now able to return the list of 10 random elements selected from the populated one leaving the original population unchanged.

Upvotes: 0

Christopher Peterson
Christopher Peterson

Reputation: 1671

You are getting the error about population because you are using it incorrectly. It doesn't expect a tuple of lower and upper ranges, but rather a list of elements to randomly choose from. It should be used like this:

>>> import random
>>> random.sample(range(0, 20), 10)
[7, 4, 8, 5, 19, 1, 0, 12, 17, 11]
>>> 

Or with any list of items as the first variable.

Upvotes: 1

zeldor
zeldor

Reputation: 101

Just use a while loop:

num = 10
while num>0:
    print("Batman picks the number",random.randint(bottom,top),"from the range between",bottom,"and",top)
    num -= 1

Upvotes: -1

Related Questions