I can select randomly from a list… but how do I use this as a variable for different commands? Python

Question:

Lets say I have the following:

foo = ('animal', 'vegetable', 'mineral')

I want to be able to randomly select from the list THEN, depending on which one is selected, have a set of commands to follow.

For instance, if ‘animal’ was randomly selected, I want the message print(‘rawr I’m a tiger’), or if it was ‘vegetable’ print(‘Woof, I’m a carrot’) or something.

I know to randomly select it is:

from random import choice
print choice(foo)

but I don’t want the choice to be printed, I want it to be secret.

Asked By: pythonnoobface

||

Answers:

If you don’t want to print it, just assign it to a variable:

element = choice(foo)

To then pick the appropriate message, you might want a dictionary from the element type (animal/mineral/vegetable) to a list of random messages associated with that element type. Take the list from the dictionary, then pick a random element to print…

Answered By: Jon Skeet
import random
messages = {
    'animal': "rawr I'm a tiger",
    'vegetable': "Woof, I'm a carrot",
    'mineral': "Rumble, I'm a rock",
}
print messages[random.choice(messages.keys())]

If you wanted to branch off to some other sections in an app, something like this might suite better:

import random

def animal():
    print "rawr I'm a tiger"

def vegetable():
    print "Woof, I'm a carrot"

def mineral():
    print "Rumble, I'm a rock"

sections = {
    'animal': animal,
    'vegetable': vegetable,
    'mineral': mineral,
}

section = sections[random.choice(sections.keys())]
section()
Answered By: bradley.ayers

You just assign your randomly selected item to a variable.

Answered By: Rabarberski
>>> messages = {"animal" : "Rawr I am a tiger", "vegtable" :"Woof, I'm a carrot", "mineral" : "I shine"}
>>> foo = ('animal', 'vegtable', 'mineral')                                     >>> messages[random.choice(foo)]"Woof, I'm a carrot"

>>> messages[random.choice(foo)]
"Woof, I'm a carrot"

or more condensed if you don’t have to keep a tuple:

messages[random.choice(messages.keys())]
Answered By: Mike Lewis
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.