Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a random event in Python by picking a random variable?

Tags:

python

random

Let's say I have to variables, dog and cat. Dog = 5, and cat = 3. How would I tell Python to pick one of these variables by random and print it to the screen?

like image 204
Noah R Avatar asked Dec 08 '22 01:12

Noah R


2 Answers

import random
print random.choice([dog, cat])

It's that simple. choice() takes a sequence and returns a random selection from it.

like image 50
Rafe Kettler Avatar answered Jan 18 '23 23:01

Rafe Kettler


You can put all the variables you want to choose from in a list and use the random module to pick one for you.

import random
dog = 5
cat = 3
vars = [dog,cat]
print random.sample(vars, 1)

The sample method takes two arguments: the population you want to choose from, and the number of samples you want (in this case you only want one variable chosen).

like image 22
user470379 Avatar answered Jan 18 '23 22:01

user470379