Devdit
 

Python หาผลรวมใน List ด้วยคำสั่ง sum

17.2K

คำสั่ง sum ภาษา Python ใช้สำหรับหาผลรวมของข้อมูลภายใน List ทั้งหมด โดยข้อมูลใน List ที่จะใช้คำสั่ง sum ได้ต้องเป็นตัวแปรชนิดตัวเลขเท่านั้น สามารถเขียนโค้ดได้ดังนี้

 

ตัวอย่าง

number = [50,70,30,40,60]

print(sum(number))

ผลลัพธ์

250

 

กรณีใช้คำสั่ง sum กับ List ที่ไม่ใช่ข้อมูลชนิดตัวเลขจะขึ้น Error ว่า TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> a = ['a','b']
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ