Python 类型错误:+= 不支持的操作数类型:'int' 和 'str'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40441209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:32:28  来源:igfitidea点击:

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

pythonpython-3.4typeerror

提问by kieranw

I'm getting this error when reading from a file:

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

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

I'm taking an integer in the file and adding it to the variable score. The reading from the file is done in the next_linefunction which is then called in the next_blockfunction.

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

I have tried converting both scoreand pointsto an integer which doesn't seem to work.

我试过将score和都转换points为一个似乎不起作用的整数。

Here's the program code:

这是程序代码:

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

回答by Martijn Pieters

pointsis a string, because you read this from the file:

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

points = next_line(the_file)

but scoreis an integer:

但是score是一个整数:

score = 0

You can't add a string to an integer. If the value you read from the file represents an integer number, you need to convert it first, using int():

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

score += int(points)

回答by maze88

When receiving an error message, it can often reveal useful information about a problem...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'is basically saying that one can't use the +=operator (which can be simplified to +) with the two different types of objects it received (string and integer, in your case).
Your pointsobject is of type integer, whilst your scoreis a string (since it was read from a file).

To correct this, you must convert the string to an integer, allowing you to sum it with the other integer, this can be done using the int()function.

tl;dr: type(1)!=type('1')

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

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

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

回答by Vivek Srinivasan

you are trying to add intand str

您正在尝试添加intstr

score = int(score)
score += points