TypeError: can only concatenate str (not "int") to str but when trying to change var's to str, I get a different error

TypeError: can only concatenate str (not "int") to str but when trying to change var's to str, I get a different error

所以,我正在尝试为 Python 中的俄罗斯方块制作一个 PPS(每秒放置的棋子数)计算器。但是,当我尝试划分时间和片段时出现此错误:

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

网站上有些人说“将 int 转换为 str!” 但是当我这样做时,我得到 this error:

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) 并且有效。