你如何在Python中创建条件语句?

时间:2014-12-06 23:44:51

标签: python-2.7

我对如何制作条件语句感到困惑。我似乎无法弄明白。在下面的示例中,我希望拍摄输入仅在用户在此情况下选择游戏中的枪时才起作用。与刀等相同。

def chap4():
print "You feel around the room.\n"
time.sleep(3)
print "You find a small chest...\n"
time.sleep(3)
print "You open the chest...\n"
time.sleep(2)
print "[pickaxe, shovel, lighter, axe, 9mm(0), knife]\n"
    while (True):
        chest = raw_input("What will you take?: ")
        if chest == "pickaxe":
            print "You take the pickaxe"
            break
         elif chest == "shovel":
            print "You take the shovel"
            break
        elif chest == "lighter":
            print "You take the axe"
            break
        elif chest == "9mm":
            print "You take the empty 9mm pistol"
            break
        elif chest == "knife":
            print "You take the knife"
            break
        elif chest == "axe":
            print "You take the axe"
            break 
        else:
            print "Invalid choice. Try again..."
chap4()

def zombie():
    print "A zombie is seem in the distance"
    while (True):
        attack = raw_input("> ")
        if attack == "shoot":
            print "Zombie hp 50/100"
        elif attack == "stab":
            print "Zombie hp 70/100"
        else:
            print "Invalid input. Try again..."

因此,您可以通过代码告诉我有麻烦...我原本以为我可能会在if语句中创建另一个if语句,但我不确定。如果可以,请帮忙...谢谢!

3 个答案:

答案 0 :(得分:1)

我建议添加conditional if

def chap4():
    ....
    return(chest)
def zombie()
    weapon = chap4()
    if weapon == "9mm":
        if attack =="shoot":
            print(...)
        elif attack =="stab":
        ...

等等。 因此,在zombie()中的条件中指定武器。此外,zombie()必须知道chest变量,因此return(chest)函数末尾为chap4(),并在chap4() <{}}内调用zombie() < / p>

编辑:在chap4()中调用zombie()时,需要调用变量,在本例中为weapon

答案 1 :(得分:1)

你可以存储这样的胸部组合:

chestContainer= {"pickaxe": "pickaxe", "shovel": "shovel", "lighter": "lighter", "9mm(0)": "9mm(0)", "knife": "knife", }

然后你可以打印这样的选项:

print chestContainer[chest]

您可以评估输入是否有效:

if chestContainer[chest] == None:
   print "Invalid choice. Try again..."

修改

用户908293说你必须保存你选择的武器。

weapon = chestCointainer[chest]

答案 2 :(得分:1)

条件陈述是好的,只要它们去。问题是你没有在任何地方保存结果。做点什么

if chest == "pickaxe":
    print "You take the pickaxe"
    weapon = "pickaxe"
elif chest == "shovel":
    print "You take the shovel"
    weapon = "shovel"
etc.

当用户选择攻击模式时,您可以检查他是否拥有合适的武器:

if attack == "shoot":
  if weapon == "9mm":
     print "Zombie hp 50/100" 
  else: 
     print "you don't have a pistol"

在这方面,打印也许还不够。你会想要跟踪发生了什么,我想是