如何显示用户参加测验的最后三个分数

2024-10-01 07:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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是密码输入的缩写


Tags: oryoufalsetrueonlyifcountquestions
3条回答

我稍微修改了代码。输入_file.txt时使用的方法,该文件包含名称、分数和新分数,将附加到此文件中

输入文件:Input_file.txt

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

亚历山大| 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

要显示最后3个分数,您必须将分数保存在文件中,然后再读取它们

我会像这样将数据作为字典保存在JSON文件中

users.json

{
    "Scott": {
        "password": "heyall",
        "scores": []
    },
    "alexander": {
        "password": "heyall",
        "scores": []
    },
    "Lisa1": {
        "password": "heyall",
        "scores": []
    }
}

顺便说一句:类似的方式,我会把问题保存在JSON文件中

data.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-循环,代码更简单

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)

你的代码有几处错误,但既然这不是问题所在,我就不在这里讨论了

下次,试着让你的问题更简洁。你想具体完成什么?据我所知,你只是想按用户存储一些文本

如何使用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 = []

相关问题 更多 >