Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将用户名和最后3个分数保存到文本文件中?_Python - Fatal编程技术网

Python 如何将用户名和最后3个分数保存到文本文件中?

Python 如何将用户名和最后3个分数保存到文本文件中?,python,Python,我需要把最后三个学生的分数和他们的名字写进一个文本文件,以便老师的程序稍后阅读和排序。 我仍然不知道如何保存最后3分 到目前为止,我已经尝试过: #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

我需要把最后三个学生的分数和他们的名字写进一个文本文件,以便老师的程序稍后阅读和排序。 我仍然不知道如何保存最后3分 到目前为止,我已经尝试过:

#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()

你的程序现在似乎运行得很好

我已经根据PEP8的指导原则对代码进行了重新分析,您真的应该让代码更清晰易读

删除了此处不需要的
try/except
块。不要在没有异常的情况下使用
try/except
ValueError,KeyError
…)。另外,使用带有打开(…)的
作为…
而不是
打开/关闭
,它将为您关闭文件

# 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()

它不保存最后3个分数我不知道如何保存最后3个分数谢谢你知道如何从txt文件中读取学生的最后3个分数,因为这是我一直坚持的;)您必须使用读取模式打开文件,
,以open(“class1.txt”,“r”)作为my_class:
和my_class
上的循环作为my_class:print line.strip中的line:print line.strip
感谢您的帮助:),但是由于您已经存储了
name:score
,我建议您检查
JSON
Pickle
,它保存了不需要解析的Python数据类型结构。当我尝试使用它时,您能解释一下pickle,但无法理解它吗