-2

I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.

My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.

The records currently look like this:

name,score,score,score,score,

etc so they can be split using commas.

I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:

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.")
user
  • 5,370
  • 8
  • 47
  • 75
  • 1
    Open the file, read the lines (for line text) and `if username in line == false` append, else well replace the score – Maximilian Kindshofer Feb 19 '15 at 12:54
  • 2
    OT but I'd strongly recommend you use a function instead of mirroring three times the same code, especially if you are actually learning. – d6bels Feb 19 '15 at 13:07

1 Answers1

0

Here is a beginning.

First, to open a file, you can use with and the open function. (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'

You can use the same kind of logic to write your scores back to the file.

When you have your lines, you may want to use the split function to get the name and scores. (https://docs.python.org/3.3/library/stdtypes.html#str.split)

# For every line, store in a list
scores = []
for score_line in file_content:
    scores.append(score_line.split(','))

There you will have a list of lists for instance [['Kevin', '1', '2', '3'], ['Murphy', '12', '5', '10']] and you can them search into them if the person is already registered, add a score (use .append()) and so on.

This is not a complete solution, but it gives you some insights to get to where you want.
Feel free to try, change and ask other questions if you need to.


While I'm at it, you should really consider using functions and avoid repeating code because readability counts.

You could for instance use the following to print your class scores:

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("")
d6bels
  • 1,432
  • 2
  • 18
  • 30