bravestar
Июнь 11, 2018 19:04:12
Всем доброго времени суток!
Имеется вот такой код:
# Trivia Challenge
# Trivia game that reads a plain text file
import sys
def open_file(file_name, mode):
“”“Open a file.”“”
try:
the_file = open(file_name, mode)
except IOError as e:
print(“Unable to open the file”, file_name, “Ending program.\n”, e)
input(“\n\nPress the enter key to exit.”)
sys.exit()
else:
return the_file
def next_line(the_file):
“”“Return next line from the trivia file, formatted.”“”
line = the_file.readline()
line = line.replace(“/”, “\n”)
return line
def next_block(the_file):
“”“Return the next block of data from the trivia 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
explanation = next_line(the_file)
return category, question, answers, correct, explanation
def welcome(title):
“”“Welcome the player and get his/her name.”“”
print(“\t\tWelcome to Trivia Challenge!\n”)
print(“\t\t”, title, “\n”)
def main():
trivia_file = open_file(“trivia.txt”, “r”)
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print(“\t”, i + 1, “-”, answers)
# get answer
answer = input(“What's your answer?: ”)
# check answer
if answer == correct:
print(“\nRight!”, end=“ ”)
score += 1
else:
print(“\nWrong.”, end=“ ”)
print(explanation)
print(“Score:”, score, “\n\n”)
# get next block
category, question, answers, correct, explanation = next_block(trivia_file)
trivia_file.close()
print(“That was the last question!”)
print(“You're final score is”, score)
main()
input(“\n\nPress the enter key to exit.”)
и данные, которые берет из текстового файла.
Мне не понятна вот эта строка кода:
correct = next_line(the_file)
if correct:
correct = correct
Ведь correct эта переменная, а не список?
PEHDOM
Июнь 11, 2018 22:28:12
bravestar
Мне не понятна вот эта строка кода:
correct = next_line(the_file)
if correct:
correct = correct
Ведь correct эта переменная, а не список?
в correct передается строка из файла, пустая строка вида '' возвращает False , непустая True.
соотвествнно условие “if correct:” проверяет не пустая ли строка.
А вот следующая строка “correct = correct” абсолютно бессмыслена, если конечно там нету квадратных скобок котоые сьел движок сайта.
rami
Июнь 11, 2018 23:00:00
PEHDOM
А вот следующая строка “correct = correct” абсолютно бессмыслена, если конечно там нету квадратных скобок котоые сьел движок сайта.
Движок, таки, съел, в оригинале у ТС должно быть:
if correct:
correct = correct[0]
Это потому, что из файла строки считываются с символом конца строки. По минимуму можно поправить функцию:
def next_line(the_file):
'''Return next line from the trivia file, formatted.'''
line = the_file.readline().strip('\n') #убрать переводы строк
line = line.replace('/', '\n')
return line
bravestar
Июнь 12, 2018 02:53:59
Извиняюсь, впервые задавал вопрос на сайте. Да движок съел квадратные скобки

В оригинале, код выглядит вот так:
# Trivia Challenge
# Trivia game that reads a plain text file
import sys
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia 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):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("You're final score is", score)
main()
input("\n\nPress the enter key to exit.")
bravestar
Июнь 12, 2018 03:27:29
rami
И все же все равно непонятно.
correct = next_line(the_file)
if correct:
correct = correct[0]
Итак, переменная correct считывает и присваивает следующую строку кода.
Если correct непустая строка:
переменной correct присваивается первый элемент списка correct.
Откуда взялся список correct и зачем его присваивать значению переменной correct?
rami
Июнь 12, 2018 07:17:27
bravestar
Если correct непустая строка:
переменной correct присваивается первый элемент списка correct.
Откуда взялся список correct и зачем его присваивать значению переменной correct?
correct не список, а строка (состоящая из символов).
Если correct не пустая строка, то она содержит два элемента — цифру правильного ответа и перевод строки, нам нужен первый элемент, а не оба.
Этот “хитрый манёвр” работает правильно только если номер правильного ответа однозначный, если двузначный — выдаст ошибку.
Лучше:
if correct:
correct = correct[0]
заменить на:
correct = correct.strip('\n')
PEHDOM
Июнь 12, 2018 09:45:55
bravestar
Откуда взялся список correct и зачем его присваивать значению переменной correct?
вы не поверите но строки поддерживают доступ по индексу и срезы.
>>> st = 'python'
>>> st[0]
'p'
>>> st[0:3]
'pyt'
>>> st[-1]
'n'
>>> st[0::2]
'pto'
>>> st[:]
'python'
>>>
подробнее:
http://ps.readthedocs.io/ru/latest/strings.htmlостальное вам уже обьяснили..
bravestar
Июнь 12, 2018 18:14:07
rami
correct не список, а строка (состоящая из символов).
Если correct не пустая строка, то она содержит два элемента — цифру правильного ответа и перевод строки, нам нужен первый элемент, а не оба.
Спасибо большое!!!! Ваш ответ это то что мне было нужно. Теперь я понял.