我正在尝试编写一个程序来获取用户信息并将其添加到列表中,然后我想计算总共有多少用户输入,但我做不到。我尝试运行累加器,但收到 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
>>>
预先感谢您的任何建议。
最佳答案
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))
我希望这对你有用
关于python - 困惑为什么我不能将字符串添加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644212/