-5

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later. I still don't know how to save the last 3 scores I have tried this so far:

#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
    name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name    
    if name==(""):#checks if the name entered is blank
        print ("please enter a valid name")#prints an error mesage if the user did not enter their name
        main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
    class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
    try:#This function will try to run the following but will ignore any errors
        class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
        if class_no not in range(1, 3):
            print("Please enter the correct class - either 1,2 or 3!")
            class_name(yourName)
    except:
        print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
        class_name(yourName)#Branches back to the class choice

    score=0#sets the score to zero
    #add in class no. checking
    for count in range (1,11):#Starts the loop
        numbers=[random.randint (1,11),
                 random.randint (1,11)]#generates the random numbers for the program 
        operator=random.choice(["x","-","+"])#generates the random operator
        if operator=="x":#checks if the generated is an "x" 
            solution =numbers[0]*numbers[1]#the program works out the answer 
            question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
        elif operator=="+":#checks if the generated operator is an "+"
            solution=numbers[0]+numbers[1]#the program works out the answer 
            question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
        elif operator=="-":
            solution=numbers[0]-numbers[1]#the program works out the answer
            question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user

        try:
            answer = int(input(question))

            if answer == solution:#checks if the users answer equals the correct answer
                score += 1 #if the answer is correct the program adds one to the score
                print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
            else:
                print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message 
        except:
            print("Your answer is not correct")#if anything else is inputted output the following

    if score >=5:
        print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
    else:
        print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))

    name_score.append(yourName)
    name_score.append(score)

    if class_no ==1:
        myclass1.write("{0}\n".format(name_score))
    if class_no ==2:
        myclass2.write("{0}\n".format(name_score))
    if class_no ==3:
        myclass3.write("{0}\n".format(name_score))

    myclass1.close()
    myclass2.close()
    myclass3.close()
Taryn
  • 242,637
  • 56
  • 362
  • 405
Jake Murray
  • 1
  • 1
  • 8

1 Answers1

0

Your program seems to be working just fine now.

I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.

Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.

# Task 2
import random

def main():
    your_name = ""
    while your_name == "":
        your_name = input("Please enter your name:")  # asks the user for their name and then stores it in the variable name

    class_no = ""
    while class_no not in ["1", "2", "3"]:
        class_no = input("Please enter your class - 1, 2 or 3:")  # Asks the user for an input

    score = 0

    for _ in range(10):
        number1 = random.randint(1, 11)
        number2 = random.randint(1, 11)
        operator = random.choice("*-+")

        question = ("{0} {1} {2}".format(number1,operator,number2))

        solution = eval(question)

        answer = input(question+" = ")

        if answer == str(solution):
            score += 1
            print("Correct! Your score is, ", score)
        else:
            print("Your answer is not correct")


    print("Congratulations {0}, you have finished your ten questions!".format(your_name))
    if score >= 5:
        print("Your total score is {0} which is over half.".format(score))
    else:
        print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))

    with open("class%s.txt" % class_no, "a") as my_class:
        my_class.write("{0}\n".format([your_name, score]))

main()
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62
  • Thanks a lot do you know how to read the last 3 scores from a student from the txt file as that is what I'm stuck on ;) – Jake Murray Jan 28 '15 at 08:06
  • you have to open the file using the read mode, `with open("class1.txt", "r") as my_class:` and the loop over my_class `for line in my_class: print line.strip` – f.rodrigues Jan 28 '15 at 16:24
  • But since you are already storing `name:score` I would recomend that you check `JSON` or `Pickle`, it's saves Python datatypes strucutures that don't need to be parsed. – f.rodrigues Jan 28 '15 at 16:25
  • Can you explain pickle as I tried using that but couldn't understand it – Jake Murray Jan 28 '15 at 16:26
  • I just tried `for line in my_class: print line.strip` but i am getting an error missing parentheses in call to print – Jake Murray Jan 28 '15 at 16:45
  • I could explain pickle, but that seems like another question worth, even it probably been asked. Sorry about the print , just replace for `print(line.strip())`, I'm using Python 2.7 – f.rodrigues Jan 28 '15 at 16:53
  • That's ok and i will just try and explain my task so you understand. I need to read the scores and sort In alphabetical order with each students highest score for the test, By the highest score, highest to lowest?,By the average score, highest to lowest? Each of those sorts is for each student individually – Jake Murray Jan 28 '15 at 16:58
  • You better using a class and than sorting the instances. – f.rodrigues Jan 28 '15 at 17:17
  • `with open("class%s.txt" % class_no, "r") as my_class: Student=input("What student's scores do you want to find?") for line in my_class: if student in line: scores.append(line)` – Jake Murray Jan 28 '15 at 17:19
  • As I said, you better using pickle or json, check this answer: http://stackoverflow.com/a/7502013/3014930 – f.rodrigues Jan 28 '15 at 17:30
  • If I use pickle will i have to pickle dump to the file in the previous program? – Jake Murray Jan 28 '15 at 17:33
  • Yes you dump when you want to save, and you load when you want to use the data. – f.rodrigues Jan 28 '15 at 18:27