无法转换' int'隐含地反对str

时间:2015-04-26 19:28:13

标签: 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

3 个答案:

答案 0 :(得分:2)

是的,因为字符串和整数不能连接,所以没有意义!

假设我们有:

oneString = 'one'
twoInt = 2

那是什么类型

oneString + twoInt

str,还是int

因此,您可以int内置语言将str显式解析为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

答案 1 :(得分:0)

代码无法添加字符串&#39; name&#39;数字得分&#39;。尝试使用函数str()将得分转换为字符串(您可能也想在其中添加空格)。看看这个问题Converting integer to string in Python?

答案 2 :(得分:0)

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

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

\n用于换行,否则每个名称和分数都在同一行。