Как показать последние три балла пользователя викторины, которую он прошел - PullRequest
0 голосов
/ 12 июля 2020

Я провел викторину с тремя разными пользователями в Python. Мне нужно сохранить и показать последние три балла, которые пользователь, вошедший в систему, получил за прохождение викторины, и я не знаю, как это сделать.

Вот код, который у меня есть:

import sys   

c2 = 0
Score = 0
CU1 = "Scott"
CU2 = "alexander"
CU3 = "Lisa1"
CP1 = "heyall"
CP2 = "password"
CP3 = "Simpson"
Questions = ["True or False? CPU stands for Central Processing Unit?", "True or False? On average magnetic tape is more expensive than an Optical disk.", "True or False? A Binary Search looks for items in an ordered list.", "True or False? Extended ASCII covers all major languages.",  "True or False? Procedures always must take parameters.", "True or False? In flow charts input/output is represented in a diamond.", "True or False? The world's largest WAN is the cloud.", "True or False? POP3 is used to retrieve emails from a server.", "True or False? In hexidecimal the binary number 01001110 equals 4E.", "True or False? An interpreter is only required once to run the program."]
Answers = ["True", "False", "True", "False", "False", "False", "False", "True", "True", "False"]
uninput = input("Please type in your username to continue:")

if uninput == CU1 or CU2 or CU3:
    Auth = True
else:
    Auth = False

if Auth == False:
    print("Username not found")
    sys.exit("Username incorrect!")
    
    
if Auth == True:
    print("Username found!")
    psinput = input("Please type in your password to continue:")
    
if psinput == CP1 or CP2 or CP3:
    Auth2 = True
else:
    Auth2 = False

if Auth2 == False:
    print("Password incorrect!")
    sys.exit("Password incorrect")

if Auth2 == True:
    import random

if Auth == True and Auth2 == True:
    Count = 1

if CU1 == uninput and CP1 == psinput:
    Count = Count + 1
elif CU2 == uninput and CP2 == psinput:
    Count = Count + 1
elif CU3 == uninput and CP3 == psinput:
    Count = Count + 1
else:
    Count = 0
    sys.exit("No access granted!")

if Count == 2:
    print("Commencing Quiz")
    while len(Questions) > 0:
        Question = random.randint(0, (len(Questions))-1)
        Ans = input(Questions[Question])
        if Ans == Answers[Question]:
            print("Correct!")
            Questions.remove(Questions[Question])
            Answers.remove(Answers[Question])
            Score = Score + 1
            c2 = c2 + 1
        else:
            print("Incorrect!")
            Questions.remove(Questions[Question])
            Score = Score
            c2 = c2 + 1
        
if Score == 10:
    print("Well done sport! You got", Score ,"I'm so proud of you!")
elif Score == 9:
    print("Well done sport! You got", Score ,"I'm so proud of you!")
if 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 Score == 6:
    print("Try again. You only got", Score,"/10")
elif Score == 5:
    print("Try again. You only got", Score,"/10")
elif Score == 4:
    print("Try again. You only got", Score,"/10")
elif Score == 3:
    print("Try again. You only got", Score,"/10")
elif Score == 2:
    print("Try again. You only got", Score,"/10")
elif Score == 1:
    print("Try again. You only got", Score,"/10")
elif Score == 0:
    print("You're a disgrace! You only got", Score,"/10!!!")

uninput - это сокращение от ввода имени пользователя, а psinput - сокращение от ввода пароля, если кому-то интересно.

Ответы [ 3 ]

0 голосов
/ 12 июля 2020

Я немного изменил код. Подход, используемый при наличии input_file.txt, который имеет имена и оценки, и новые оценки будут добавлены к этому файлу.

Входной файл: input_file.txt

Scott|0
Scott|4
Scott|6
alexander|6
alexander|1
alexander|6

alexander | 6

Код

import sys

Score = 0
userDatabase = {"Scott" : "heyall", "alexander" : "password", "Lisa1" : "Simpson"}
Questions = ["True or False? CPU stands for Central Processing Unit?", "True or False? On average magnetic tape is more expensive than an Optical disk.",
             "True or False? A Binary Search looks for items in an ordered list.", "True or False? Extended ASCII covers all major languages.",
             "True or False? Procedures always must take parameters.", "True or False? In flow charts input/output is represented in a diamond.",
             "True or False? The world's largest WAN is the cloud.", "True or False? POP3 is used to retrieve emails from a server.",
             "True or False? In hexidecimal the binary number 01001110 equals 4E.", "True or False? An interpreter is only required once to run the program."]
Answers = ["True", "False", "True", "False", "False", "False", "False", "True", "True", "False"]
uninput = input("Please type in your username to continue:")

# file_object = open('input_file.txt', 'a')
previos_scores = 0
if uninput in userDatabase.keys():
    print("Username found!")
    psinput = input("Please type in your password to continue:")
    if psinput == userDatabase[uninput]:
        print("Successfully logged in.!! \n Answer following questions.")
        for index,element in enumerate(Questions):
            currentAnswer = input(element)
            if currentAnswer.strip() not in ("True", "False"):
                raise Exception("Answer should be either True or False")
            if currentAnswer.__contains__(Answers[index]) :
                Score += 1
        with open("input_file.txt", "a") as file_object:
            file_object.write(uninput + "|"+ str(Score)+"\n")

        with open("input_file.txt", "r") as file_object_prevscores:
            previos_scores = file_object_prevscores.read()
        print("\nPrevious three scores : ", [x.split("|")[1] for x in previos_scores.split("\n")[-4:-2] if x.__contains__(uninput)],
              "\nThe current score received : ", Score)
    else:
        print("Password incorrect!")
        sys.exit("Password incorrect")
else:
    print("Username not found")
    sys.exit("Username incorrect!")

Выход

Please type in your username to continue:alexander
Username found!
Please type in your password to continue:password
Successfully logged in.!! 
 Answer following questions.
True or False? CPU stands for Central Processing Unit?False
True or False? On average magnetic tape is more expensive than an Optical disk.False
True or False? A Binary Search looks for items in an ordered list.False
True or False? Extended ASCII covers all major languages.False
True or False? Procedures always must take parameters.False
True or False? In flow charts input/output is represented in a diamond.False
True or False? The world's largest WAN is the cloud.False
True or False? POP3 is used to retrieve emails from a server.False
True or False? In hexidecimal the binary number 01001110 equals 4E.False
True or False? An interpreter is only required once to run the program.False

Previous scores :  ['1', '6'] 
The current score received :  6
0 голосов
/ 12 июля 2020

Чтобы отобразить 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)
0 голосов
/ 12 июля 2020

В вашем коде есть несколько ошибок, но поскольку вопрос не в этом, я не буду go вдаваться в него.

В следующий раз постарайтесь сделать ваш вопрос более кратким. Чего конкретно вы пытаетесь достичь в sh? Насколько я понимаю, вы просто пытаетесь сохранить какой-то текст для каждого пользователя.

Как сохранить что-то с помощью Python?

В качестве первого шага попробуйте сформулировать что именно вы хотите хранить. Как должна выглядеть переменная ? В этом случае это может быть что-то вроде lastScores = [6, 8, 9].

Теперь мы хотим сохранить и загрузить это. Как вы хотите его сохранить?

  • В базе данных?
  • Просто сохранить его в памяти, когда вы повторно запустите программу?
  • Сохранить все оценки вместе в один myquiz -файл?
  • Сохранять оценки для каждого пользователя в отдельном файле?

Просто чтобы дать вам некоторый код, я предполагаю, что вы хотите сохранить это как один файл для каждого пользователя, как обычный текст, всегда в одну и ту же папку.

Сохранение:

scorefile = open('C:/Path/to/quiz/folder/' + uninput + '_scores.txt', mode = 'w')
scorefile.write(', '.join([str(score) for score in lastScores]))
scorefile.close()

Здесь мы открываем файл C:/Path/to/quiz.folder/Scott_scores.txt для w ритинга.

Так как это текстовый файл, мы преобразуем результаты в строку текста. Каждый элемент lastScores преобразуется в str, а все значения объединяются запятой и пробелом. Итак, мы пишем: 6, 8, 9

Наконец, мы закрываем файл, чтобы другие процессы могли открыть его позже.

Загрузка

Не то чтобы другое:

scorefile = open('C:/Path/to/quiz/folder/' + uninput + '_scores.txt', mode = 'r')
lastScores = [int(score) for score in scorefile.read().split(', ')]
scorefile.close()

Мы открываем файл, на этот раз для r чтения.

Последние оценки получаются при чтении файла с разделением на запятую + пробел. И каждый из элементов преобразуется в int

И мы снова закрываем файл.

Если вы не уверены, что файл уже существует, вы можете изменить его следующим образом:

try:
    scorefile = open('C:/Path/to/quiz/folder/' + uninput + '_scores.txt', mode = 'r')
    lastScores = [int(score) for score in scorefile.read().split(', ')]
    scorefile.close()
except FileNotFoundError:
    lastScores = []
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...