当我在列表中添加数字并打印它们时,它只会添加第一个数字
When i add numbers in a list and print them it only adds the first number
当我 print(sum(n))
时,我得到 7
而不是列表元素的总和 32
。我做错了什么?
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
n = [7, 12, 5, 8]
print (sum(n))
让我们一步一步来解释:
def sum(numbers):
total = 0
for number in numbers:
total += number
#If you return here, you wont sum the rest, just the first
return total # Return must go outside the for loop, because it breaks the execution
n = [7, 12, 5, 8]
print (sum(n))
您的总和会立即返回,您无需等待列表循环。
如果您的 return
语句在 for
循环中,那么它将 return 恰好迭代一次后的总数,因此 total
的值将是循环中的第一个元素:在本例中为 7
。您应该将 return 语句放在循环之后,以便计算整个总数:
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
n = [7, 12, 5, 8]
print(sum(n))
但是,sum()
已经是 Python 中的内置函数,因此您只需将代码简化为以下内容:
n = [7, 12, 5, 8]
print(sum(n))
其中任何一个都将打印 32
。
当我 print(sum(n))
时,我得到 7
而不是列表元素的总和 32
。我做错了什么?
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
n = [7, 12, 5, 8]
print (sum(n))
让我们一步一步来解释:
def sum(numbers):
total = 0
for number in numbers:
total += number
#If you return here, you wont sum the rest, just the first
return total # Return must go outside the for loop, because it breaks the execution
n = [7, 12, 5, 8]
print (sum(n))
您的总和会立即返回,您无需等待列表循环。
如果您的 return
语句在 for
循环中,那么它将 return 恰好迭代一次后的总数,因此 total
的值将是循环中的第一个元素:在本例中为 7
。您应该将 return 语句放在循环之后,以便计算整个总数:
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
n = [7, 12, 5, 8]
print(sum(n))
但是,sum()
已经是 Python 中的内置函数,因此您只需将代码简化为以下内容:
n = [7, 12, 5, 8]
print(sum(n))
其中任何一个都将打印 32
。