提问者:小点点

我一直得到错误“TypeError:只能将str(不是”int“)concantenate为str


目标是创建一个骰子游戏,在游戏中,无论玩家掷出什么,都会加到他们的分数上,除非是6,否则游戏会重置。 我一直得到这个错误,不知道为什么。 我只是普通中等教育证书一年级的学生,所以别把我钉死在十字架上。

    import random
min = 1
max = 6

rollAgain = input('Do you want to roll the dice?\n')
userScore = 0
if rollAgain == "yes" or rollAgain == "Yes":
  newScore = userScore+(random.randint(min, max))
  print('Your score is ' + newScore)
  rollAgainTwice = input('Do you want to roll again?\n')

请帮帮我


共3个答案

匿名用户

不能打印变量的int类型。 为此,您必须使用f字符串或str()函数。 在括号之间,将要更改为字符串的值或变量放入。 您必须将print('Your score is'+newScore)修改为print('Your score is'+str(newScore))

import random
min = 1
max = 6

rollAgain = input('Do you want to roll the dice?\n')
userScore = 0
if rollAgain == "yes" or rollAgain == "Yes":
  newScore = userScore+(random.randint(min, max))
  print('Your score is ' + str(newScore))
  rollAgainTwice = input('Do you want to roll again?\n')

通过使用f字符串,它将以print(F'Your score is{newScore})的方式显示。 在{}之间放置一个要添加到字符串短语中的变量。

匿名用户

尝试将其更改为:

print('Your score is ' + str(newScore))

匿名用户

变量NewScore需要转换为Str,以便使用+运算符:

print('Your score is ' + newScore)
                         ^

将其更改为:

print('Your score is ' + str(newScore))