关于python:无法将”int”对象隐式转换为str

Can't convert 'int' object to str implicitly

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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()

然后出现此错误消息:

1
2
3
4
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


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

假设我们有:

1
2
oneString = 'one'
twoInt = 2

那是什么类型的呢

1
oneString + twoInt

它是一个str,还是一个int

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

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

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

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

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

1
2
classe.write(name + str(score) +"
"
)


是一个新行,否则每一个名字和分数都将在同一行上。


代码无法将字符串"name"添加到数字"score"。尝试使用函数str()将分数转换为字符串(您可能还需要在其中添加一个空格)。看看这个在python中将整数转换成字符串的问题吧?