2017-10-19 62 views
0

所以我試圖安排我的文本基礎遊戲的遊戲性能如何,如果玩家在他們的庫存中可能沒有某些物品。庫存幫助Python

print ("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up jumpsuit") 
    if "comb" and "razor" in inventory: 
     print ("and the table with the empty bottle.") 
    else "comb" not in inventory and "razor" in inventory: 
     print ("and the table with the empty bottle and comb.") 
    else "razor" not in inventory and "comb" in inventory: 
     print ("and the table with the empty bottle and razor") 

它告訴我,我有一個語法錯誤在這行代碼

else "comb" not in inventory and "razor" in inventory: 

我似乎無法看到我做了什麼錯,我是初學者所以可能有執行我的需求的另一種方式。

+8

我想你是指'elif',而不是'else'。 – khelwood

回答

0

你幾乎沒有

else作品只有這樣

else: 
    do something 

所以,你的代碼會是這樣的

print ("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up jumpsuit") 
    if "comb" and "razor" in inventory: 
     print ("and the table with the empty bottle.") 
    elif "comb" not in inventory and "razor" in inventory: 
     print ("and the table with the empty bottle and comb.") 
    elif "razor" not in inventory and "comb" in inventory: 
     print ("and the table with the empty bottle and razor") 

或者說

print ("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up jumpsuit") 
    if "comb" and "razor" in inventory: 
     print ("and the table with the empty bottle.") 
    elif "comb" not in inventory and "razor" in inventory: 
     print ("and the table with the empty bottle and comb.") 
    else: #using the else here 
     print ("and the table with the empty bottle and razor") 

但是,當測試你的代碼時,我意識到你放置邏輯的方式將無法正常工作。

使用if all(x in inventory for x in ['comb','razor'])會正確對待這兩個變量,在inventorycombrazor的存在,並允許以正確的方式來推出的其他條件,如果其他價值的缺失。

inventory = ['comb','razor'] 
#inventory = ['razor',''] 
#inventory = ['comb'] 

print("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up ju 
mpsuit") 
if all(x in inventory for x in ['comb','razor']): 
    print ("and the table with the empty bottle.") 
elif ('comb' not in inventory) and ('razor' in inventory): 
    print("and the table with the empty bottle and comb.") 
elif ('razor' not in inventory) and ('comb' in inventory): 
    print("and the table with the empty bottle and razor") 
0
print ("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up jumpsuit") 
    if "comb" and "razor" in inventory: 
     print ("and the table with the empty bottle.") 
    elif "comb" not in inventory and "razor" in inventory: 
     print ("and the table with the empty bottle and comb.") 
    elif "razor" not in inventory and "comb" in inventory: 
     print ("and the table with the empty bottle and razor")