0

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

3
  • 1
    name = random.choice(names)?! Commented Jan 22, 2016 at 21:48
  • 1
    Well, you're using variables, and you're calling functions. Do you know how to assign the return value of a function call to a variable? Commented Jan 22, 2016 at 21:48
  • Do you need if statement to check whether you random.choice is Tim? Commented Jan 22, 2016 at 21:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.