Чтобы отобразить 3 последних результата, вы должны сохранить их в файле, а затем прочитать их.
Я бы сохранил данные в файле JSON как словарь, как этот
пользователей. json
{
"Scott": {
"password": "heyall",
"scores": []
},
"alexander": {
"password": "heyall",
"scores": []
},
"Lisa1": {
"password": "heyall",
"scores": []
}
}
Кстати: аналогично, я бы сохранял вопросы в JSON файле
данных. json
[
{
"question": "True or False? CPU stands for Central Processing Unit?",
"answer": "True"
},
{
"question": "True or False? On average magnetic tape is more expensive than an Optical disk.",
"answer": "False"
},
{
"question": "True or False? A Binary Search looks for items in an ordered list.",
"answer": "True"
},
{
"question": "True or False? Extended ASCII covers all major languages.",
"answer": "False"
},
{
"question": "True or False? Procedures always must take parameters.",
"answer": "False"
},
{
"question": "True or False? In flow charts input/output is represented in a diamond.",
"answer": "False"
},
{
"question": "True or False? The world's largest WAN is the cloud.",
"answer": "False"
},
{
"question": "True or False? POP3 is used to retrieve emails from a server.",
"answer": "True"
},
{
"question": "True or False? In hexidecimal the binary number 01001110 equals 4E.",
"answer": "False"
},
{
"question": "True or False? An interpreter is only required once to run the program.",
"answer": "False"
}
]
И тогда я могу прочитать его при запуске
with open('users.json') as fh:
all_users = json.load(fh)
with open('data.json') as fh:
data = json.load(fh)
Обновить после викторины
all_users[username]['scores'].append(score)
И сохранить
with open('users.json', 'w') as fh:
json.dump(all_users, fh)
И тогда я могу отобразить 3 последних результата (или больше) с использованием [-3:]
print('Three last scores:', all_users[username]['scores'][-3:])
Полный код (с другими изменениями)
Я использую random.shuffle(data)
для изменения порядка в данных, а затем могу использовать обычный for
-l oop и код проще.
import sys
import random
import json
# read data
with open('users.json') as fh:
all_users = json.load(fh)
with open('data.json') as fh:
data = json.load(fh)
# login
username = input("Login: ")
password = input("Password: ")
if username not in all_users.keys():
print("Username not found")
sys.exit("Username incorrect!")
if password != all_users[username]['password']:
print("Password incorrect!")
sys.exit("Password incorrect")
# change questions order
random.shuffle(data)
# ask questions
score = 0
for item in data:
question = item['question']
answer = item['answer']
user_answer = input(question)
if user_answer == answer:
print("Correct!")
score += 1
else:
print("Incorrect!")
# keep new score
all_users[username]['scores'].append(score)
# display result
if 10 >= score >= 8:
print("Well done sport! You got", score ,"I'm so proud of you!")
elif score == 7:
print("Good job you got", score ,"! It's not so bad! I'm proud!")
elif 6 >= score >= 1:
print("Try again. You only got", score,"/10")
elif score == 0:
print("You're a disgrace! You only got", score,"/10!!!")
print('Three last scores:', all_users[username]['scores'][-3:])
# save it
with open('users.json', 'w') as fh:
json.dump(all_users, fh)