2016-09-15 5 views
0
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.") 

私は上のクイズを作っていますが、名前とスコアが高い順に並んだハイスコア表を作成したいと考えています。オーダースコアテーブルを名前付きで追加する方法

私が最初にスコアをソートするためにしようとしています、これは私が出ているものです:

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

私はこの作品とは思いませんし、私が名前とスコアを結合しますかわからないん最後に正しいスコアが正しい名前の横にあることを確認してください。助けてください。 ありがとう

答えて

0

名前とスコアをcsvとして保存することをお勧めします。次にスコアで名前を読み取ってスコアをキーとして並べ替えることができます。

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

どのように私はcsvとしてそれらを保存しますか? – user6834144

+0

これは無効な構文を使い続けています。 pls help – user6834144

+0

ああ、私はPython 3を使っているようですが、これはPython 2.7で書かれています。 – Quack

0

あなたのテキストファイルがどのくらい正確に見えているのかよく分かりませんが、同じスコアを2回以上持たない限り辞書を使うことをお勧めします。このように、あなたはあなたのスコアをキーにすることができ、値は名前であり、辞書はキーの順に自動的にソートされます。

関連する問題