1

我正在尝试编写一个程序来获取用户信息并将其添加到列表中,然后我想总计有多少用户输入,但我做不到。我试过运行一个累加器,但我得到 TypeError: unsupported operand type(s) for +: 'int' and '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
>>> 

在此先感谢您的任何建议。

4

3 回答 3

2

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

    total = 0

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

    ## 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))

我希望这对你有用

于 2014-07-09T01:57:54.590 回答
0

您可以使用该len()函数获取 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))

请注意最后两行的缩进减少 - 您只需在打印完名人姓名后运行它们一次。

于 2014-07-09T01:58:00.987 回答
0

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

您可以使用 . 检查 python 中任何变量的类型type(variable_name)

len(object)返回数值。

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)
于 2014-07-09T01:58:03.183 回答