我的代码跳过了 does not through the whole else 语句

My code skips the does not go through the whole else statement

提问人:Big_Port 提问时间:7/21/2023 更新时间:7/21/2023 访问量:47

问:

因此,我正在制作一个数学游戏,用户可以尝试三次来回答问题,如果没有,它会显示答案并转到下一个问题,但是我的代码只允许他们在进入下一个问题之前出错一次。我做错了什么

    nQuestions = 0
    cAnswers = 0
    attempts = 0
    lvl = get_level()
    while nQuestions != 10:
        if attempts == 0:
            x, y = generate_integer(lvl)
            answer = x + y
            sum = int(input(f"{x} + {y} = "))
        if sum == answer:
                cAnswers += 1 
                attempts = 0
                nQuestions +=1
                continue
        else:
                attempts += 1
                if attempts == 3:
                    print(f"{x} + {y} = {answer}")
                    attempts = 0
                    nQuestions += 1
                continue
python-3.x 循环 if-statement while-loop

评论

0赞 mr_mooo_cow 7/21/2023
“if attempts == 0” 看起来只会触发一次。如果您想要 3 次尝试,它应该是“if attempts <= 3:”,但如果您在 else 部分处理它,它也是多余的。如果完全删除第一个,您可以删除第一个。
2赞 Anentropic 7/21/2023
因为你只给他们一个机会在 .您希望取消缩进该行,使其位于该 if 块之外,以便它每次都通过 while 循环执行if attempts == 0:sum = int(input(f"{x} + {y} = "))

答:

0赞 Niveditha S 7/21/2023 #1

这是因为您的代码只允许用户输入一次。当尝试次数少于 3 次时,您应该要求用户再次输入(重试)。

以下作品:

nQuestions = 0
cAnswers = 0
lvl = get_level()
while nQuestions < 10:
    x, y = generate_integer(lvl)
    answer = x + y
    #sum = int(input(f"{x} + {y} = "))
    attempts = 0
    while attempts<3:
        sum = int(input(f"{x} + {y} = "))
        if sum == answer:
            cAnswers += 1
            nQuestions +=1
            break
        else:
            attempts += 1
    if attempts == 3:
            print(f"{x} + {y} = {answer}")
            nQuestions += 1

评论

1赞 ShadowRanger 7/21/2023
注意:由于 Python 允许 else 链接到 whilefor 循环,您可以只替换为 .如果退出时没有 ,则该块将执行,如果由于 (或 或抛出异常)而退出,则该块将被跳过。if attempts == 3:else:else:whilebreakbreakreturn