import random

scores = []
excellent = 0
good = 0
fail = 0

for i in range(500):
    score = random.randint(0, 100)
    scores.append(score)
    if score >= 90:
        print(score, '优秀')
        excellent += 1
    elif score >= 60:
        print(score, '良好')
        good += 1
    else:
        print(score, '不及格')
        fail += 1

print('优秀:', excellent, '占比:', excellent/500)
print('良好:', good, '占比:', good/500)
print('不及格:', fail, '占比:', fail/500)

该代码首先使用 random.randint(0, 100) 生成 500 个随机分数,并存入 scores 列表中。然后,代码遍历分数列表,根据分数大小进行评级,并统计各等级的数量。最后,代码输出各等级的数量和占比。

示例输出:

...  # 随机生成的500个分数
95 优秀
87 良好
...  # 其他分数
优秀: 105 占比: 0.21
良好: 250 占比: 0.5
不及格: 145 占比: 0.29

代码说明:

  • random.randint(0, 100) 生成一个 0 到 100 之间的随机整数,并赋值给 score 变量。
  • scores.append(score)score 添加到 scores 列表中。
  • 使用 if-elif-else 语句判断分数等级,并进行相应的计数操作。
  • 最后使用 print() 函数输出各等级的数量和占比。
Python 生成随机分数并评级统计

原文地址: https://www.cveoy.top/t/topic/f1Sz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录