英文:
Having a problem finding the sum by iterating through args
问题
抱歉,这听起来像一个愚蠢和显而易见的问题,我是新手,目前正在做一个教程,我在教程的args部分,但由于某种原因它无法遍历元组以求和,它只显示第一个索引的值,我不知道我做错了什么,请帮忙,我正在使用Pycharm和Python版本3.11.1,如果这有关系的话。
def add(*numbersum):
sum = 0
for i in numbersum:
sum += i
return sum
print(add(0, 559, 499, 2))
我回到教程去仔细检查,但由于某种原因它对我不起作用,它应该给我所有参数的总和,但它没有。
英文:
noob here, sorry if this sounds like a dumb and obvious question, I'm currently doing a tutorial and I'm in the args section of the tutorial and for some reason it fails to iterate through the tuple in order to sum up the numbers as it keeps on displaying only the value of the first index, I don't know what I'm doing wrong, please help, I'm using Pycharm and version 3.11.1 of python if that has anything to do with it
def add (*numbersum):
sum = 0
for i in numbersum:
sum += i
return sum
print(add(0,559,499,2))
I went back to the tutorial to double check and for some reason it just doesn't work for me, it's supposed to give me the sum of all arguments but it isn't
答案1
得分: 2
I think the "return sum" is double indented.
Try to un-indent it once.
英文:
I think the "return sum" is double indented.
Try to un-indent it once
答案2
得分: 1
请注意,sum
是一个内置函数。您应避免使用相同的命名空间。
使用 sum
的示例:
def add(*numbers):
return sum(numbers)
因此,在实践中,最好直接使用 sum
,例如 sum([0, 559, 499, 2])
。
英文:
Mind that sum
is a built-in function. You should avoid using the same namespace.
def add(*numbers):
result = 0
for n in numbers:
result += n
return result
Using the built-in sum
:
def add(*numbers):
return sum(numbers)
So, in practice, better to use sum
directly with sum([0,559,499,2])
答案3
得分: 0
代码中的问题是return sum
语句放在for
循环内部,而应该放在外部。
函数错误地只返回了numbersum
参数中第一个数字的总和。为了纠正这个问题,需要将return sum
语句移到循环外部,以允许函数正确计算并返回所有数字的总和。
def add(*numbersum):
sum = 0
for i in numbersum:
print(i)
sum += i
return sum
print(add(0,559,499,2))
英文:
The bug in the given code is due to the placement of the return sum
statement inside the for
loop, where it should be placed outside.
Function mistakenly returns the sum of only the first number in the numbersum
argument. To rectify this issue, the return sum
statement needs to be moved outside the loop, allowing the function to accurately calculate and return the total sum of all the numbers
def add(*numbersum):
sum = 0
for i in numbersum:
print(i)
sum += i
return sum
print(add(0,559,499,2))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论