Pulling raw_input options form a list
Hi I'm just starting to learn Python, I'm using the book "learn python the hard way" and one of the exercises is to build a simple game. I wanted to give options to the user from a list.
For example I would make a list called animals which would include 3 animals, lion tiger and fish. is is possible to offer selected elements from a list. I'm pretty sure it is but I just don't know how.
I was thinking some开发者_JAVA百科thing like this (obviously wrong but I think it helps to understand what I mean)
animals = ['Lion', 'Tiger', 'Fish']
print "which of these animals is your favourite?"
favourite = raw_input(animals[0] or animals[2])
if favourite = "Lion':
print "Nice choice"
else:
print "Bad choice"
Again I can't stress enough I know the above is really crap but essentially I want to offer certain items of a list as an option for the raw_input. In the above case the 0 item and the 2 item.
Thanks in advance for the help.
favourite = raw_input(' or '.join(animals))
This will take all the strings from the list animals
and join them together with or
in between, so you'll end up with
Lion or Tiger or Fish
if you want to add a question mark and space to the end, you can do
favourite = raw_input(' or '.join(animals) + '? ')
Also, on the line
if favourite = "Lion':
Your quotes don't match -- make sure to use either double or single quotes, not one of each. You also need to use ==
to compare two things; =
is for assigning a value, not comparing.
I would probably do it like
animal_string = ' or '.join(animals)
favourite = raw_input("Which of these animals is your favourite:\n{}? ".format(animal_string))
Which first makes the animal string, then formats the choices into the question on a new line (because of the \n
), and puts ?
after.
How about this?
favourite = raw_input("which of these animals is your favourite? "+",".join([str(a)+":"+b for a,b in enumerate(animals)])+">")
fav = animals[int(favourite)]
print fav+" is a nice choice indeed!. The big bear will kill you anyway. Good bye."
精彩评论