1、实现1-100的所有的和
# 方法1: sum = 0 for i in range(1,101): sum += i print(sum) # 方法2: num1 = int(input('请输入起始数字')) num2 = int(input('请输入末尾数字')) sum = (num1 + num2) * num2 / 2 print(int(sum))
2、实现1-500所有奇数的和
sum = 0 for i in range(1,501): _,result = divmod(i,2) if not result: sum += i print(sum)
3、实现1!+2!+3!+4!...+20!的结果
sum = 0 result = 0 for i in range(1,21): if i == 1: sum = i else: for j in range(1,i+1): if j == 1: result = 1 else: result *= j sum += result print(sum)
4、对指定的list进行排序[2,32,43,453,54,6,576,5,7,6,8,78,7,89]
# sorted()拷贝排序 li = [2,32,43,453,54,6,576,5,7,6,8,78,7,89] new_li= sorted(li) print(li) # 原列表不变 print(new_li) # sort()是原地排序 li = [2,32,43,453,54,6,576,5,7,6,8,78,7,89] li.sort() print(li) # 直接对原列表进行修改