来自用户输入字符串的累计总数
问题描述:
我试图编写一个函数,该函数将用户输入的整数序列作为输入并返回累计总数。例如,如果输入是1 7 2 9
,则该函数应打印1 8 10 19
。我的程序无法正常工作。下面是代码:来自用户输入字符串的累计总数
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
这里是输出:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我不知道这是什么错误表示。请帮我调试我的代码。
答
此代码将工作。记住:阅读代码并了解它是如何工作的。
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
有代码中有两处新的东西:
-
x.split(y)
分裂x
成更小的字符串列表,使用y
作为分隔符。例如,"1 7 2 9".split(" ")
返回[“1”,“7”,“2”,“9”]。 -
total += int(v)
比较复杂。我将分解更多:-
split()
函数给了我们一串字符串,但我们需要数字。int()
函数(除其他外)将字符串转换为数字。这样,我们可以添加它。 -
+=
运算符表示“增加”。写作x += y
与写作x = x + y
相同,但输入时间较短。
-
有一个与代码另一个问题:你说你需要的功能,但是这是不是一个函数。函数可能是这样的:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
,并使用它:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
但程序会工作得很好。
答
累加总数
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)
看看你的错误信息:'类型错误:不支持的操作数类型(S)为+: '诠释' 和“str''。这意味着什么是一个问题,你可以采取哪些步骤来理解和解决它? – hexafraction
你可以请你的问题重新说一下吗?就像这样,它听起来有点像[gimme teh codez](http://meta.stackoverflow.com/questions/288133/is-using-stack-overflow-for-gimme-codez-questions-encouraged)问题,这些网站不鼓励这些内容。但是,高质量的问题会让您获得声望,从而为您提供更多的网站权限。 – wizzwizz4
不要让downvotes不鼓励你,你可以改善这个问题。只需点击[编辑](http://stackoverflow.com/posts/35827634/edit)按钮即可。 – wizzwizz4