无法将“int”对象隐式转换为str

2024-04-25 11:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个由随机问题组成的数学测验。测验结束时会显示一个分数,然后我尝试将结果和学生姓名放入一个文件中,然后会弹出一条错误消息:

import random
import time

counter = 0

#I think the problem is around here?
score = int("0")
count = 0

function = ['+', 'x', '-']

# Introducing quiz
print('Welcome To The Arithmetic Quiz!')
time.sleep(2)

name = input('Please enter you name. ')
time.sleep(1)

print('Thanks', name, '. Let\'s Get Started!')
time.sleep(1)

while counter < 10:
questions.
    firstnumber = random.randint(0, 12)
    secondnumber = random.randint(0, 6)
    operator = random.choice(function)

    question = print(firstnumber, operator, secondnumber, '=')

    userAnswer = input('Answer:')

    if operator == '+':
        count = firstnumber + secondnumber
        if count == int(userAnswer):
            print('Correct!')
            score = score+1
        else:
            print('Incorrect')
    elif operator== 'x':
        count = firstnumber*secondnumber
        if count == int (userAnswer):
            print('Correct!')
            score = score+1
        else:
            print('Incorrect')
    elif operator== '-':
        count = firstnumber - secondnumber
        if count == int(userAnswer):
            print('Correct!')
            score = score + 1
        else:
            print('Incorrect')
    counter += 1

    print("Your quiz is over!")
    print("You scored", score, "/10")
    what_class = input("Please enter your class number: ")
    classe = open("what_class.txt", "wt")
    type(classe)
    classe.write(name + score)
    classe.close()

然后出现以下错误消息:

Traceback (most recent call last):
  File "C:/4/gcse maths.py", line 61, in <module>
    classe.write(name+score)
TypeError: Can't convert 'int' object to str implicitly

Tags: nameiftimecountcountersleeprandomoperator
3条回答

对,因为字符串和int不能连接,所以这样做是没有意义的!

假设我们有:

oneString = 'one'
twoInt = 2

那是什么类型

oneString + twoInt

是吗?

是一个str,还是一个int

因此,可以通过str()内置函数将int显式解析为str

result = oneString + str(twoInt)
print(result)
# printed result is 'one2'

但要注意这种情况的倒数,即将oneString转换为int。你会得到一个ValueError。请参见以下内容:

result = int(oneString) + twoInt
print(result)
# raises a ValueError since 'one' can not be converted to an int

代码无法将字符串“name”添加到数字“score”中。尝试使用函数str()将分数转换为字符串(您可能也希望在其中添加一个空格)。看看这个问题Converting integer to string in Python?

写入文件时,只能写入字符串,不能写入整数。要解决这个问题,需要将整数转换为字符串。这可以使用str()函数完成-更多信息here

classe.write(name + str(score) + "\n")

\n用于新行,否则每个名称和分数将位于同一行。

相关问题 更多 >