2015-02-12 77 views
0

这只是我的程序的一小部分,所以我只是一件件地创建它。所以我现在要做的就是让我的程序向ast1添加一个“*”,如果输入小于或等于10,但我总是收到错误“无法将int'对象隐式转换为str”我不完全确定为什么。有人可以在这里把我的骨头扔给我,帮助我。为什么我得到错误“无法将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) 

回答

0

我想现在做的是有我的程序添加一个“*”来AST1如果输入小于或等于10

你应该那样做,那么:

ast1 = ast1 + '*' 

或者更短:

ast1 += '*' 

如果你想使用数学运算符,你可以使用MULT iplier:

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

但你会做乘法,当然第二次,你就会有​​。不知道这是你想要的。

虽然你可以直接乘以星号 - 如'*' * 3。它将返回'***'

+0

不,这不是我想要的,尽管您确实给了我更多的知识。我为我的作业做的是创建一个程序,它将输入0-100之间的任意数字,直到所输入的字符串是“done”,然后从那里我将打印每个数字的星号数量[ 0,25](25,50](50,75)(75,100),但我喜欢在小部分中完成作业。 – HawkeyeNate 2015-02-12 05:13:01

0

由于ast1变量包含*其被定义为串和1被定义为整数,从而字符串加上整数级联将是不可能的。对字符串变量和整数变量进行算术运算是不可能的。

+0

因此,如果我想添加一个“*”到ast1所有输入都是<= 10我需要创建另一个变量来将ast1乘以输入<= 10的次数n? – HawkeyeNate 2015-02-12 05:06:04

+0

您的ast1变量包含字符串'*'。将int'1'转换为像'ast1 + str(1)'这样的字符串# – 2015-02-12 05:07:00

0

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

应该

ast1 = ast1 + str(1) 

数字需要明确类型强制转换为字符串在Python中,尤其是在字符串操作。

相关问题