我在自學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