
[英]TypeError: unsupported operand type(s) for <<: 'str' and 'int'
[英]TypeError: unsupported operand type(s) for +=: 'int' and 'str'
從文件讀取時出現此錯誤:
line 70 in main: score += points
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
我在文件中取一個整數,並將其添加到變量score
。 從文件讀取是在next_line
函數中完成的,然后在next_block
函數中調用。
我嘗試將score
和points
都轉換為似乎不起作用的整數。
這是程序代碼:
# 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
是一個字符串,因為您是從文件中讀取的:
points = next_line(the_file)
但score
是整數:
score = 0
您不能將字符串添加到整數。 如果從文件中讀取的值表示整數,則需要先使用int()
對其進行轉換:
score += int(points)
收到錯誤消息時,它通常可以顯示有關問題的有用信息...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
基本上是說不能對接收到的兩種不同類型的對象使用+=
運算符(可以簡化為+
)字符串和整數(在您的情況下)。
您的points
對象是整數類型,而您的score
是一個字符串(因為它是從文件中讀取的)。
若要更正此問題,您必須將字符串轉換為整數,並允許將其與其他整數求和,這可以使用int()
函數完成。
tl; dr: type(1)
!= type('1')
您正在嘗試添加int
和str
score = int(score)
score += points
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.