通过迭代参数来找到总和时遇到问题

huangapple go评论55阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月5日 18:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定