user1871071
user1871071

Reputation: 67

How do I choose between 3 random numbers in Python 2.7?

Lets say I want to generate one of the numbers 1, 4, or 7.

How would I do this? I originally thought I could write

import random
rand.randint(1,4,7)

but that doesn't seem to work. Thanks.

Upvotes: 4

Views: 12735

Answers (2)

namit
namit

Reputation: 6957

import random
import string
def random_number(length):
    return [random.choice(string.digits) for x in range(length)]

>>> random_number(5)
['0', '1', '1', '9', '0']
>>> random_number(2)
['5', '9']
>>> random_number(1)
['0']
>>> random_number(11)
['2', '3', '4', '7', '1', '8', '1', '9', '3', '6', '9']
>>> 

Upvotes: 1

Kartik
Kartik

Reputation: 9873

Use random choice

print random.choice([1,4,7])

Upvotes: 21

Related Questions