我正在尝试编写一个获取用户信息并将其添加到列表中的程序,然后我想总计有多少用户输入,但我无法做到。我试过运行一个累加器,但是我得到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
>>>
提前感谢任何建议。
答案 0 :(得分: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))
我希望这对你有用
答案 1 :(得分: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))
请注意最后两行的缩进缩小 - 在完成名人姓名的打印后,您只需要运行一次。
答案 2 :(得分:0)
Python是一种动态类型语言。因此,当您键入total = 0
时,变量total变为整数,即Python根据变量包含的值为变量赋值。
您可以使用type(variable_name)
检查python中任何变量的类型。
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)