Python 困惑于为什么我能';不要把字符串加在一起

Python 困惑于为什么我能';不要把字符串加在一起,python,accumulator,Python,Accumulator,我正在尝试编写一个程序,获取用户信息并将其添加到列表中,然后我想合计有多少用户输入,但我做不到。我尝试运行累加器,但得到了TypeError:+:“int”和“str”的操作数类型不受支持 def main(): #total = 0 cel_list = [] another_celeb = 'y' while another_celeb == 'y' or another_celeb == 'Y': celeb = input('Ent

我正在尝试编写一个程序,获取用户信息并将其添加到列表中,然后我想合计有多少用户输入,但我做不到。我尝试运行累加器,但得到了TypeError:+:“int”和“str”的操作数类型不受支持

def main():
    #total = 0

    cel_list = []

    another_celeb = 'y'

    while another_celeb == 'y' or another_celeb == 'Y':

        celeb = input('Enter a favorite celebrity: ')

        cel_list.append(celeb)

        print('Would you like to add another celebrity?')

        another_celeb = input('y = yes, done = no: ')


        print()
    print('These are the celebrities you added to the list:')
    for celeb in cel_list:
        print(celeb)
        #total = total + celeb
        #print('The number of celebrities you have added is:', total)



main() 
这里是不带累加器的输出,但我仍然需要将输入相加。我已经把累加器注释掉了

Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y

Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done

These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>> 
提前感谢您的建议。

总计是一个整数(前面声明为)

正如错误代码所示,您正在尝试用字符串连接整数。这是不允许的。要通过此错误,您可以:

    ## convert total from int to str
    output = str(total) + celeb
    print(" the number of celebrities you have added is', output)
或者更好的是,您可以尝试使用字符串格式

    ##output = str(total) + celeb
    ## using string formatting instead
    print(" the number of celebrities you have added is %s %s', %  (total, celeb))

我希望这对您有用

您可以使用函数获取Python列表中的条目数。因此,只需使用以下方法:

print('These are the celebrities you added to the list:')
for celeb in cel_list:
    print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))

请注意最后两行的缩进减少了—在打印出名人姓名后,只需运行一次即可。

Python是一种动态类型语言。因此,当您键入
total=0
时,变量total将变为整数,即Python根据变量包含的值为变量分配类型

您可以使用
type(variable\u name)
检查python中任何变量的类型

len(对象)返回整数值

for celeb in cel_list:
    print(celeb)

#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)

然后用户输入,您添加的名人数量为:',然后反复迭代。此时输入或输出,然后,您添加的名人数量是:like soEnter a favorite名人:Jen Anniston您想添加另一个名人吗?y=是,完成=否:y输入最喜爱的名人:布拉德·皮特您想添加其他名人吗?y=是,完成=否:y输入最喜爱的名人:吉姆·布朗您想添加其他名人吗?y=是,完成=否:完成这些是您添加到列表中的名人:Jen Anniston您添加的名人数量是:3 Brad Pitt您添加的名人数量是:3 Jim Brown您添加的名人数量是:3@user3818550-那是因为在你问题中的代码中,在for循环中有print语句。在回答中,我在for循环外有print语句。@user3818550-您可以通过减少缩进来结束for循环。@user3818550-很高兴我能提供帮助!
for celeb in cel_list:
    print(celeb)

#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)