[英]Shortest way in Python to set boolean to False if True, and set to True if False
[英]True & False Boolean in Python
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means.
這是為了顯示我對布爾的理解。 next == "taunt bear" and not bear_moved
的行測試中,如果我的輸入是taunt bear
,結果為True and True
,它將繼續循環。
所以讓我感到困惑的是, next == "taunt bear" and bear_moved
線測試next == "taunt bear" and bear_moved
。 如果我的輸入是taunt bear
,是否應該是"taunt bear" == "taunt bear"
和bear_moved
,分別為True and True
? 這意味着循環將繼續而不是取消循環。
while True:
會無限期繼續(除非您稍作break
-通常, break
是Python等語言中的不良設計)。
您可能想做:
while something == True: #Or - as has been pointed out, `while something` - which is equivalent and more Pythonic
...
some code which eventually sets something to False
...
python中的elif
等價於else if
。 如果執行其中一個elif
塊,則其他任何一個都不能執行,並將跳至if
的底部。
在執行next == "taunt bear" and not bear_moved
並評估為true,然后執行該塊后,對程序的控制在循環的最前面繼續,並再次請求輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.