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 something 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."
Related
I'm trying to make an electronic menu service for a diner, one of the required functions is to be able to add to the menu. I'm not very good at all of the debugging side of things and I'm now getting an error saying
Can only concatenate list (not string) to list
I don't know what it means and have tried everything to get rid of the error but it won't go away. can you guys help me out?
menu = (["all day breakfast large, £5.50", "all day breafast small, £3.50", "hot dog, £3.00", "burger, £4.00", "cheese burger, £4.25", "chicken goujons, £3.50", "fries, £1.75", "salad, £2.20", "milkshake, £2.20", "soft drinks, £1.30", "still water, £0.90", "sparkling water, £0.90"])
for i in menu:
text_file.write(i)
elif menu_editing == "add":
add_item_number = (input("please enter what number you would like to add the new item. "))
add_item_name = (input("""please enter the name of the item like this: all day breakfast large"""))
add_item_price = (input("please enter the price of the item you wish to add without the pound sign. "))
menu == menu + "",add_item_name,"£"+add_item_price[add_item_number]
Is menu variable a list? If it is, you should use menu.append(<stuff you want to append as string here>)
Also, you get three string back from your input, what are you trying to achieve with add_item_price[add_item_number]? From the little information that we have, I assume you want to display the price * itemnumber? You can do that like this:
menu.append(f"{add_item_name}, £ {int(add_item_price)*int(add_item_number)}")
Note the f" " notation, which allows for reference to variables in string using accolades.
I am new to python and want to write a simple text adventure game. The player enters a tavern and interacts with the guests. The game takes place in a fantasy setting, where there are multiple races. I want to randomly generate each guest and then interact with them in the tavern. Here is my simplified code:
import random
class guest:
def __init__(self,race,name,fav_food):
self.race = race
self.name = name
self.fav_food = fav_food
guest1 = guest('human','Tom','chicken')
print('The first guest you meet is a '+guest1.race+ ' named '+guest1.name+ '. He really likes '+guest.fav_food+ '.')
So far so good. But here i get stuck: I want the set of data for guest1 to be randomly selected from other guests that i create beforehand.
guest1 = guest('human','Tom','chicken')
guest1 = guest('dwarf','Bjorn','potatoes')
guest1 = guest('orc','Orok','pork')
guest1 = guest('elf',,'Eli','Salad')
How do i do that? Sure, i could name them guest2,guest3 etc., but then it wouldn´t be random anymore.
When i run the code, i want to randomly encounter Tom,Bjorn,Orok or Eli
I would really appreciate any help on this matter.
Sorry for my bad english :)
You can put all of your guests into an array and use random.choice to set random guest to a variable called random_guest.
guests = [guest('human', 'Tom', 'chicken'),
guest('dwarf', 'Bjorn', 'potatoes'),
guest('orc', 'Orok', 'pork'),
guest('elf', 'Eli', 'Salad')]
random_guest = random.choice(guests)
print('The first guest you meet is a '+ random_guest.race + ' named '+ random_guest.name + '. He really likes '+ random_guest.fav_food + '.')
It's perfectly fine to use random.choice to select one character from a list of characters but sometimes random.choice is not what you want.
I mean, no problem if your game is conversational: you meet George, move on to Rita and next it's George again...
But, if your game implies that you KILL George (or George kills you... Game Over) then you KILL Rita, well it would be strange (unless your game is titled Zombie34 — the Tavern Massacre) if George comes back to harass you.
If your use case is the second one, I'd suggest using a combination of random.shuffle
characters = [...]
random.shuffle(characters)
and the .pop method of a list
# whenever you need a new character
try:
a_character = characters.pop()
except IndexError:
# if you are here, you have exausted your list of characters,
# you could consider generating a new list and possibly starting a new level
I am trying to create a questionnaire where it asks multiple yes/no questions, and after receiving all of the responses a different output is shown depending on the combination of answers provided.
For example, if there were three questions and someone answered no, no, then yes, they would see one output (just a simple sentence that I will create), but if someone else answered yes, no, yes, they would see a different response at the end. I don't want to provide feedback after each individual question, only when all questions have been answered.
I was trying to use if/else, but that didn't seem to be working for my purposes (at least the way I was doing it, but I am very new to Python!). I'm sorry that I don't have much to work with, but I am trying to learn and have been doing Google search after Google search to no avail. Thank you!!
EDIT: Here's what I've been trying. Is there any way to extend on this? What I've done is based on my limited knowledge of Python.
female = raw_input("Are you female?")
over18 = raw_input("Are you over 18?")
shopping = raw_input("Do you like to go shopping?")
And then I know how to do something like
if female=="yes":
print "blahblah"
else:
print "something else"
But I don't know how to use all three responses to contribute to what will print. I also can't figure out how to restrict each question to just a yes/no answer.
EDIT 2:
Can I use multiple if statements as shown below? I know how to use just one response to change the output, but having three influence just one output is just throwing me for a loop.
female = raw_input("Are you female?")
over18 = raw_input("Are you over 18?")
shopping = raw_input("Do you like to go shopping?")
if (female=="yes" and over18=="yes" and shopping=="yes"):
print "1"
if (female=="yes" and over18=="yes" and shopping=="no"):
print "2"
if (female=="yes" and over18=="no" and shopping=="no"):
print "3"
if (female=="yes" and over18=="no" and shopping=="yes"):
print "4"
if (female=="no" and over18=="yes" and shopping=="yes"):
print "5"
if (female=="no" and over18=="yes" and shopping=="no"):
print "6"
if (female=="no" and over18=="no" and shopping=="yes"):
print "7"
if (female=="no" and over18=="no" and shopping=="no"):
print "8"
else:
print "invalid"
It looks like that is functioning relatively well, but no matter what combination of "yes" and "no" I use it will give me the correct number output but then also say "invalid." However, if I take out the else, it won't restrict the answers to "yes" or "no," will it?
One way that occurs to me is to make a dictionary keyed by a tuple of yes/no responses - one for each question. So if you have, say, 2 questions - 1 and 2, you'd have 4 possible outcomes. YY, YN, NY, and NN. You can create a dictionary with keys that correspond to these. So something like
def ask_question(qn):
resp = raw_input(qn)
if resp.lower() in ["yes", "y"]: # Handles Yes, yes etc.
return True
else:
return False
responses = {(True, True) : "Old Male",
(True, False) : "Young Male",
(False, True) : "Old Female",
(False, False) : "Young Female"}
answers = []
questions = ["Are you male?", "Are you over 18?"]
for q in questions:
answers.append(ask_question(q))
print responses[tuple(answers)]
Since the actual answers are in data (rather than code), you can read these out from a file which you can edit/generate easily. It's a much more conventient way of mananging than a huge and hairy if/elif/else block.
How to print different items depending on a random print in Python? Here is part of my script.
Mage = "Mage"
Warrior = "Warrior"
Thief = "Thief"
skilltree = (Mage, Warrior, Thief)
print random.choice (skilltree)
Now say it randomly chose Warrior. In my next script it would print 7 skills. But if it were to randomly choose Thief or Mage they would of been 7 completely different skills. So I want the 7 skills you get to depend on the randomly chosen skill tree.
You have done the hard part. Now you just need to map the skills to each category. For instance, using a dictionary:
skills = {'Mage': range(7), 'Warrior': range(7,14), 'Thief': range(14,21)}
choice = random.choice(skilltree)
print skills[choice]
This will print the list of skills you associated with the chosen skilltree. I used range just to illustrate, you could have a list of strings with the skills.
I will just illustrate a little bit further with Paulo's example in case you are not familiar with using a dictionary (and like he said using a dictionary is probably the best choice for a mapping).
MageSkills = ["Mskill1", "Mskill2"]
ThiefSkills = ["Tskill1", "Tskill2"]
WarriorSkills = ["Wskill1", "Wskill2"]
skills = {'Warrior': WarriorSkills, 'Mage': MageSkills, 'Thief': ThiefSkills}
choice = 'Warrior'
print(skills[choice])
The general concept of a solution has been outlined by others, but I think they're missing the key misunderstanding behind your question, which is how to persist something that you randomly chose and printed. As far as that goes, and for understanding this is what I would do:
import random
classes = ("Mage", "Warrior", "Thief")
skill_dictionary = {"Mage": ["Fireball", "Ice Blast"...], "Warrior": [...]} # etc
random_class = random.choice(classes) # Keep a version around for yourself
print random_class # print the version you just saved so you still have a copy
print skill_dictionary[random_class] #Then use the saved version to get the skill list
An important thought distinction to have here is separating getting the data from displaying it. First you randomly choose the data, and only after you already have it do you decide to show it to the user with your print statement.
The dictionary is just a key/value store (something that maps keys(your classes) to values (your skills)). It happens to fit this problem well, but you could implement this in other ways.
I am working on a quiz game and when I get asked any question, i type in the right answer, which I defined in the a variable that holds that correct answer but it says it is wrong if it isn't the first word for that variable (In this case, Metallica). Here is what my code looks like.
q1answer = "Metallica" or "metallica" or "Slayer" or "slayer" or "Anthrax" or "anthrax" or "Megadeth" or "megadeth"
answerinput = str(input("name one of the 'Big Four' metal bands'"))
if answerinput == q1answer:
print ("You got the right answer!")
else:
print ("That is the wrong answer...")
Now, if I was to type in 'Metallica' it would be correct because it is the first word for the q1answer variable. But, if I type metallica, Slayer, slayer, Anthrax, anthrax, megadeth or Megadeth, I would get the wrong answer text. Is there a way for all of these strings to be working for this one variable if i was to type anything but the first word in that variable? I'm a rookie in python so any help would be great.
Put them in a set and test for a correct answer using in instead:
q1answer = {"Metallica", "metallica", "Slayer", "slayer", "Anthrax", "anthrax", "Megadeth", "megadeth"}
...
if answerinput in q1answer:
Right now, your series of ors is just resulting in the first one - "Metallica". You can also stop duplicating every name for case-insensitivity and instead use lower:
if answerinput.lower() in q1answer:
Change your code like this:
q1answer = ("metallica", "slayer", "anthrax", "megadeth")
...
if answerinput.lower() in q1answer:
...