如何阻止无限循环?

时间:2016-10-28 01:50:27

标签: python loops

我正在制作一个脚本游戏并使用此代码进行多项选择。

while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
    print ("You befriend fred. You now have a friend..")
elif d1a == "B":
    print ("You angered Fred. He kills you. RIP.")
elif d1a == "Q" :
    break

发生这种情况后,如果您键入A或B,它将打印所需的文本然后再次询问您“你想和fred成为朋友吗?”等

1 个答案:

答案 0 :(得分:0)

您只需向每个条件添加break语句:

while True:
    d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
    if d1a == "A":
        print ("You befriend fred. You now have a friend..")
        break
    elif d1a == "B":
        print ("You angered Fred. He kills you. RIP.")
        break
    elif d1a == "Q" :
        break

此外,如果您想在一次迭代后离开循环,则不需要循环。但是,我假设你循环直到得到正确的输入,在这种情况下告诉你的播放器输入不正确可能会很好:

while True:
    d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
    if d1a == "A":
        print ("You befriend fred. You now have a friend..")
        break
    elif d1a == "B":
        print ("You angered Fred. He kills you. RIP.")
        break
    else:
        print("Incorrect input")