在python中对while循环使用多个条件

2024-03-29 02:08:58 发布

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

我对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: ")

任何帮助都会很棒的。提前谢谢。在


Tags: inyouyourlenhaveitemsnowbag
3条回答

Python解释while循环的条件如下:

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

而且,它的计算结果总是True,因为非空字符串的计算结果总是True


若要解决此问题,可以改用^{}

^{pr2}$

not in将测试在元组("A", "a", "B", "b")中是否可以找到{}。


您还可以在这里使用^{}来缩短元组的长度:

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

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

while ANS[0].lower() not in 'ab':
    ....
while ANS not in ['A', 'a', 'B', 'b']:
    print...

或者更广泛地说

^{pr2}$

相关问题 更多 >