【问题标题】:My code freezes and stops, what's wrong with it?我的代码冻结并停止,它有什么问题?
【发布时间】:2021-11-15 20:08:06
【问题描述】:

我是 python 新手,所以如果它真的很基本,请不要感到惊讶,但我一直在尝试编写这段代码来询问数学问题,然后保存分数以便在开始时再次显示它们的循环,但它不保存分数。我应该改变什么? 这是代码

scores = []
names = []
while True:
    f = open("highscore.txt", "r")
    for line in f:
        line = line.strip("\n")
        line = line.split(" ")
        names.append(line[0])
        scores.append(int(line[1]))
    print(f.read())
    for pos in range(len(names)) :
        print(pos + 1, names[pos], scores[pos])
    f.close()
    score = 0
    print("hello, welcome to maths game")
    print("\nQuestion 1: what is 2 x 2 x 2?")
    answer = int(input("your answer >"))
    if answer == 8:
        print("correct")
        score = score + 1
        print("your score is ", score)
    else:
        print("incorrect")
        print("the score is ", score)
    print("\nQuestion 2: what is 34 x 2?")
    answer = int(input("your answer >"))
    if answer == 68:
        print("correct")
        score = score + 1
        print("your score is", score)
    else:
        print("incorrect")
        print("the score is", score)
    name = input("what is your name?")
    position = 0
    for compare_score in scores :
        if score < compare_score:
            position = position + 1
        scores.insert(position, score)
        names.insert(position, name)
        scores = scores[:5]
        names = names[:5]
    f = open("highscore.txt", "w")
    for pos in range (len(names)):
        f.write(names[pos] + " " + scores[pos])

它不会给出任何类型的错误消息,只是循环返回并且不保存名称,也不保存分数

【问题讨论】:

  • 在询问代码相关问题时,始终需要为您使用的语言添加标签。这次我已经为你做了,但以后请记住。
  • 顺便说一句,反复将内容写入文件然后再将它们读回是非常低效的。您希望在开始时将文件读入内存一次,然后在游戏结束时写入更新的文件(除非您非常需要程序的多个实例来共享相同的数据,在这种情况下,文本文件非常脆弱并且,同样,效率低下)。
  • 我会尽量记住这一点。对于不必要的更新,我很抱歉,但我仍在学习如何编写它们。谢谢你的耐心
  • @S.Tack 每当您使用while True。确保在某些情况下具有breakreturn 语句(或程序退出)。否则它将永远运行

标签: python loops saving-data


【解决方案1】:

scores 上有一个 for 循环,它在每次迭代时将一个新项目添加到 scores 列表中。 for 循环永远不会到达列表的末尾,因为总是有“一个”。

【讨论】:

  • 你指的是什么?抱歉,我就是不知道你指的是什么
  • for compare_score in scores : ... scores.insert(position, score) 在您的代码中
  • 衷心感谢
【解决方案2】:

Alain T. 的回答已经说明了您遇到的根本原因。循环永远不会停止,这在您看来是“冻结”,因为您(作为用户/开发人员)没有看到循环仍在运行的输出或指标。所以实际上这里没有冻结.. 它只是永远运行。

出于这个原因,我想添加一个简短的说明,以便下次您自己深入了解问题。 这里的关键词很明显:debugging。

调试意味着:“找出你的代码在执行时做了什么”

一种非常简单但(至少对于小程序而言)非常有效的方法是使用一个或多个print() 语句。这些可用于显示变量的值、对象的属性或像print("I am before the loop") 这样的语句,以了解执行运行/停止的位置..

可能是:(查看打印语句)

while True:
    print("in while")                         #<-- this one
    ...
    print("before loop")                      #<-- this one
    for compare_score in scores :
        print("in loop")                      #<-- this one repeats....
        if score < compare_score:
            position = position + 1
        scores.insert(position, score)
        names.insert(position, name)
        scores = scores[:5]
        names = names[:5]
    print("After loop")                       #<-- never see this one
    f = open("highscore.txt", "w")
    for pos in range (len(names)):
        f.write(names[pos] + " " + scores[pos])

再次运行你的程序应该会打印出来:

in while
before loop
in loop
in loop
in loop
in loop
in loop
in loop
in loop
...

等等...所以你现在知道的是:

  • 循环之前的所有内容至少都已执行
  • 循环永远运行。

所以现在是时候深入挖掘一下循环了。 最有趣的是检查循环退出的变量 依靠。 在您的情况下,这是 scores 列表的长度:

for compare_score in scores:

所以循环一直运行,直到分数列表中没有更多分数可供比较。

因此,print() 列表的长度可能是一个好主意,以检查它是否以及如何减少,直到没有更多的分数可供比较。

所以添加如下内容: 检查包含len(scores)的两个print()语句

for compare_score in scores:
    print("in loop")
    if score < compare_score:
        position = position + 1
    scores.insert(position, score)
    names.insert(position, name)
    scores = scores[:5]
    names = names[:5]
    print(len(scores))                  #<--- this one
    # or a bit nicer as f-string:
    print(f"len score: {len(scores)}")  #<--- this one
    print("After loop")

两者都显示scores 列表的长度。 前者只是做得更好一点。 调试还有很多。 VSCode、Pycharm 等许多工具支持更复杂的方法来单步执行代码、设置断点、检查对象和变量...... 但对于小型和简单的项目,以及当重点是学习、即时反馈和重复时。至少在我看来。 Print() 调试以非常简单的方式为您提供了很多洞察力。

哦,如果你读到这里:

"Welcome to the community"  Just jokin', welcome !! ;)"

【讨论】:

  • 非常感谢您抽出宝贵时间。非常感谢
猜你喜欢
  • 1970-01-01
  • 2022-12-06
  • 2021-11-14
  • 2011-07-28
  • 1970-01-01
相关资源
最近更新 更多