我在自学python,学习Python很困难,我遇到了一个问题ex36。这个if语句有什么问题
我处于开发的相当早期阶段,我无法弄清楚我的if语句有什么问题。不管出于什么原因,我的代码永远不会使得过去
elif "1" or "2" in choice and not key.
即使“1”或“2”都没有在声明。我不明白为什么会发生这种情况。看起来很好。当我为此使用另一个嵌套的if语句时,嵌套语句通过了这一点,但它被挂在另一个点上,所以我移动了我的初始化变量 - 不太确定这是否是python中的事情 - 我确实移动了它们尽管 - 在while循环之外。 在我漫不经心的时候,下面是代码的全部内容。 我知道逻辑不完整,并且超过一半的代码没有完成,但我需要知道为什么这个声明不起作用。
#write function definition statements.
def darkRoom():
door = raw_input(">>> ")
if "1" in door:
lions()
elif "2" in door:
tiger()
elif "3" in door:
bear()
else:
print """A thunderous voice booms through the room exclaiming,
"CHOOSE DOOR 1, 2, OR 3!"""
darkRoom()
def lions():
#naming error somewhere here
keys = False
lions = False #lions are calm if false. They are pissed if true
warning = True
while True:
choice = raw_input(">>> ")
print " %r %r %r" % (keys, lions, warning)
x = "1" or "2" not in choice and not key and lions
if "take" and "key" in choice:
key = True
print """There are two doors behind the angry pride of lions.
Which door are you going to run to and open before the lions eat you?"""
door = raw_input(">>> ")
if "1" in door and key == True:
threeBrickRoads()
elif "2" in door and key == True:
quickSand()
else:
youDie("You take too long to decide which door to take and the lions eat you.")
elif "look" in choice:
print "Looks like you're going to have to take the key from the lions"
#never gets past this statement even when 1 and two not in choice. This is what my question
#is about
elif "1" or "2" in choice and not key:
print "The Door is locked and the lions are starting to stare."
lions = True
print " %r %r %r" % (keys, lions, warning)
print "%r" % choice
#never reaches this point. I don't know why.
elif x and warning:
print """The lions leave the key and start to chase you. Quick get the
key before they catch you"""
warning = False
#Statement never reaches this point. It should
elif x and not warning:
youDie("You take too long to take the key and the lions eat you for it.")
# entering jig in statement should put me here and not at line 46
else:
print """"You quickly realize that doesn't do you any good.
You take another look at your surroundings"""
#don't think I need that while I have the while loop.
#lions()
##def tiger():
##def bear():
##def threeBrickRoads():
##def quickSand():
##def sizePuzzle():
##def riddlesOnWall():
##def wolfSheepCabbage():
##def duckHunt():
##def hangman():
##def goldRoom():
##def oceanShore():
##def winScreen():
def youDie():
print why, """You lay there pondering your mistake as
the last fleeting pulses of life slowly beat out of you."""
#exit(0)
darkRoom()
重要的是,这里的电脑是愚蠢的。如果我说'如果VAR == 1或2',那么计算机会检查'if VAR == 1'。然后它检查以查看“是否2”。因为'2'是一个正整数,所以'或2'将导致条件始终为真,无论“VAR”如何。你的情况是相似的,因为英文不完全符合你想要说的Python的等价物。 – turbulencetoo
所以'如果var === 1或var === 2'是正确的,或者你需要检查vars内容列表 – Steve