2016-11-05 2 views
-3

파일에서 읽을 때 나는이 오류를 받고 있어요 :형식 오류 : 지원되지 않는 피연산자 유형 (들) + = 대한 '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.") 

답변

1

points은 문자열입니다 :

points = next_line(the_file) 

하지만 score 정수 : 여기

는 프로그램 코드의

score = 0 

당신 정수에 문자열을 추가 할 수 없습니다. 이 파일에서 읽은 값이 정수를 나타내는 경우, 당신은 int()를 사용하여, 먼저 변환해야합니다

score += int(points) 
+0

덕분에,이 일했다. 왜 함수가 작동하지 않는 정수로 함수 호출을 변환하려고했습니다. – kieranw

0

오류 메시지를 수신, 그것은 종종 문제에 대해 유용한 정보를 밝힐 수 ...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'은 기본적으로 += 연산자 (+으로 단순화 될 수 있음)와받은 두 가지 유형의 객체 (귀하의 경우에는 문자열 및 정수)를 사용할 수 없다고 말합니다.
points 객체의 형식은 정수이며, score은 문자열입니다 (파일에서 읽은 이후).

이 문제를 해결하려면 문자열을 정수로 변환해야합니다.이 정수를 다른 정수와 더할 수 있도록하려면 int() 함수를 사용하면됩니다.

TL; DR :! 당신이 int을 추가하려고 type('1')

+0

설명 주셔서 감사합니다, 그것은 지금 의미가 있습니다 :) – kieranw

0

type(1) = 및 str

score = int(score) 
score += points 
관련 문제