python 中的用户输入验证

发布于 2025-01-19 08:42:37 字数 729 浏览 2 评论 0原文

我已经玩了几个小时了,并且尝试了一些变体,但仍然一无所获,不确定我出了什么问题。我正在尝试将其做到,以便用户只能给出A,B或C的输入值。如果有人建议这样做,这将不胜感激。谢谢。

def run_quiz(questions):
    """
    Function loops through questions and checks answer given
    against correct answer. If correct answer given
    then score increases by 1.
    """
    score = 0
    for question in questions:
        answer = input(question.prompt)
        answer = answer.lower()
        if answer == question.answer:
            score += 1
            while answer not in {'a', 'b', 'c'}:
                return "Invalid answer, try again"
            else:
                return f"You guessed {answer}"

    print(f"{name} got {score} out of {str(len(questions))} questions correct")

I've been playing about with this for a few hours now and have tried a few variations and am still getting nowhere and am not sure what I'm getting wrong. I'm trying to make it so users can only give input values of a, b or c. If anyone could advise that would be greatly appreciated. Thanks.

def run_quiz(questions):
    """
    Function loops through questions and checks answer given
    against correct answer. If correct answer given
    then score increases by 1.
    """
    score = 0
    for question in questions:
        answer = input(question.prompt)
        answer = answer.lower()
        if answer == question.answer:
            score += 1
            while answer not in {'a', 'b', 'c'}:
                return "Invalid answer, try again"
            else:
                return f"You guessed {answer}"

    print(f"{name} got {score} out of {str(len(questions))} questions correct")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女的英雄梦 2025-01-26 08:42:37

不需要这些 return 语句。

def run_quiz(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt).lower()
        while answer not in {'a','b','c'}:
            answer = input("Invalid answer, try again").lower()
        if answer == question.answer:
            score += 1
            print("Correct")
        else:
            print("Incorrect")
    print(f"{name} got {score} out of {len(questions)} questions correct")

There's no need for those return statements.

def run_quiz(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt).lower()
        while answer not in {'a','b','c'}:
            answer = input("Invalid answer, try again").lower()
        if answer == question.answer:
            score += 1
            print("Correct")
        else:
            print("Incorrect")
    print(f"{name} got {score} out of {len(questions)} questions correct")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文