how to add an ordered score table with names
<pre><code>import random
number_correct = 0

def scorer():
    global number_correct
    if attempt == answer:
        print("Correct.")
        number_correct = number_correct + 1
    else: 
        print('Incorrect. The correct answer is ' + str(answer))

name = input("Enter your name: ")

for i in range(10):
    num1 = random.randrange(1, 100)
    num2 = random.randrange(1, 100)
    operation = random.choice(["*", "-", "+", "%", "//"])
    print("What is the answer?", num1, operation, num2)
    attempt = int(input(" "))
    if operation == "+":
        answer = num1 + num2
        scorer()
    elif operation == "-":
        answer = num1 - num2
        scorer()
    elif operation == "*":
        answer = num1 * num2
        scorer()
    elif operation == "%":
        answer = num1 % num2
        scorer()
    elif operation == "//":
        answer = num1 // num2
        scorer()
print(name + ", you got " + str(number_correct) + " out of 10.")
</code></pre>

<p>I have made the quiz above and now want it to make a high-score table with the names and scores next to each other from highest to smallest.</p>

<p>I am trying to sort the scores first and this is what I have come up with:</p>

<pre><code>scores = []
names = []
file = open("scores.txt","a")
addedline = number_correct
file.write('%d' % addedline) 
file.close()
file = open("scores.txt","r")
for eachline in file:
    scores.append(eachline)
    x = scores.sort()
    print(x)
file.close()
</code></pre>

<p>I don't think this works and am not sure how i will combine the names and scores at the end (making sure that the correct score is next to the correct name). Please help.
thanks</p>

<p>I would recommend storing the names and scores as a csv, then you could read the names with the scores and then sort with the score as a key.</p>

<pre><code>with open("scores.txt", "a") as file:
    file.write("%s, %s\n" % (name, number_correct))
with open("scores.txt", "r") as file:
    data = [line.split(", ") for line in file.read().split("\n")]

data = sorted(data, key = lambda x: -int(x[1]))

print("\n".join(["%s\t%s" % (i[0], i[1]) for i in data]))
</code></pre>

python