简体   繁体   English

如果用户输入任何内容,循环列表将继续

[英]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.当我为我的判决输入文本时,我可以输入任何内容,例如“zzzzz”,然后程序继续执行列表。

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?这是我到目前为止所拥有的,我也尝试过使用while True是否更好?

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.要只接受guiltynot guilty的答案,您可以删除顶部的while循环并将其移动到 for 循环内。 Also, use str.lower to make answers case-insensitive:此外,使用str.lower使答案不区分大小写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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