2

Помогите найти ошибку в коде:

import sys
def open_file(file, mode):
    """Открывает файл"""
    try:
        the_file = open(file, mode, encoding='utf-8')
    except IOError as e:
        print("невозможно открыть файл:", file, "программа будет завершена", e )
        input("нажмите Enter to exit")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """ возвращает в отформатированном виде очередную строку игрового файла """
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """ возвращает очередной блог данных из игрового файла """
    category = next_line(the_file)
    question = next_line(the_file)
    answers = []
    for i in range(4):
        answers.append(next_line(the_file))
        correct = next_line(the_file)
        if correct:
            correct = correct[0]
            explanation = next_line(the_file)
    return category, question, answers, correct, explanation
def welcome(title):
    print("Добро пожаловать!  ")
    print("\t\t, title, \n")

def main():
    trivia_file = open_file("file.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0
2
  • 2
    уточните вопрос или предоставьте тестовые данные. По return category, question, answers, correct, explanation - не ясно почему именно так решили делать.
    – Igor
    19 июл 2017 в 22:15
  • Ответил в этой теме: ru.stackoverflow.com/questions/694320
    – user254763
    20 июл 2017 в 23:44

2 ответа 2

1

Ты вызываешь функцию main() после того, как выводишь результат, поэтому функция print не распознаёт переменную score. А также, если ты назначаешь переменной значение в функции, то оно будет локальным, а надо сделать его глобальным (global score). У меня нету файла твоей игры, но у тебя также есть ошибка с отступами. Цикл for i in range(4) должен только записывать данные в файл, а у тебя он 4 раза достаёт другие данные. Вот так должен выглядеть твой год

import sys
def open_file(file, mode):
    """открывает фаил"""
    try:
        the_file = open(file, mode, encoding='utf-8')
    except IOError as e:
        print("не возможно открыть фаил", file, "программа будет завершена", e )
        input("нажмите Enter to exit")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    category = next_line(the_file)
    question = next_line(the_file)
    answers = []
    for i in range(4):
        answers.append(next_line(the_file))
    correct = next_line(the_file)
    if correct:
        correct = correct[0]
        explanation = next_line(the_file)
    return category, question, answers, correct, explanation
def welcome(title):
    print("Добро пожаловать!  ")
    print("\t\t, title, \n")

def main():
    global score
    trivia_file = open_file("file.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

    category, question, answers, correct, explanation = next_block(trivia_file)
    while category:
        print(category)
        print(question)
        for i in range(4):
            print("\t", i+1, "-", answers[1])
        answer = input("ваш ответ: ")
        if answer == correct:
            print("\nYes", end=" ")
            score += 1
        else:
            print("\nнет", end=" ")
            print(explanation)
            print("Счет: ", score, "\n\n")
        category, question, answers, correct, explanation = next_block(trivia_file)
        trivia_file.close()
main()
print("это был последний вопрос")
print("на вашем счету: ", score)

input()

0

correct и explanation создаются 4 раза внутри цикла for i in range(4). Соответствунно return вернет последнее из них

for i in range(4):
    answers.append(next_line(the_file))
    correct = next_line(the_file)
    if correct:
        correct = correct[0]
        explanation = next_line(the_file)
return category, question, answers, correct, explanation
  • структура файла file.txt плоха, ошибка может быть в ней. Лучше хранить все, например в dict, а читать и записывать его в файл с помощью pickle

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.