Чтобы исправить бесконечный цикл, избегайте повторного открытия файла при каждом вызове на print_et_list()
Попробуйте это (я переименовал function
в file_handle
, чтобы быть немного более четким при чтении кода)
import sys
def print_et_list (file_handle):
answer_list = []
#Question
question = file_handle.readline()
print question
#Choices
one = file_handle.readline()
two = file_handle.readline()
answer_list.append(one)
answer_list.append (two)
for item in answer_list:
print item
#Solution
solution = None
try:
result = file_handle.readline()
result.replace("\n","")
solution = int(result)
except:
print "There's an error in the answer"
##for the blank line
file_handle.readline()
return question, one, two, solution
##file_handle for prompting the user for an answer, comparing an answer, keeping score and printing score.
def hey_user (solution, score=0):
user_answer = int(raw_input ("Enter what you think the answer is, user.\n"))
print "you answered '%s'"%user_answer
if user_answer == solution:
print "You've got it right!"
score += 1
elif user_answer == 0:
sys.exit()
else:
print "You've got it wrong."
return score
def main ():
file_handle = open ("modStory.txt","r")
question, one, two, solution = print_et_list(file_handle)
scoresofar = hey_user(solution)
print "\nYour score is now", scoresofar
while question:
question, one, two, solution = print_et_list(file_handle)
if question:
scoresofar = hey_user(solution, scoresofar)
print "\nYour score is now", scoresofar
file_handle.close()
main ()
raw_input ("Hit enter to exit.")
Это не идеальная версия, но, похоже, работает;)