为什么我收到错误 "Can't convert 'int' object to str implicitly"
Why am I get the error "Can't convert 'int' object to str implicitly"
这只是我的程序的一小部分,所以我只是一点一点地创建它。所以我现在要做的就是让我的程序在输入小于或等于 10 时向 ast1 添加一个“*”,但我一直收到错误 "Can't convert 'int' object to str implicitly" 并且我不完全确定为什么.有人可以在这里给我一根骨头来帮助我吗?
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)
已编辑代码:当用户输入 "done" 时,如何让这个程序进入 terminate/break?
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)
因为 ast1
变量包含 *
,它被定义为字符串,而 1 被定义为整数,所以字符串加整数连接是不可能的。将无法对字符串变量和整数变量进行算术运算。
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
。它将 return '***'
.
这个
ast1 = ast1 + 1 #This is where the error is occuring
应该是
ast1 = ast1 + str(1)
在 Python 中,数字需要明确地类型转换为字符串,尤其是在字符串操作中。
这只是我的程序的一小部分,所以我只是一点一点地创建它。所以我现在要做的就是让我的程序在输入小于或等于 10 时向 ast1 添加一个“*”,但我一直收到错误 "Can't convert 'int' object to str implicitly" 并且我不完全确定为什么.有人可以在这里给我一根骨头来帮助我吗?
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)
已编辑代码:当用户输入 "done" 时,如何让这个程序进入 terminate/break?
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)
因为 ast1
变量包含 *
,它被定义为字符串,而 1 被定义为整数,所以字符串加整数连接是不可能的。将无法对字符串变量和整数变量进行算术运算。
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
。它将 return '***'
.
这个
ast1 = ast1 + 1 #This is where the error is occuring
应该是
ast1 = ast1 + str(1)
在 Python 中,数字需要明确地类型转换为字符串,尤其是在字符串操作中。