Theist17 Theist17 - 1 month ago 11
Python Question

Multiple random choices with different outcomes

I'm trying to make a random NPC generator in Python--the last time I tried this, it was in PHP, and that went. . . strangely. What I'd like to be able to do with this is to call the defined variables within the string multiple times. I can do that by running a

for i in range(n)
loop, but that gets me the same random choice every time.

I've been looking, and I'm not totally sure that I've found how to call that function multiple times and get different results each time.

import random
gend = [ 'male', 'female' ]
race = [ 'Human', 'Elf', 'Orc', 'Halfling', 'Gnome', 'Half-Elf', 'Half-Orc', 'Outsider' ]
pers = [ 'leader-like, optimistic', 'bad-tempered, irritable', 'relaxed, peaceful', 'quiet, analytical' ]
hook = [ 'a chore that needs doing', "some concerns for another's well-being", 'an item that needs retrieving/delivering',
'a grudge', 'a person/organization in their way', 'a target on his or her back', 'an indiscretion that needs covering up',
'a debt that needs paying' ]
randgend = random.choice(gend)
randrace = random.choice(race)
randpers = random.choice(pers)
randhook = random.choice(hook)
print("A {} {}, with a {} disposition and {}.".format(randgend, randrace, randpers, randhook))


The line:

randgend = random.choice(gend)

makes randgend a single random choice from [ 'male', 'female' ], you're basically writing:

randgend = 'male'  # or female, whichever gets picked first

If you want it to be a function that returns a different random choice each time, you need:

randgend = lambda: random.choice(gend)

(see the docs on lambda expressions) then call it:

print("A {} {}, with a {} disposition and {}.".format(
    randgend(),  # note parentheses

Alternatively, much easier, just move the call to random.choice:

print("A {} {}, with a {} disposition and {}.".format(