2013-04-17 109 views
-3

此代码适用于琐事游戏,并且每当有人获得正确的问题时,他们都会被授予一定数量的每个问题点数。我不知道如何让代码在每个正确的答案后添加点。每次我尝试一些不同的东西时,我总是会得到这个错误信息。TypeError:不支持的操作数类型为+:'int'和'str'

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) 

    points = next_line(the_file) 

    return category, question, answers, correct, explanation, points 

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_points.txt", "r") 
    title = next_line(trivia_file) 
    welcome(title) 
    score = 0 

    # get first block 
    category, question, answers, correct, explanation, points = 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=" ") 
      total = sum(points + points) 
      score = total 
     else: 
      print("\nWrong.", end=" ") 
     print(explanation) 
     print("Score:", score, "\n\n") 

     points = int(points) 

     # get next block 
     category, question, answers, correct, explanation, points =  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.") 
+1

请提供完整的堆栈跟踪 – hexist

回答

0

你得到点作为一个字符串,并需要他们最好尽快转换为int 前做任何与它的计算,尽可能:

points = int(next_line(the_file)) 

在next_block应该做的伎俩。 另外,您并未将分数添加到分数中,而是将其替换。

total = sum(points + points) 
score = total 

应该

score += points 

加上 '点' 到 '得分'。

+0

非常感谢你! –

相关问题