简体   繁体   中英

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

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_line function which is then called in the next_block function.

I have tried converting both score and points to an integer which doesn't seem to work.

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

points is a string, because you read this from the file:

points = next_line(the_file)

but score is an integer:

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() :

score += int(points)

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 points object is of type integer, whilst your score is 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')

you are trying to add int and str

score = int(score)
score += points

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM