简体   繁体   中英

List for loop continues if user inputs anything

When I input text for my verdict I can put anything, eg "zzzzz", and the program continues on through the list.

I want the program to stop when user inputs "Guilty". And only move on when user inputs "Not Guilty".

This is what I have so far, I also tried using while True if that's better?

guilty = False
character = ["Miss Scarlett", "Professor Plum", "Mrs Peacock", "Reverend Green", "Colonel Mustard", "Dr Orchid"]

while not guilty:
    for accused in character:
        verdict = input("Do you find %s guilty or not guilty? " % accused)
        if verdict == "guilty":
            print("User finds %s guilty" % accused)
            guilty = True
            break
        else:
            guilty = False

To accept only answers guilty and not guilty you can remove the top while loop and move it inside for-loop. Also, use str.lower to make answers case-insensitive:

character = ["Miss Scarlett", "Professor Plum", "Mrs Peacock", "Reverend Green", "Colonel Mustard", "Dr Orchid"]

for accused in character:
    verdict = ''
    while verdict not in ('guilty', 'not guilty'):
        verdict = input("Do you find %s guilty or not guilty? " % accused).lower()

    if verdict == "guilty":
        print("User finds %s guilty" % accused)
        break

Prints (for example):

Do you find Miss Scarlett guilty or not guilty? d
Do you find Miss Scarlett guilty or not guilty? d
Do you find Miss Scarlett guilty or not guilty? f
Do you find Miss Scarlett guilty or not guilty? not guilty
Do you find Professor Plum guilty or not guilty? guilty
User finds Professor Plum guilty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM