Форум сайта python.su
0
Всем доброго времени суток!
Имеется вот такой код:
# 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 эта переменная, а не список?
Прикреплённый файлы:
trivia.txt (1,5 KБ)
Офлайн
294
bravestarв correct передается строка из файла, пустая строка вида '' возвращает False , непустая True.
Мне не понятна вот эта строка кода:
correct = next_line(the_file)
if correct:
correct = correct
Ведь correct эта переменная, а не список?
[code python][/code]
Офлайн
72
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
Офлайн
0
Извиняюсь, впервые задавал вопрос на сайте. Да движок съел квадратные скобки
В оригинале, код выглядит вот так:
# 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.")
Офлайн
0
ramiИ все же все равно непонятно.
correct = next_line(the_file) if correct: correct = correct[0]
Офлайн
72
bravestarcorrect не список, а строка (состоящая из символов).
Если correct непустая строка:
переменной correct присваивается первый элемент списка correct.
Откуда взялся список correct и зачем его присваивать значению переменной correct?
if correct: correct = correct[0]
correct = correct.strip('\n')
Офлайн
294
bravestarвы не поверите но строки поддерживают доступ по индексу и срезы.
Откуда взялся список correct и зачем его присваивать значению переменной correct?
>>> st = 'python' >>> st[0] 'p' >>> st[0:3] 'pyt' >>> st[-1] 'n' >>> st[0::2] 'pto' >>> st[:] 'python' >>>
[code python][/code]
Отредактировано PEHDOM (Июнь 12, 2018 09:46:08)
Офлайн
0
ramiСпасибо большое!!!! Ваш ответ это то что мне было нужно. Теперь я понял.
correct не список, а строка (состоящая из символов).
Если correct не пустая строка, то она содержит два элемента — цифру правильного ответа и перевод строки, нам нужен первый элемент, а не оба.
Офлайн