【问题标题】:TypeError: unsupported operand type(s) for +=: 'int' and 'str'类型错误:+= 不支持的操作数类型:“int”和“str”
【发布时间】:2016-11-06 01:44:22
【问题描述】:

读取文件时出现此错误:

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

【问题讨论】:

    标签: python python-3.4 typeerror


    【解决方案1】:

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

    points = next_line(the_file)
    

    但是score 是一个整数:

    score = 0
    

    您不能将字符串添加到整数。如果你从文件中读取的值代表一个整数,你需要先转换它,使用int()

    score += int(points)
    

    【讨论】:

    • 谢谢,这行得通。我试图将函数调用转换为整数,这就是它不起作用的原因
    【解决方案2】:

    您正在尝试添加intstr

    score = int(score)
    score += points
    

    【讨论】:

      【解决方案3】:

      当收到错误消息时,它通常可以揭示有关问题的有用信息...
      TypeError: unsupported operand type(s) for +=: 'int' and 'str' 基本上是说不能使用+= 运算符(可以简化为+ ) 与它收到的两种不同类型的对象(字符串和整数,在你的情况下)。
      您的 points 对象是整数类型,而您的 score 是字符串(因为它是从文件中读取的)。

      要更正此问题,您必须将字符串转换为整数,以便将其与另一个整数相加,这可以使用 int() 函数来完成。

      tl;博士:type(1)!=type('1')

      【讨论】:

      • 谢谢你的解释,现在说得通了:)
      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2017-05-27
      • 2013-10-12
      • 2014-08-10
      相关资源
      最近更新 更多