2015-10-24 8 views
0

Здесь у меня есть программа, которая викторирует учеников и сохраняет их оценки для своего учителя. Однако теперь меня попросили сохранить каждого ученика последние три оценки, что означает, что программа должна распознавать имена людей, как бы я это сделал?Как мне распознать имена учеников?

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) 

ответ

0

Вы можете использовать словарь. Ключ будет именем студентов, и значение может быть списком последних 3 баллов. В конце теста вы бы обновить словарь так:

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

В приведенном выше примере, последняя оценка всегда последняя оценка в списке. scoresDict необходимо будет инициализировать как пустой словарь (или прочитать из файла - см. Ниже) для начала. Сначала попробуйте добавить оценку к существующему 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) 

Когда программа закрывается, после обновления оценки Dict, вы откачиваете его обратно на диск:

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

Это было бы более чем подходит для простых нужд. Для более сложных данных или если вы планируете хранить большие объемы данных, вы должны посмотреть на использование базы данных. Python поставляется с модулем SQLite в стандартной библиотеке, которая может быть использована.

+0

Я пробовал это, но говорит, что os и path не определены – user5151709

+0

'os' является модулем в std lib. Вам нужно «импортировать» его, чтобы использовать его. – jramm

+0

Что означает по типу ошибка 'str' не поддерживает буферный интерфейс – user5151709