def flips():
print "Alright the workout of the day is a front-flip, back-flip and
side flip"
flips_left = ['side flip', 'front flip', 'back flip']
flip_choice = None
while len(flips_left) > 0:
flip_choice = raw_input("Do a flip ")
if "side flip" in flip_choice:
print flip_lines['side_flip']
flips_left.remove('side flip')
print "Great! Now just do the rest: %s" % flips_left
elif "front flip" in flip_choice:
print flip_lines['front_flip']
flips_left.remove('front flip')
print "Good stuff! This is what you have left: %s" %
flips_left
elif "back flip" in flip_choice:
print flip_lines['back_flip']
flips_left.remove('back flip')
else:
"That is not a type of flip! Try again!"
print "Great! You completed the WOD!"
This question is actually a two-parter:
What I'm doing is telling the user to input 'side flip', 'back flip' or 'front flip'. When they do the input is removed from the list 'flips_left'. That works fine until say the user enters the same flip again, I want to return a message telling them they did that already, and to try again.
For some reason I can't get the program to print the else statement when the user inputs something that isn't 'side flip' 'front flip' or 'back flip'. Any ideas? Thanks!
Your if statement logic isn't checking what remains in flips_left
Your best bet would be to do something more generic such as:
if flip_choice in flips_left:
print flip_lines[flip_choice]
flips_left.remove(flip_choice)
else:
print "Some error"
If you want to keep track of choices already made you could use a dictionary to keep track of which flips have already been performed.
flips_left = {'side flip':True, 'front flip':True, 'back flip':True}
...
if flip_choice in flips_left:
if flips_left[flip_choice]:
print flip_lines[flip_choice]
flips_left[flip_choice] = False
else:
print "You have already done %s!" % flip_choice
else:
print "That is not a valid flip"
Try adding a print keyword before your message:
else:
print "That is not a type of flip! Try again!"
Related
So, in this block of code, I am having the user input a string. The user has to answer with one of the given options (which is shown in the for-loop). If the user does not respond with any option, the else statement should be used, restarting the block. However, no matter what the input for choice1 is, the if statement is always used. I am not sure what is going on with the if,elif,else statement.
print 'You enter door 1 and find a hideous internet troll.'
print "The troll says, 'LOOK AT THIS LOSER"
options = ["YOU'RE THE LOSER", "I don't care." , "YOU'RE FAT"]
for x in options:
print "\t :> %s" % x
choice1 = raw_input("What is your response? :>")
if 'loser' or 'fat' in choice1:
print "You are sucked into the troll's behaviour and are driven insane"
print "After three days of insanity, you starve to death"
dead()
elif 'care' in choice1:
print 'The troll cannot feed off of your anger.'
print 'The troll starves and you recover one piece of the lever from his stomach.'
change()
entrywayopen()
return incomp1 == True
else:
unknown()
change()
door1()
In the expression if 'loser' or 'fat' in choice1: only 'fat' gets checked against being in choice1. 'loser', being a non-empty string is simply interpreted as a True so you have if True or 'fat' in choice1 which always yields True. Try instead if ('loser' in choice1) or ('fat' in choice1):.
I am trying to program a simple text based game. In order to do this, I am having the user go to three separate rooms to complete a task and receive a piece. In order to do this, I have a value set as False then, upon completion of the room, I have a return statement used to change the Boolean value to True. When all three room functions return a True, then I set that to open a function that progresses the game. As of know, however, the return does not take place, and thus the Boolean values remain unchanged.
Here is an example of one door function:
def door1(incomp1):
if incomp1 == False:
print 'You enter door 1 and find a hideous internet troll.'
print "The troll says, 'LOOK AT THIS LOSER'"
options = ["YOU'RE THE LOSER", "I don't care." , "YOUR MOM IS FAT"]
options2 = [1,2,3]
for x in options:
print "\t :> %s" % x
choice1 = raw_input("What is your response? :>")
if ('loser' in choice1) or ('fat' in choice1):
print "You are sucked into the troll's behaviour and are driven insane"
print "After three days of insanity, you starve to death"
dead()
elif 'care' in choice1:
print 'The troll cannot feed off of your anger.'
print 'The troll starves and you recover one piece of the lever from his stomach.'
change()
entrywayopen()
return incomp1 == True
else:
unknown()
change()
door1(incomp1)
elif incomp1 == True:
print 'You already recovered the piece from room 1.'
entrywayopen()
So, I have incomp1 already at a value of False when the function is called. The user must get the correct answer, in this case the elif statement. At the end, I have it to return incomp1 == True. Yet, the value remains unchanged. My endgame in this room strategy is to return a value of True for the statement if door1(incomp1) and door2(incomp2) and door3(incomp3):. What is causing the Boolean change in value to not be returned?
A little about Python boolean expressions:
every python expression can be evaluated as a boolean
None, False, 0, 0.0, empty strings, lists, tuples and dictionaries are False; most others objects are True
that means: instead of x == True you can usually just write x, in your case: if incomp1:
If you are executing a function and it finishes without hitting a return, a None will be returned implicitly. If you do a boolean comparison on it, it will evaluate as False.
You need to replace "return incomp1 == True" with just "return True". Then call the door1 function like this "incomp1 = door1(incomp1)".
This will change the value of incomp1 to the value returned by the function "True".
You can also replace "elif incomp1 == True:" with a simple "else".
You might also consider adding a .lower() to choice1 = raw_input("What is your response? :>"). This will make it so if the player uses a capital letter in the input it will still function as desired.
def door1(incomp1):
if incomp1 == False:
print 'You enter door 1 and find a hideous internet troll.'
print "The troll says, 'LOOK AT THIS LOSER'"
options = ["YOU'RE THE LOSER", "I don't care." , "YOUR MOM IS FAT"]
options2 = [1,2,3]
for x in options:
print "\t :> %s" % x
#choice1 = raw_input("What is your response? :>")
choice1 = raw_input("What is your response? :>").lower()
if ('loser' in choice1) or ('fat' in choice1):
print "You are sucked into the troll's behaviour and are driven insane"
print "After three days of insanity, you starve to death"
dead()
elif 'care' in choice1:
print 'The troll cannot feed off of your anger.'
print 'The troll starves and you recover one piece of the lever from his stomach.'
change()
entrywayopen()
return True
else:
unknown()
change()
door1(incomp1)
#elif incomp1 == True:
else:
print 'You already recovered the piece from room 1.'
entrywayopen()
incomp1 = door1(incomp1)
The code gets stuck within the yes_or_no function right after the user input. No error message, please help! As you can see all I am trying to do is effectuate a simple purchase, I haven't been able to test the buy_something function, and I'm aware that it may have issues.
#!/usr/bin/env python
import time
# Intro
print "Input Name:"
time.sleep(1)
name = raw_input()
print "Welcome to Tittyland brave %s'" %(name)
time.sleep(2)
print "You are given nothing but 500 gold to start you journey..."
time.sleep(2)
print "Good luck..."
time.sleep(3)
print "Shopkeeper: 'Eh there stranger! Looks like you'll need some gear before going into the wild! Check out my store!'"
time.sleep(4)
print ""
#Inventory and first shop
inventory = {
'pocket' : [],
'backpack' : [],
'gold' : 500,
}
shop = {
'dagger' : 50,
'leather armor' : 150,
'broadsword' : 200,
'health potion' : 75,
}
#Buying items
for key in shop:
print key
print "price: %s" % shop[key]
print ""
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input()
def buying_something(x):
for i in shop:
if shop[i] == x:
inventory[gold] -= shop[i]
inventory[backpack].append(shop[i])
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"
yes_or_no(answer1)
I fixed both your functions. You had your raw_inputs at the wrong place:
def yes_or_no(purchase_q):
if purchase_q == "yes":
while True:
things = raw_input("Great. What is your hearts desire(type no more to exit shop): ")
if things != "no more":
buying_something(things)
else:
print "Good luck on your journey then"
break
def buying_something(item):
if item in shop.keys():
print "You have %s gold available" %(inventory.get('gold'))
print "Item Added {0}: ".format(item)
backpack_items = inventory.get('backpack')
backpack_items.append(item)
item_cost = shop.get(item)
print "Cost of Item is %s gold coins " %(item_cost)
inventory['gold'] = shop.get(item) - item_cost
What happens is that after this line:
print "Shopkeeper: So, you interested in anything?"
you wait for raw input with this answer1 = raw_input()
Then immediately after you type yes or no, you wait for input again item = raw_input()
Tt's not getting stuck or anything, it's just doing as it's told.
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input() // <-- This is in the wrong place
yes_or_no(answer1)
What you've written requires the user to type in the item they want after the yes or no answer, and regardless of a yes or no. I suggest you move the item = raw_input() into your yes_or_no function.
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
item = raw_input()
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"
I'm currently going through the book "Learning Python The Hard Way", and I'm trying to make a simple game. In this game, I want to be able to pick up at item "Flashlight" in one room, to be able to get into another room. I can, however, not make it work :-(
So the question is, how do I carry the same list through several functions, and how do I put things in it? I want to be able to put multiple things in it.
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
Hope you can help me out, thanks :-)
Code:
def start(bag):
print "You have entered a dark room"
print "You can only see one door"
print "Do you want to enter?"
answer = raw_input(">")
if answer == "yes":
light_room(bag)
elif answer == "no":
print "You descidede to go home and cry!"
exit()
else:
dead("That is not how we play!")
def light_room(bag):
print "WOW, this room is amazing! You see magazines, cans of ass and a flashlight"
print "What do you pick up?"
print "1. Magazine"
print "2. Cans of ass"
print "3. Flashlight"
pick(bag)
def pick(bag):
pick = raw_input(">")
if int(pick) == 1:
bag.append("Magazine")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 2:
bag.append("Can of ass")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 3:
bag.append("Flashlight")
print "Your bag now contains: \n %r \n" % bag
else:
print "You are dead!"
exit()
def start_bag(bag):
if "flashlight" in bag:
print "You have entered a dark room"
print "But your flashlight allows you to see a secret door"
print "Do you want to enter the 'secret' door og the 'same' door as before?"
answer = raw_input(">")
if answer == "secret":
secret_room()
elif answer == "same":
dead("A rock hit your face!")
else:
print "Just doing your own thing! You got lost and died!"
exit()
else:
start(bag)
def secret_room():
print "Exciting!"
exit()
def dead(why):
print why, "You suck!"
exit()
bag = []
start(bag)
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
The problem here is that in this line:
def pick(bag):
pick = raw_input(">")
you bind pick to a new value (a str) so it doesn't reference a function anymore. Change that to something like:
def pick(bag):
picked = raw_input(">")
employee = float(raw_input('Employee code number or 0 for guest:') or 0.0)
if employee == isalpha:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
This code does not recognize alphabetical input.
There are 2 ways.
You can catch the the exceptions and pass.
try:
employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except KnownException:
# You can handle Known exception here.
pass
except Exception, e:
# notify user
print str(e)
Check for the type of input and then do what you want to do.
employee = raw_input('Employee code number or 0 for guest:')
if(employee.isalpha()):
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
else:
print "Your employee no is:" + str(employee)
Do not use try and catch until and unless there are chances of unknown exceptions. To handle things with if and else are recommended.
Read more about : why not to use exceptions as regular flow of control
Use a try
try:
employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except ValueError:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
You can use try/except as the other answer suggested, and if you want to use str.isalpha() you have to call it on the string, not compare it with the string. For example:
employee = raw_input('Employee code number or 0 for guest:')
if employee.isalpha():
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
else:
employee = float(employee)
If you want it to only accept positive integers you can check usingisdigit() which is basically the opposite of isalpha().Try:
employee = raw_input('Employee code number or 0 for guest:')
if employee.isdigit()==False:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
elif int(employee)==0:
print "You are a guest"
else:
print "Your employee no is:" ,employee
I also added a bit of code using elif to check if you're a guest