sillydad
sillydad

Reputation: 13

python assign a variable to a randomly selected string

my children and I are messing with a random bedtime story generator. And apart from being amazed at how easy python is to use, we want to generate a random name for our protagonist, but for them to keep the same name throughout the story.

import random
names= ["Tim", "Ju Ju", "Legface", "Dusty", "Smudger"]
thing = ["princess", "elf", "fairy", "mermaid", "shoe maker"]

count = 0
while (count < 1):

  print "Once upon a time there was a ",
  print(random.choice(thing)),
  print "whose name was ",
  print(random.choice(names)),

so if the random name turns out to be Tim, I would like to continue the story as

print $thevariablethatisTim 
print "was a very happy man"

I realise this is a trivial thing, but I can't seem to get it right and we are having such a good laugh at bedtime with this.

Thanks in advance

Neil

Upvotes: 0

Views: 73

Answers (1)

timgeb
timgeb

Reputation: 78690

Just choose the name of your hero before you enter the while loop.

hero = random.choice(names)
# stuff
while some_condition:
    # do stuff
    print(hero) # or formatted string
    # do other stuff

any time you want to refer to your protagonist, use the variable hero instead of calling random.choice again.

Upvotes: 3

Related Questions