为什么会出现错误“无法将int对象隐式转换为str”

2024-05-16 08:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这只是我的程序的一小部分,所以我只是一块一块地创建它。所以我现在要做的就是让我的程序在输入小于或等于10的情况下给ast1加一个“*”,但是我一直得到一个错误“不能隐式地将int对象转换成str”,而且我也不知道为什么。有人能扔我一根骨头来帮我吗。你知道吗

ast1 = "*"
count = 0

while (True):
    n = int(input("Enter a number between 0 - 100:"))
    if n<=10:
        ast1 = ast1 + 1 #This is where the error is occuring


print(ast1)

编辑的代码:当用户输入“完成”时,我如何让这个程序终止/中断?你知道吗

ast1 = ""
ast2 = ""
ast3 = ""
ast4 = ""


while (True):
    n = int(input("Enter a number between 0 - 100:"))
    if n>=0 and n<=25:
        ast1 = ast1 + "*"
    elif n>25 and n<=50:
        ast2 = ast2 + "*"
    elif n>50 and n<=75:
        ast3 = ast3 + "*"
    elif n>75 and n<=100:
        ast4 = ast4 + "*"
    else:break


print(ast1)
print(ast2)
print(ast3)
print(ast4)

Tags: and程序truenumberinputbetweenintprint
3条回答

因为ast1变量包含*,它被定义为string,而1被定义为integer,所以string加integer连接是不可能的。不能对字符串变量和整数变量进行算术运算。你知道吗

I'm trying to do right now is have my program add a "*" to ast1 if the input is less than or equal to 10

你应该这样做:

ast1 = ast1 + '*'

或者,甚至更短:

ast1 += '*'

如果要使用数学运算符,可以使用乘法器:

# will set ast1 to '**'
ast1 = ast1 * 2

但是第二次你要做乘法,当然,你会得到'****'。不知道这是不是你想要的。你知道吗

你可以直接将星号相乘,就像'*' * 3。它将返回'***'。你知道吗

这个

ast1 = ast1 + 1 #This is where the error is occuring

应该是

ast1 = ast1 + str(1)

在Python中,尤其是在字符串操作中,数字需要显式类型转换为字符串。你知道吗

相关问题 更多 >