而loop只是无缘无故地随机停止工作?

2024-09-30 14:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用Python编写我的第一个程序,这基本上是一个词汇学习游戏,但由于某种原因,我突然在一个函数中遇到了一些问题,该函数最初运行得很好,但开始运行得很糟糕(中断得太晚),现在根本不起作用。我一直在搜索所有的互联网和我的代码,但我真的找不到任何东西。只是没有任何意义

def Spiel_Spanisch_Deutsch():
    puntos = 0
    intentos = 0

    while puntos < 20:
        for vokabel in vokabeln:
            antwort = input(vokabel.spanisch + ": ")
            if antwort == vokabel.deutsch:
                print("Corecto! {} = {}\n".format(vokabel.spanisch, vokabel.deutsch))
                puntos += 1
                intentos += 1
                print("Tienes {} de 20 puntos!\n ".format(puntos))
            else:
                print("Falso! Estudia mejor! La corecta respuensa seria: {}\n".format(vokabel.deutsch))
                intentos += 1
                print("Tienes {} de 20 puntos!\n ".format(puntos))
    print("You needed {} tries to get 20 right!\n".format(intentos)

当变量puntos>;20但很明显,点数计数器工作,数值在增加,因为在我打印的文本中,分数在增加。谢谢你


Tags: 函数程序format游戏de互联网词汇print
1条回答
网友
1楼 · 发布于 2024-09-30 14:25:35
while puntos < 20:
    for vokabel in vokabeln:
        antwort = input(vokabel.spanisch + ": ")
        # Irrelevant code removed.

如果问题是当你达到所需的Punto数(点)时,它没有停止,你应该意识到当内环仍在运行时,外环不能退出。外部循环检查仅在每个内部循环完成后执行(整个内部循环,而不仅仅是一次迭代)

例如,假设vokabeln(词汇?)中有15个项目,而你是一个完美的翻译,所以一切都会正确

因此,外部循环的第一次迭代将以puntos == 15结束

然后,它将进入该外循环的第二次迭代,并在内循环中向您询问完整的十五个问题,即使您在回答前五个问题后已经得到20分

As an aside, if it stopped working for no apparent reason, it may be because your original vokabeln had n entries, where n is a factor of twenty (i.e., 1, 2, 4, 5, 10), or you were getting enough wrong so that the end of the inner loop happened to coincide with the answer that gave you your twentieth point.

如果您想在获得足够正确答案后立即停止,可以使用以下方法:

def Spiel_Spanisch_Deutsch():
    puntos = 0
    intentos = 0
    necesitar = 20      # My very suspect attempt at Spanish :-)

    while puntos < necesitar:
        for vokabel in vokabeln:
            antwort = input(vokabel.spanisch + ": ")
            if antwort == vokabel.deutsch:
                print(f"Corecto! {vokabel.spanisch} = {vokabel.deutsch}")
                puntos += 1
            else:
                print(f"Falso! Estudia mejor! La corecta respuensa seria: {vokabel.deutsch}")

            intentos += 1
            print(f"Tienes {puntos} de {necesitar} puntos!")

            # Exit inner loop as soon as we answer what's required.

            if puntos >= necesitar: break

    print(f"You needed {intentos} tries to get {necesitar} right!")

我还对代码进行了一些清理,以避免重复递增intentos(尝试?)之类的操作

我使用了f字符串(Python3.6+),因为它们比str.format()好得多,因为您要打印的东西正是输出字符串中要打印的内容。如果您想更改它或找出它的来源,则不必在str.format()参数列表中搜索它

相关问题 更多 >