TypeError: =: 'int' 和 'str' 不支持的操作数类型

新手上路,请多包涵

从文件读取时出现此错误:

 line 70 in main: score += points
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

我在文件中取一个整数并将其添加到变量 score 。从文件中读取是在 next_line 函数中完成的,然后在 next_block 函数中调用该函数。

我已经尝试将 scorepoints 转换为一个似乎不起作用的整数。

这是程序代码:

 # 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)

    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.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= " ")
            score += points
        else:
            print("\nWrong.", end= " ")
        print(explanation)
        print("Score:", score, "\n\n")

        # get next block
        category, question, answers, correct, explanation, points = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("Your final score is", score)

main()
input("\n\nPress the enter key to exit.")

原文由 kieranw 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 415
2 个回答

points 是一个字符串,因为您是从文件中读取的:

 points = next_line(the_file)

但是 score 是一个整数:

 score = 0

您不能将字符串添加到整数。如果您从文件中读取的值表示整数,则需要先使用 int() 对其进行转换:

 score += int(points)

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 3.0 许可协议

您正在尝试添加 intstr

 score = int(score)
score += points

原文由 Vivek Srinivasan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题