【问题标题】:TypeError: unsupported operand type(s) for +: 'int' and 'str'类型错误:+ 不支持的操作数类型:“int”和“str”
【发布时间】:2013-04-17 02:00:10
【问题描述】:

此代码用于问答游戏,每次有人答对一题,每个问题都会获得一定的积分。我不知道如何让代码在每个正确答案后将分数加在一起。每次我尝试不同的东西时,总是会收到此错误消息。

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.")

【问题讨论】:

  • 请提供完整的堆栈跟踪

标签: python-3.x


【解决方案1】:

您将点作为字符串输出,并且需要在使用它进行任何计算之前将它们转换为 int,最好尽快:

points = int(next_line(the_file))

在 next_block 中应该可以解决问题。 此外,您不是在分数中添加分数,而是在替换它。

total = sum(points + points)
score = total

应该是

score += points

将“点”添加到“分数”。

【讨论】:

    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2017-05-27
    • 2013-10-12
    • 2014-08-10
    相关资源
    最近更新 更多