2014-02-06 61 views
1

我对Python相当陌生,已经开始制作一些有趣的小游戏来记住它是如何工作的。我遇到了一个我想在while循环中使用多个条件的区域,并且无法解决如何操作。我在这里看到过一些人在用数字等来做这件事,但我使用的是字母,没有做任何事情或搜索似乎都有效。这是迄今为止我所拥有的。这个想法是,人选择A或B(大写或小写),如果他们不这样做,它会再次循环输入。在python的while循环中使用多个条件

ANS = input("\tA/B: ") 
if ANS == "A": 
    print("They beat you up and stole all of your stuff. You should have run away.") 
    del BAG[:] 
    print("You now have", len(BAG), "items in your bag.")        
elif ANS == "a": 
    print("They beat you up and stole all of your stuff. You should have run away.") 
    del BAG[:] 
    print("You now have", len(BAG), "items in your bag.")        
elif ANS == "B": 
    print("You got away but they stole something from you.")       
    ran_item = random.choice(BAG) 
    BAG.remove(ran_item) 
    print("You now have", len(BAG), "items in your bag")        
    print("They are:", BAG) 
elif ANS == "b": 
    print("You got away but they stole something from you.")       
    ran_item = random.choice(BAG) 
    BAG.remove(ran_item) 
    print("You now have", len(BAG), "items in your bag")        
    print("They are:", BAG) 
while ANS != "A" or "a" or "B" or "b": 
    print("You must make a choice...") 
    ANS = input("\tA/B: ") 

任何帮助都会很棒。先谢谢了。

+0

非常感谢大家对我的快速回复和帮助。所有的编辑工作都很有用! – robblockwood

回答

3
while ANS not in ['A', 'a', 'B', 'b']: 
    print... 

或者更一般

while ANS != 'A' and ANS != 'a' and ... 
2

您while循环的条件是由Python的解释是这样的:

while (ANS != "A") or ("a") or ("B") or ("b"): 

此外,它将始终评估为True因为非空串总是评估为True


为了解决这个问题,你可以使用not in代替:

while ANS not in ("A", "a", "B", "b"): 

not in是检验ANS可以在元组("A", "a", "B", "b")被发现。


您也不妨使用str.lower这里来缩短数组的长度:

while ANS.lower() not in ("a", "b"): 
0

我能想到的做,在这种情况下,最简单的方法是:

while ANS[0].lower() not in 'ab': 
    ....