python经常要用到各种求和,例如列表求和,元素求和,利用函数求和,将这些方法总结发给大家!
1.python两个数的求和函数
def sum_2_num(num1,num2):
result =num1 + num2
return result
#必须在执行行输入,函数命名后必须调用,调用sum_2_num(),或者 print()
#sum_2_num(10,20)
sum_2_num(10,20)
print(sum_2_num(20,30))
2.关于python列表内求和
def sum_of_list(param_list):
total = 0
for item in param_list:
total += item
return total
list1 = [1,2,3,4]
list2 = [2,3,4,5]
print(f"sum of {list1}=",sum_of_list(list1))
print(f"sum of {list2}=",sum_of_list(list2))
#print(f"sum of {list1}=",sum(list1))
#内置函数sum可以直接替代求和函数
3.1-100数字求和
#coding=utf-8
sum=0
for i in range(1,101):
sum=sum + i #sum+=i
print(sum)
#
4.利用内置函数sum求列表内偶数和
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sum = sum([num for num in numbers if num % 2 == 0])
print(even_sum) # 输出结果为 30
#num for num in numbers是利用了列表推导式进行计算。
标签:python,list,sum,list1,求和,num,初学者,print From: https://blog.csdn.net/knight0113/article/details/137609289