在Fi中查找和添加记录

2024-09-30 01:22:31 发布

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

我对python相当陌生,我需要做一个程序来询问10个问题,将分数保存到一个文件中,并允许某人从文件中读取分数。在

我的问题:我需要检查完成测试的人是否已经在文件中有记录,如果有,我需要将他们的分数添加到记录的末尾。在

当前的记录如下:

name,score,score,score,score,

等等,这样它们就可以用逗号分开了。在

我也在寻找最简单的答案,而不是最有效的答案。 另外,如果你能对代码进行注释,这会使它更容易。以下是我目前为止的代码:

from random import randint
import time
import csv
looping = 0
correctAnswers = 0
userNameValid = False
classNoValid = False
loop = 0

while loop == 0:
    print("-------Maths Quiz-------")
    print("1. Play A Game")
    print("2. See Scores from previous games")
    print("3. Exit")
    playOrScores = input("Which option would you like to do? ")
    #^ Menu to find out which operation user would like to do. ^



if playOrScores == "1":

    while userNameValid == False:
        userName = input("What is your name? ")
        if userName.isnumeric() == True:
            print("That username is invalid")
            userNameValid = False
        elif userName.isspace() == True:
            print("That username is invalid")
            userNameValid = False
        elif userName == "":
            print("Please input a username")
            userNameValid = False
        else:
            userNameValid = True
            #^Menu to validate users name input^
    while classNoValid == False:
        print("Which class are you in? ")
        print("1. Class 1a")
        print("2. Class 1b")
        classNo = input("3. Class 1c ")
        if classNo.isnumeric() == False:
            print("That input is invalid")
            classNoValid = False
        elif classNo.isspace() == True:
            print("That input is invalid")
            classNoValid = False
        elif classNo == "":
            print("Please input a class")
            classNoValid = False
        else:
            classNoValid = True
    #^menu to see which class the student is in and validate input ^

    while looping < 10:                     #Allow the program to loop
        randomNumber1 = randint(1,10)
        randomNumber2 = randint(1,10)
        signNumber = randint(1,3)
        if signNumber == 1:
            correctAnswer = randomNumber1 + randomNumber2
            userAnswer = input("What is " + str(randomNumber1) + " + " + str(randomNumber2) + "?")
            if int(userAnswer) == correctAnswer:
                print("Correct!")
                correctAnswers += 1
            else:
                print("Oh, sorry, the correct answer was " + str(correctAnswer))
        elif signNumber == 2:
            correctAnswer = randomNumber1 - randomNumber2
            userAnswer = input("What is " + str(randomNumber1) + " - " + str(randomNumber2) + "?")
            if int(userAnswer) == correctAnswer:
                print("Correct!")
                correctAnswers += 1
            else:
                print("Oh, sorry, the correct answer was " + str(correctAnswer))
        elif signNumber == 3:
            correctAnswer = randomNumber1 * randomNumber2
            userAnswer = input("What is " + str(randomNumber1) + " x " + str(randomNumber2) + "?") 
            if int(userAnswer) == correctAnswer:
                print("Correct!")
                correctAnswers += 1
            else:
                print("Oh, sorry, the correct answer was " + str(correctAnswer))
        looping += 1
    print("Well done " + userName + " Your final score was " + str(correctAnswers) + "!")
    print("")
    print("")

    if classNo == "1":
        class1 = open("Class1Scores.txt", "a+")
        #Opens a file in the name "Class1Scores"
        newRecord = userName+ "," + str(correctAnswers) + "," + "\n"
        #Creates a string containing the user's name and score, seperated by commas and with a new line at the end.
        class1.write(newRecord)
        #Writes this string to the file
        class1.close()
        #Closes the file

    elif classNo == "2":
        class2 = open("Class2Scores.txt", "a+")
        newRecord = userName+ "," + str(correctAnswers) + "," + "\n"
        class2.write(newRecord)
        class2.close()

    elif classNo == "3":

        class3 = open("Class3Scores.txt", "a+")
        newRecord = userName+ "," + str(correctAnswers) + "," + "\n"
        class3.write(newRecord)
        class3.close()


elif playOrScores == "2":
    while classNoValid == False:
        print("Which class do you want to read? ")
        print("1. Class 1a")
        print("2. Class 1b")
        classNo = input("3. Class 1c ")
        if classNo.isnumeric() == False:
            print("That input is invalid")
            classNoValid = False
        elif classNo.isspace() == True:
            print("That input is invalid")
            classNoValid = False
        elif classNo == "":
            print("Please input a class")
            classNoValid = False
        else:
            classNoValid = True
            #^ Menu to validate class input, shown in detail earlier ^

    if classNo == "1":
        #Uses this option if teacher wants to see scores for class 1
        class1 = open("Class1Scores.txt", "r")
        #Opens file for class 1
        class1Array = class1.readlines()
        #Reads all lines and stores them in the variable "class1Array"
        noRecords1 = len(class1Array)
        #Finds the number of records
        for i in range (0, noRecords1):
            tempArray = class1Array[i].split(",")
            tempArray.remove("\n")
            print(tempArray)
            class1.close()
            #Loops through all records, removing the "\n" and printing it

        print("")
        print("")

    #^^ This code is mirrored for class 2 and class 3. ^^


    elif classNo == "2":

        class2 = open("Class2Scores.txt", "r")    
        class2Array = class2.readlines()

        noRecords2 = len(class2Array)

        for i in range (0, noRecords2):

            tempArray = class2Array[i].split(",")
            tempArray.remove("\n")
            print(tempArray)
            class2.close()

        print("")
        print("")

    elif classNo == "3":

        class3 = open("Class3Scores.txt", "r")    
        class3Array = class3.readlines()

        noRecords3 = len(class3Array)

        for i in range (0, noRecords3):

            tempArray = class3Array[i].split(",")
            tempArray.remove("\n")
            print(tempArray)
            class3.close()

        print("")
        print("")

elif playOrScores == "3":
    loop = 1
    quit()

else:
    print("That is an invalid entry, please enter a number between 1 and 3.")

Tags: thetofalseinputifisclassprint
1条回答
网友
1楼 · 发布于 2024-09-30 01:22:31

这是一个开始。在

首先,要打开一个文件,可以使用withopen函数。(https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files

# Open the file
with open("scores.txt", 'r') as scorefile:
   # Read all lines
   content = scorefile.readlines()
   # Note that you can also combine .read().splitlines() to get rid of the '\n'

你可以用同样的逻辑把你的分数写回文件。在

当您有了行之后,您可能需要使用split函数来获取名称和分数。(https://docs.python.org/3.3/library/stdtypes.html#str.split

^{pr2}$

在那里你会有一个列表列表,比如[['Kevin', '1', '2', '3'], ['Murphy', '12', '5', '10']],如果这个人已经注册,你可以用它们来搜索,添加一个分数(使用.append())等等。在

这不是一个完整的解决方案,但它给了你一些见解,让你达到你想要的目的。
如果需要,请随时尝试、更改和询问其他问题。


在我做这个的时候,你应该考虑使用函数,避免重复代码,因为readability counts。在

例如,您可以使用以下课程打印分数:

def print_class(class_number):
    """ Prints the class 'class_number' scores"""
    # Open the file safely
    with open("Class{}Scores.txt".format(class_number), 'r') as classfile:
        classArray = classfile.readlines()
        noRecords = len(classArray)

        for i in range(noRecords):
            tempArray = classArray[i].split(",")
            tempArray.remove("\n")
            print(tempArray)

        print("")
        print("")

相关问题 更多 >

    热门问题