Sean.D
Sean.D

Reputation: 97

Random picking 3 chosen numbers

Ok, I am creating a game and no matter what I do, it just isn't working. So I have 3 numbers chosen, 25,50,75. I want to be able to random pick one of them. Then I will need to be able to add it to a total making it obviously an integer. I have imported random. I have tried random.sample but I can't get that one to be an number that I can add. I tried random.randint and that did not work at all. I have tried looking it up but it is pretty much all random in a range and not specific. Any ideas? Thanks in advance. I am using python 3.4.3.

Upvotes: 1

Views: 97

Answers (2)

mhawke
mhawke

Reputation: 87134

random.choice() is the way to go, however, random.sample() will also work if you use a sample size of 1 and you access the first element of the returned list.

>>> import random
>>> data = [25, 50, 75]
>>> random.choice(data)
50
>>> random.sample(data, 1)
[75]
>>> random.sample(data, 1)[0]
25

The point here is that random.sample() returns a list because that function is designed to select multiple values from the population. That's why you can not immediately use the result as an integer.

Upvotes: 0

Nehal J Wani
Nehal J Wani

Reputation: 16639

Use random.choice:

>>> import random
>>> random.choice([25,50,75])
25
>>> random.choice([25,50,75])
25
>>> random.choice([25,50,75])
75

Upvotes: 4

Related Questions