簡體   English   中英

如何使程序識別學生姓名?

[英]How do I make my program recognize students names?

在這里,我有一個程序可以測驗學生並保存分數以供老師查看。 但是,現在我被要求保存每個學生的最后三個分數,這意味着該程序必須識別人們的名字,我該怎么做?

import random
import sys

def get_input_or_quit(prompt, quit="Q"):
    prompt += " (Press '{}' to exit) : ".format(quit)
    val = input(prompt).strip()
    if val.upper() == quit:
        sys.exit("Goodbye")
    return val

def prompt_bool(prompt):
    while True:
        val = get_input_or_quit(prompt).lower()

        if val == 'yes':
          return True
        elif val == 'no':
          return False
        else:
         print ("Invalid input '{}', please try again".format(val))


def prompt_int_small(prompt='', choices=(1,2)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

def prompt_int_big(prompt='', choices=(1,2,3)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

role = prompt_int_small("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")
if role == 1:
    score=0
    name=input("What is your name?")
    print ("Alright",name,"welcome to your maths quiz."
            " Remember to round all answers to 5 decimal places.")
    level_of_difficulty = prompt_int_big("What level of difficulty are you working at?\n"
                                 "Press 1 for low, 2 for intermediate "
                                    "or 3 for high\n")


    if level_of_difficulty == 3:
        ops = ['+', '-', '*', '/']
    else:
        ops = ['+', '-', '*']

    for question_num in range(1, 11):
        if level_of_difficulty == 1:
            max_number = 10
        else:
            max_number = 20

        number_1 = random.randrange(1, max_number)
        number_2 = random.randrange(1, max_number)

        operation = random.choice(ops)

        maths = round(eval(str(number_1) + operation + str(number_2)),5)
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",number_1,operation,number_2)
        answer = float(input("What is your answer: "))
        if answer == maths:
            print("Correct")
            score = score + 1
        else:
            print ("Incorrect. The actual answer is",maths)

    if score >5:
        print("Well done you scored",score,"out of 10")
    else:
        print("Unfortunately you only scored",score,"out of 10. Better luck next time")


    class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")

    filename = (str(class_number) + "txt")
    with open(filename, 'a') as f:
        f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty) + "\n")
    with open(filename) as f:
        lines = [line for line in f if line.strip()]
        lines.sort()

    if prompt_bool("Do you wish to view previous results for your class"):
        for line in lines:
            print (line)
    else:
        sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
if role == 2:
    class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
    filename = (str(class_number) + "txt")

    f = open(filename, "r")
    lines = [line for line in f if line.strip()]
    lines.sort()
    for line in lines:
        print (line)

您可以使用字典。 關鍵是學生姓名,值可以是最近3個分數的列表。 在測試結束時,您將像這樣更新字典:

try:
     scoresDict[name][2] = score
except KeyError:
     scoresDict[name] = [None, None, score]

在上面的示例中,最新分數始終是列表中的最后分數。 scoresDictscoresDict初始化為空字典(或從文件中讀取-參見下文)。 您首先嘗試將分數添加到現有name ,如果失敗,則在dict中創建一個新條目。

程序關閉后,您將需要保留數據。 您可以使用pickle模塊執行此操作。

程序啟動時,您將嘗試從文件中加載現有數據,或者如果文件不存在,則創建一個新的scoresDict

scoresDict = {}
fpath = os.path.join(os.path.dirname(__file__), "scores.pickle")
if os.path.exists(fpath):
    with open(fpath, "r") as f:
        scoresDict = pickle.load(f)

程序關閉時,更新分數字典后,將其轉儲回磁盤:

with open(fpath, "w") as f:
    pickle.dump(scoresDict, f)

這將更適合簡單的需求。 對於更復雜的數據,或者如果您打算存儲大量數據,則應該考慮使用數據庫。 Python在其標准庫中附帶了一個SQLite模塊,可以使用該模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM