微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TypeError:只能将str而不是“ int”连接到str,但是当尝试将var更改为str时,出现了另一个错误

如何解决TypeError:只能将str而不是“ int”连接到str,但是当尝试将var更改为str时,出现了另一个错误

因此,我正在尝试为Python中的俄罗斯方块制作一个PPS(每秒放置的零件)计算器。但是,当我尝试分割时间和碎片时,会出现此错误

TypeError: can only concatenate str (not "int") to str

网站上的一些人说“将int转换为str!”之类的内容。 但是当我这样做时,会出现 this 错误

TypeError: unsupported operand type(s) for /: 'str' and 'str'

代码如下:

pieces = input("How many pieces did you place? ")
time = input("How long did you play for? (In Seconds Please!) ")
PPS = " "


def answer():
    PPS = round(str(time) / str(pieces))
    print("Your PPS is: " + PPS)


answer()

请尽快提供帮助,谢谢!

解决方法

可以对数字执行数学运算,并在字符串上进行串联... 您可以尝试以下方法:

def answer():
    PPS = round(int(time) / int(pieces))
    print("Your PPS is: " + str(PPS))

或:

def answer():
    PPS = round(int(time) / int(pieces))
    print("Your PPS is: {0}".format(PPS))

或者您可以将int包裹在input周围 因此它变成pieces = int(input("How many pieces did you place? ")),与time类似 然后在函数内部:

pieces = int(input("How many pieces did you place? "))
time = int(input("How long did you play for? (In Seconds Please!) "))
PPS = ""

def answer():
    PPS = round(time / pieces)
    print("Your PPS is: " + str(PPS))
,

我已经解决了问题。我需要改变的问题 TimePiecesfloat(time)float(pieces)即可。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。