簡體   English   中英

無法理解為什么True / False無效

[英]Can't understand why True/False isn't working

玩家拿起燈泡后,“ bulb”將附加到清單中,並且light_bulb變量設置為True 我已經在代碼中添加了print(light_bulb) ,並且一旦print(light_bulb)燈泡,它的確設置為True

我什至無法理解為什么即使第9行的末尾有a and not light_bulb: 代碼第二次,第三次或第四次運行,因為light_bulb設置為True 結果將為and not Trueand Falseand not True 這意味着第14行應該代替9運行,對嗎?

inventory = ["null"]

def lol():
    choice1 = input(">")
    light_bulb = False
    if "bulb" in inventory:
        light_bulb = True 

    if "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or "light" in choice1.lower() and not light_bulb:
        inventory.append("bulb")
        print("You try to fix the light bulb but it comes off. You decide to keep it.")
        alley()

    elif "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() and light_bulb:
        print ("You already have a light bulb!")
        alley()
    else:
        dead("You fumble around in the darkness and accidentally kill yourself.")

and運算符的綁定比or緊密。 因此,您寫的內容等同於:

  if "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or ("light" in choice1.lower() and not light_bulb):

您想要的是:

  if ("bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or "light" in choice1.lower()) and not light_bulb:

為此,需要括號。

問題與orand表達式的求值順序有關。 and運算符的優先級高於其之前的or表達式,因此將首先對其求值。 我懷疑您希望對它進行最后評估。 嘗試添加括號以使順序明確(這也使您可以將行換成更合理的長度):

if ("bulb" in choice1.lower() or "unscrew" in choice1.lower() or
    "lightbulb" in choice1.lower() or "light" in choice1.lower()) and not light_bulb:

請注意,檢查字符串"lightbulb"可能是不必要的,因為您還要分別檢查其子字符串"light""bulb" (並且in運算符不遵守字邊界)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM