AppleJax AppleJax - 1 month ago 4
Python Question

How to stop an endless loop?

I am making a script game and use this code for multiple choice.

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


After this happens,If you type A or B it will print the desired text and then ask you again "Do you want to befriend fred?" etc.

Answer

You can simply add break statements to each conditional:

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

Also if you want to leave the loop after one iteration the loop isn't necessary. However, I assume you're looping until you get the correct input, in which case it might be nice to tell your player that the input was incorrect:

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")
Comments