# 1. 统计个数
# 案例: 统计scores中不及格学生的人数
scores = [89, 45, 67, 80, 99, 43, 83, 72, 91, 90, 98, 74, 59, 67]
count = 0 # 定义一个默认值为0的变量来记录个数
for x in scores:
if x < 60:
count += 1
print(count)
print('------------------------------------------------------------------------------------')
# 练习1: 统计1~100中不能被3或者5整除数据的个数
count = 0
for x in range(1, 101):
if x % 3 != 0 or x % 5 != 0:
count += 1
print(count)
print('------------------------------------------------------------------------------------')
# 练习2:统计nums中偶数的个数
nums = [19, 23, 90, 87, 201, 430, 78, 91]
count = 0
for x in nums:
if x % 2 == 0:
count += 1
print(count)
print('------------------------------------------------------------------------------------')
# 练习3:统计nums中个位数小于5的元素的个数
nums = [19, 23, 90, 87, 201, 430, 78, 91]
count = 0
for x in nums:
if x % 10 < 5:
count += 1
print(count)
print('------------------------------------------------------------------------------------')
# 2. 累积求和
# 案例1: 求scores中所有学生的总分
scores = [89, 45, 67, 80, 99, 43, 83, 72, 91, 90, 98, 74, 59, 67]
sum1 = 0 # 定义一个默认值是0的变量来保存最后的和
for x in scores:
sum1 += x
print(sum1)
print('------------------------------------------------------------------------------------')
# 案例2: 求scores中所有及格学生的总分
sum1 = 0
for x in scores:
if x >= 60:
sum1 += x
print(sum1)
print('------------------------------------------------------------------------------------')
# 练习1:求scores中所有及格学生的平均分
scores = [89, 45, 67, 80, 99, 43, 83, 72, 91, 90, 98, 74, 59, 67]
sum1 = 0
count = 0
for x in scores:
if x >= 60:
sum1 += x
count += 1
print('平均分:', round(sum1 / count, 1))
# round(数字, N) - 让数字保留N位小数
print('------------------------------------------------------------------------------------')
# 练习2:求nums中所有数字的个位数的和
nums = [19, 23, 90, 87, 201, 430, 78, 91]
sum1 = 0
for x in nums:
sum1 += x % 10
print(sum1)
print('------------------------------------------------------------------------------------')
# 练习3:求2+4+6+8+...+100的和
sum1 = 0
for x in range(2, 101, 2):
sum1 += x
print(sum1)
print('------------------------------------------------------------------------------------')
# 3. 获取最大值、最小值
# 案例:求scores中所有学生的最高分
scores = [89, 45, 67, 80, 99, 43, 83, 72, 91, 90, 98, 74, 59, 67]
max_score = scores[0] # 假设scores中第一个元素是最大值
for x in scores:
if x > max_score:
max_score = x
print(max_score)
print('------------------------------------------------------------------------------------')
# 练习1: 求nums中最小的数
nums = [19, 23, 90, 87, 201, 430, 8, 91]
min_num = nums[0]
for x in nums:
if x < min_num:
min_num = x
print(min_num)
print('------------------------------------------------------------------------------------')
# 练习2:求nums最大的奇数
nums = [19, 23, 90, 87, 201, 430, 8, 91]
max_num = 0
for x in nums:
if x > max_num and x % 2 == 1:
max_num = x
print(max_num)
Pthon for循环的运用
最新推荐文章于 2024-10-18 00:00:00 发布