Home > Software design >  My code freezes and stops, what's wrong with it?
My code freezes and stops, what's wrong with it?

Time:11-16

I'm new to python so don't be surprised it if is something really basic, but i've been trying to write this code that asks math questions and then saves the scores in order to show them again at the start of the loop, but it doesn't save the scores. what should i change? this is the code

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])

it doesn't give any kind of error message, just loops back and doesn't save the names, neither the scores

CodePudding user response:

You have a for-loop on scores that adds a new item to the scores list at each iteration. The for-loop will never reach the end of the list because there is always 'one more'.

CodePudding user response:

Alain T.'s answer has already stated the root cause that you experienced. The loop never stops which appears to you as "freezing" since there are no outputs or indicators that you (as a user/developer) see that the loop still runs. So actually nothing freezes here .. it just runs forever.

For that reason I wanted to add a short note how to drill down the problem your own the next times.. Keyword here is clearly: debugging.

Debugging means: "finding out what your code does while being executed"

A very simple but (at least for small programs) quite effective approach is using one or more print() statements. These can be used to display the value of variables, the property of an object or just some statement like print("I am before the loop") to know where execution runs/stops..

A possible would be: (look at the print statements)

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])

Running your program again should print out:

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

and so on... So what you know now is:

  • Everything before the loop at least executed
  • The loop runs forever .

So now it would be time to dig a little deeper inside the loop. Most interesting would be to examine the variable on which the loop exit depends. In your case that is the length of the scores list:

for compare_score in scores:

So the loop runs until there are no more scores to compare left in the scores list.

So it might be a good idea to print() the length of the list to check if and how it decreases until there are no more scores to compare.

So add something like this: Check the two print() statements containing len(scores)

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")

Both are displaying the length of the scores list. The former one just does it a little nicer. There is a lot more to debugging. Many tools like VSCode, Pycharm, etc. support a lot more sophisticated methodologies to step through code, set breakpoints, inspect objects and variables .. But for small ans simple projects and when the focus is on learning, instant feedback and repeating. At least to my mind. Print() debugging gives you a lot of insight in a very easy and simple manner.

Oh, and if you read until here:

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