Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 848
user1871071 Avatar asked Nov 30 '22 13:11

user1871071


2 Answers

Use random choice

print random.choice([1,4,7])
like image 178
Kartik Avatar answered Dec 04 '22 16:12

Kartik


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']
>>> 
like image 36
namit Avatar answered Dec 04 '22 16:12

namit