python中sum函数的使用方法及实例

编程入门 行业动态 更新时间:2024-10-26 14:39:44

python中sum函数的<a href=https://www.elefans.com/category/jswz/34/1769874.html style=使用方法及实例"/>

python中sum函数的使用方法及实例

列表中的数字总和在任何地方都是必需的。 Python提供了一个内置函数sum(),用于对列表中的数字求和。

用法:

sum(iterable, start)

iterable: iterable can be anything list , tuples or dictionaries ,

but most importantly it should be numbers.

start:this start is added to the sum of

numbers in the iterable.

If start is not given in the syntax , it is assumed to be 0.

可能的两种语法:

sum(a)

a is the list , it adds up all the numbers in the

list a and takes start to be 0, so returning

only the sum of the numbers in the list.

sum(a, start)

this returns the sum of the list + start

以下是sum()的Python实现

# Python code to demonstrate the working of

# sum()

numbers = [1,2,3,4,5,1,4,5]

# start parameter is not provided

Sum = sum(numbers)

print(Sum)

# start = 10

Sum = sum(numbers, 10)

print(Sum)

输出:

25

35

Error and Exceptions

TypeError:如果列表中没有数字,则会引发此错误。

# Python code to demonstrate the exception of

# sum()

arr = ["a"]

# start parameter is not provided

Sum = sum(arr)

print(Sum)

# start = 10

Sum = sum(arr, 10)

print(Sum)

运行时错误:

Traceback (most recent call last):

File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in

Sum = sum(arr)

TypeError:unsupported operand type(s) for +:'int' and 'str'

因此列表应包含数字

实际应用:需要计算总和以进行进一步运算(例如找出数字的平均值)的问题。

# Python code to demonstrate the practical application

# of sum()

numbers = [1,2,3,4,5,1,4,5]

# start = 10

Sum = sum(numbers)

average= Sum/len(numbers)

print average

输出:

3

更多推荐

python中sum函数的使用方法及实例

本文发布于:2023-07-03 03:20:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使用方法   函数   实例   python   sum

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!