This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
This is the code I have written for Learn Python the Hard Way exercise 36. But I am not able to run the code in the door_1 function. If I choose 3 as an option and then left or right anything which is then stored in dir, the output is "lion ate you", no matter what I type.
from sys import exit #importing module from lib
def Tadaa():
print "This is a place where you will get a surprise"
next = int(raw_input("Enter any number from 1-10 :"))
if next <= 10:
if next % 2 == 0 :
print "You will be buying me a shake :)."
else :
print "You will be getting a shake by me."
else :
print "Do it correctly."
def door_1():
print "There are 3 doors . Choose any door from the the remaining three doors"
print "Lets hope for the best "
next = raw_input("Enter your option :")
if next == "1":
print "abc "
elif next == "2":
print "abc"
elif next == "3":
print "You have entered 3rd door ."
print "Here are 2 doors one on left and one on right."
dir = raw_input("Choose which door do you wnat to enter :")
if dir == "left" or "Left":
print "Lion ate you . You are dead ."
elif dir == "right" or "Right" :
print "You will be getting a surprise"
Tadaa()
else :
print "abc"
else :
print "abc"
def door_2():
print "There are two doors A and B which will decide your fate"
next = raw_input("Enter the door ")
if next == "A" or "a":
door_1()
elif next == "B" or "b":
print "You are back from where you have started"
start()
else :
print "I got no idea what that means."
exit(0)
def start():
print "You are in dark room"
print "There is a door to your right and left ."
print "Which one do you take"
next = raw_input("> ")
if next == "Right" or "right":
door_2()
elif next == "Left" or "left":
door_1()
else :
print "abc"
start()
The problem is your statement:
if dir=="left" or "Left":
What you want is
if dir=="left" or dir=="Left":
In effect, what just doing or "Left" is doing, is checking whether a string that you've just created exists or not. Put another way, its similar to:
x='Left'
if x:
X does exist, so if X is True.
The crux here is to always evaluate statements in quantum, and when you're using and in conjunction with or statements, make sure you use brackets to be explicit. if statement_one or statement_two.
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
import turtle
import time
import colorama
from colorama import Style, Fore, Back
colorama.init()
def gametime():
print("The game will start now.")
def firstanswer():
print(Back.WHITE)
print(Fore.CYAN)
print("get a cup of chai as we wait")
def firstdenial():
print("you dont get to play my game than humph")
print("nah just playing")
print("the long list of rules are... TL means top left, TM means top middle of the screen, TR means top right, ML means middle left of the screen, MM means the absulote MIDDLE of the screen, MR means middle right of the screen,BL means bottom left of the screen, BM means bottom middle of the screen, BR means bottom right of the screen ")
ans3 = input("Do you understand now? ")
if ans3 == "yes" or "Yes" or "Yeah" or "yeah" or "indubitably":
gametime()
else:
print ("well funk you, stupid delinquent instead of playing a game go read a book.")
exit()
def gamedrive():
print(colorama.Fore.GREEN, "tic-tac-toe")
print(colorama.Style.DIM + colorama.Fore.BLUE , "the commands of this game are:")
print("TL means top left TM means top mid TR means top right the bottom rows follow the same thinking ML is mid left BL is bottom left")
print(Fore.RESET)
ans1 = input("are the instructions clear? ")
print(Style.RESET_ALL)
if ans1 == "yes" or "Yes" or "Yeah" or "yeah" or "indubitably":
firstanswer()
else:
firstdenial()
gamedrive()
question:
if ans1 == "yes" or "Yes" or "Yeah" or "yeah" or "indubitably":
firstanswer()
else:
firstdenial()
So when running my code and inputting anything else the code still prints what's in the first line after
if ans1 == "yes" or "Yes" or "Yeah" or "yeah" or "indubitably":
my else code isn't working can anyone help me figure out how to fix my code so when you input anything other than yes, Yes, Yeah, yeah, or indubitably it will explain the full set of rules. but if you do type yes, Yes, Yeah, yeah, or indubitably to have the code run
def firstanswer():
print(Back.WHITE)
print(Fore.CYAN)
print("get a cup of chai as we wait")
for some reason it does not print my else code could I possible get some explanation?
For evaluating if multiple strings are contained in another string you can use in.
Kindly try replacing:
if ans1 == "yes" or "Yes" or "Yeah" or "yeah" or "indubitably":
with:
if ans1 in ['yes','Yes','Yeah','yeah','indubitably']:
For example:
ans1 = "Yes"
if ans1 in ['Yes','yeah','Yeah']:
print("Ok")
else:
print("Not Ok")
Evaluates to True and prints Ok
I'm currently going through Learn Python The Hard Way Exercises and wanted to try writing my own code to let a user choose different paths. When I run the code below, I don't get a name error for "first_decision". However, I keep getting a name error saying it's not defined for the variable "second_decision". I am running Python 2.7.10. Does anyone know why this is?
Error Here:
NameError: name 'second_decision' is not defined
Code Here:
print "This is the root level where we now create 3 branches of decisions. 1, 2, or anything else"
first_decision = raw_input("> ")
print "You chose %r" % first_decision
if first_decision == "1":
print "This is the context after player makes the first choice"
print "Once here, we can let the player make another decision. 1, 2, or 3"
second_decison = raw_input("> ")
print "You chose %r" % second_decision
if second_decision == "1":
print "This is two levels deep"
elif second_decision == "2":
print "This is two levels deep"
else:
print "Everything else for the second level"
elif first_decision == "2":
print "This is the second context after player makes the first choice"
print "Once here, we can let the player make another decision. 1, 2, or 3"
second_decison = raw_input("> ")
print "You chose %r" % second_decision
if second_decision == "1":
print "This is two levels deep"
elif second_decision == "2":
print "This is two levels deep"
else:
print "Everything else for the second level"
else:
print "This is for everything else"
You have wrong name, you assing to "second_decison" and then use "second_decision"
you missed i.
You made a typo in the line
second_decison = raw_input("> ")
This should be
second_decision = raw_input("> ")
I'm been having a lot of trouble properly using functions in python. Im a beginner so I'm creating this kinda maze like game, and want to use functions so that a user can return to previous locations if they choose to. The problem is that all the code after the "def sec2():" does not run, and it totally skips over this block of code. So if the user were to run the program and choose left, the program finishes with "Ah, nevermind, remember those numbers," never prompting the user with anything or printing anything from sec2. I believe my problems could be occurring with indentation. If anyone has any idea as to why the code under my functions isn't executing please let me know! Many thanks!
print ("********")
print ("Hey there soldier. This is General Chris.")
print ("I understand you are in quite the situation!")
print ("Just 4 hours ago, your patrol was ambushed by ISIS...You may not rememeber much after being knocked unconscious!")
name = input('Whats your name, soldier?')
print ("********")
print ("Alright, here's the deal",name)
print ("You are now being held hostage in an encampment near Soran, Iraq.")
print ("Unfortunately for you, our hackers have recieved intel that your captors plan on executing you in just two hours.")
print ("You dont have long to make your escape! Get moving fast!")
def sec1():
print ("********")
print ("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')
if room1 == "L":
print ("********")
print ("Good choice",name)
print ("Whats this? A slip of paper says '8642' on it...Could it mean something?")
print ("Ah, nevermind! Remember those numbers!")
def sec2():
print ("********")
print ("Now you have a choice between crawling into the cieling, or using the door!")
room2 = input('Type C for cieling or D for door, and hit Enter!')
if room2 == "C":
print ("********")
print ("Sure is dark up here in the ducts!")
print ("Stay quiet, and move very slowly.")
def ductoptionroom():
print ("Do you want to continue into the ducts or retreat?")
ductoption = input('Type C or R and hit Enter!')
if ductoption == "C":
print ("You are continuing into the ducts!")
elif ductoption == "R":
sec2()
else:
print ("Focus on the mission!")
elif room2 == "D":
print ("********")
print ("You slowly turn the door knob and see a guard standing there...He doesnt notice you!")
print ("Look, theres a piece of rope on the ground! You could use this to strangle the guard!")
def guardkillroom():
print ("Do you want to try and kill the guard so you can continue on your escape?")
guardkill = input ('Type K for kill or R for retreat and hit Enter!')
if guardkill == "K":
print ("********")
print ("You sneak behind the unsuspecting guard and quickly pull the rope over his neck!")
print ("You've strangled the guard! Now you can continue on your mission!")
elif guardkill == "R":
guardkillroom()
else:
print ("We dont have all day!")
guardkillroom()
else:
print ("Focus soldier!")
room2()
elif room1 == "R":
print ("********")
print ("Uh oh. Two guards are in this room. This seems dangerous.")
print ("Do you want to retreat or coninue?")
roomr = input('Type R or C and hit enter.')
if roomr == "R":
print ("********")
print ("Good choice!")
sec1()
elif roomr == "C":
print ("********")
print ("You continue and are spotted by a guard.")
print ("***MIISSION FAILED***")
def gameover1():
print ("Do you want to retry?")
retry1 = input("Type Y or N and hit enter!")
if retry1 == "Y":
sec1()
elif retry1 == "N":
print ("********")
print ("Thanks for playing!")
else:
gameover1()
sec1()
It looks like you only ever define sec2 and you never actually call it. When you do something like def myfunc() it just tells python what should happen when that function is called. The code will never actually be ran until you run myfunc() from somewhere else in the code. And the only place sec2 is called is recursively from within sec2 (if the player decides to retreat from the ducts)
So to use sec2 you need to call it from somewhere else within sec1
I'm not sure where that should be based upon a quick reading of the game but for testing you could do something like the following
print ("Ah, nevermind! Remember those numbers!")
def sec2():
....
elif room2 == "D":
sec2()
Additionally since sec2 is defined inside of sec1 that means sec2 can only ever be called inside of sec1 as well. I suspect that was not what was intended (though I could be wrong). To fix that you could do the following
def sec2():
...
def sec1():
... #All the same code as before except for the sec2 definition
sec1()
In this code I try to call a function. On the other hand its not working the way I want it to work, for it is staying in the loop even though I am changing the loops condition options_secondscenario[0] from 0 to 1 at the end of the Loop. What I want this to do is to move to third_scenario() function. Thanks in advance.
options_secondscenario = ['Whats going on out there?', 'So what now?']
def third_scenario():
print "This is the third scenario"
choiceselection2 = raw_input("> ")
if choiceselection2 == 1:
print "stay"
else:
print "leave"
def dead():
print "You are dead"
exit()
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
choices = options_secondscenario[0]
while choices == options_secondscenario[0]:
choiceselection = raw_input("> ")
if choiceselection == 'Whats going on out there?':
print "Conversation 4"
elif choiceselection == 'Whats up':
print "Nothing"
elif choiceselection == 'what is that':
print "I dont know"
elif choiceselection == 'is':
dead()
else:
third_scenario()
choices == options_secondscenario[1]
second_scenario()
You are trying to change your choices var AFTER the loop (check your indentation). So the while loop never gets a chance to reach this statement.
Also, you are using the compare operator == instead of the assignment operator = like so:
choices = options_secondscenario[1]
That line should be somewhere INSIDE your while loop. Check your indentation.
I'm pretty new to programming, but I've got a quick question. I'm trying to write a sort of "choose your own adventure" game, but I've run into a problem. I'm only really as far into if statements in the code, but I want to be able to send the user back to previous code when they type something.
For example:
print "You are in a room with two doors to either side of you."
choiceOne = raw_input("Which way will you go?")
choiceOne = choiceOne.lower()
if choiceOne = "r" or choiceOne = "right":
print "You go through the right door and find yourself at a dead end."
elif choiceOne = "l" or choiceOne = "left":
print "You go through the left door and find yourself in a room with one more door."
else:
print "Please choose left or right."
In the if statement, I want to send the user back to choiceOne's raw_input(). In the elif statement, I want to give the user the option to either proceed through the next door, or return to the first room to see what secrets the other door may hold. Is there any way to do this? I don't care if the way is complicated or whatever, I just want to get this working.
Are you looking for a while loop?
I think that this website explains it very well: http://www.tutorialspoint.com/python/python_while_loop.htm
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
→
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Use a while loop:
while True:
print "You are in a room with two doors to either side of you."
choice_one = raw_input("Which way will you go?").lower()
if choice_one == "r" or choice_one == "right":
print "You go through the right door and find yourself at a dead end."
continue # go back to choice_one
elif choice_one == "l" or choice_one == "left":
print "You go through the left door and find yourself in a room with one more door."
choice_two = raw_input("Enter 1 return the the first room or 2 to proceed to the next room")
if choice_two == "1":
# code go to first room
else:
# code go to next room
else:
print "Please choose left or right."
You need to use == for a comparison check, = is for assignment.
To break the loop you could add a print outside the loop print "Enter e to quit the game":
Then in your code add:
elif choice_one == "e":
print "Goodbye"
break