【问题标题】:infinite loop until one of three conditions is True. Python无限循环,直到三个条件之一为真。 Python
【发布时间】:2023-04-02 10:33:01
【问题描述】:

我对编程很陌生,所以可能只是我遇到的基本语法问题,或者可能对限制我能力的函数不熟悉,但这里有一些问题。我在 youtube 教程中找到了以下程序,其中导师使用课堂方法创建了一个多项选择题测试,其中包含 3 个可能的答案。这是原始代码:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


question_prompts = [
    'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
]

questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b'),
]


def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)

    if answer == question.answer:
            score +=1

print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')



run_test(questions)

原始代码只允许用户尝试每个问题一次,最终得分为 3。

问题:

我想添加一个条件语句/循环(在分数计算 if 语句之前)来检查用户是否输入了正确的选择“a”或“b”或“c”。如果用户输入了 a 或 b 或 c 以外的任何内容,则它必须无限循环并要求用户输入正确的选择 a 或 b 或 c。

我尝试了 while 循环,但它没有中断,即使用户输入了正确的 a、b 或 c 选择。请帮忙

【问题讨论】:

  • 您发布的代码是您尚未编写但可以工作的代码,但指的是您编写的无效代码。为什么不发布您编写的代码,因为那是有实际问题的代码?请阅读如何制作minimal reproducible example
  • 欢迎来到 Stack Overflow!查看tour。就像约翰说的,我们不是读心术的人。您需要以minimal reproducible example 的形式提供您的非工作代码。有关其他提示,请参阅 How to Ask
  • 除了其他人所说的(我同意)——不要害怕分享“坏代码”;这里的人往往很乐意帮助您改进,并且通过分享您的尝试,您将学到最多,即使您(尚未)为他们感到自豪。

标签: python conditional-statements


【解决方案1】:

您可以在无限 while 循环中添加一个 if 条件来打破它。

您的run_test() 函数也必须返回分数,见下文:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

def run_test(questions):
    score = 0
    for question in questions:
        while True:
            answer = input(question.prompt)
            if answer in ['a', 'b', 'c']:
                break

        if answer == question.answer:
            score +=1

    return score

question_prompts = ['What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
                    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
                    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n']

questions = [Question(question_prompts[0], 'a'),
             Question(question_prompts[1], 'c'),
             Question(question_prompts[2], 'b')]

score = run_test(questions)
print("\nYou got {}/{} correct".format(score, len(questions)))

样本输出:

What color are apples?
(a) Red/Green
(b) Purple
(c) Orange

a
What color are Bananas?
(a) Teal
(b) Magenta
(c) Yellow

b
What color are Strawberries?
(a) Yellow
(b) Red
(c) Blue

c

You got 1/3 correct

【讨论】:

  • 还有一个小提示,您的列表末尾有一个额外的“,”,这是不必要的。
  • 非常感谢它真的帮助我理解了while循环的逻辑
  • @ahsanmbutt 很高兴它有帮助。如果您觉得它有帮助,请投票和/或接受我的回答(复选标记)。
【解决方案2】:

您可以在 for 循环中使用 while 循环,并为每个新问题设置它,以便仅在输入错误时循环。

这应该是你要找的。​​p>

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

score = 0

question_prompts = [
    'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
]

questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b'),
]

def run_test(questions):
    score = 0

    for question in questions:
        wrong = True
        while wrong == True :
            answer = input(question.prompt)

            if answer == question.answer:
                    score +=1
                    wrong = False

print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')



run_test(questions)

【讨论】:

    【解决方案3】:

    首先,当您在最后的打印行中引用score 时,该程序将崩溃。这是因为 scorerun_test() 内部的一个局部变量,并且在该函数之外无法访问,有很多方法可以解决这个问题,但一个快速而肮脏的方法就是移动 @987654324 @ 在run_test() 之外,然后在run_test() 内部添加global score,这应该意味着分数存在于与打印语句相同的“范围”内,而global score 语句意味着run_test() 会知道向外看找到要使用的变量。

    现在对于您的实际问题,您可以通过在答案输入周围添加while True: 并在答案正确时调用break 来非常简单地解决此问题。

    您目前还应该为每个问题添加分数,而不仅仅是在最后,因此应该将其插入到for 循环中。

    最后,您在实际调用计算出它的函数之前引用了score;即使该函数是在另一段代码之上定义的,该函数中的代码在该函数被调用之前也不会运行。

    这是一段工作代码:

    class Question:
        def __init__(self, prompt, answer):
            self.prompt = prompt
            self.answer = answer
    
    
    question_prompts = [
        'What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
        'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
        'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n',
    ]
    
    questions = [
        Question(question_prompts[0], 'a'),
        Question(question_prompts[1], 'c'),
        Question(question_prompts[2], 'b'),
    ]
    
    score = 0
    
    def run_test(questions):
        global score
        for question in questions:
            while True:
                answer = input(question.prompt)
                if answer == question.answer:
                    print("Correct!")
                    score +=1
                    break
                else:
                    print("Incorrect, please try again")
    
    
    
    
    
    run_test(questions)
    
    print('You got ' + str(score) + '/' + str(len(questions)) + ' correct')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2018-07-07
      • 1970-01-01
      • 2021-12-24
      • 2013-01-21
      • 2016-06-18
      • 2016-03-15
      相关资源
      最近更新 更多