这个代码有什么问题,需要很多帮助吗?

2024-04-24 22:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

welcome = raw_input("Enter username:")
print "Welcome to dungeon crawler, %s" % (welcome)
items = []
starting_item_var = True

def sec_1():
    while True:
        starting_item = raw_input("Hammer or sword (use no caps!)")
        if starting_item == "hammer":
          items.append("hammer")
          print "Hammer was added to items"
        if starting_item == "sword":
          items.append("sword")
          print "Sword was added to items"
        if starting_item != "sword" or "hammer":
          print "Invalid option"
          continue
        return


sec_1()

在这里的代码中,我要求用户选择要使用的起始项。它会。将项目附加到项目列表中。如果这个项目不是剑或锤子,它应该说无效的选项,并送你回到乞讨的功能。不幸的是,它会的。将剑或锤子添加到列表中,但它仍将运行第三个“if”语句。你知道吗


Tags: to项目trueinputrawifitemssec
3条回答

英语“X不是Y或Z”并不像Python那样翻译。在Python中,X != Y or Z被视为(X != Y) or (Z)Z是它自己的条件,由于"hammer"本身总是真的,or "hammer"使任何条件都是真的。你真的想说starting_item != "sword" and starting_item != "hammer"。你知道吗

但实际上,你根本不应该重复你的条件:

if starting_item == "hammer":
    items.append("hammer")
    print "Hammer was added to items"
elif starting_item == "sword":
    items.append("sword")
    print "Sword was added to items"
else:
    print "Invalid option"
    continue

我建议使用以下代码

if starting_item not in ["sword", "hammer"]:

你需要改变你的第三个条件,如果

更改为:

if starting_item != "sword" or starting_item !="hammer":

相关问题 更多 >