一. 代码实现: 计算1到100之间, 所有的奇数之和
result =
for i in range(, ):
result += i
print(result)
二. 代码实现: 接收用户输入数字, 求出从0至这个数字的累加和;
num_str = input("请输入一个数字(>=1): ")
num = int(num_str) # 可以使用try...except...以及判定语句进行容错处理
result = # 保存最终结果
expression = "" # 记录表达式
for i in range(, num + ):
result += i
expression += " + {}".format(i)
else:
expression += " = {}".format(result)
print(expression)
三. 将以下学生姓名和分数组成的列表, 转换成字典形式
stu_list = ["小王", , "小强", , "小华", ] # 原始数据
stu_dic = {} # 结果字典
# 没隔一个位置, 取两个数据, 组成一个键值对
for idx in range(, len(stu_list), ):
name, score = stu_list[idx: idx + ]
stu_dic[name] = score
print(stu_dic)
四. 代码实现: 将以上的学生分数替换成级别
stu_list = ["小王", , "小强", , "小华", ]
stu_dic = {}
stu_list_len = len(stu_list)
for idx in range(, stu_list_len, ):
name, score = stu_list[idx: idx + ]
if score >= :
level = "A"
elif score >= :
level = "B"
elif score >= :
level = "C"
else:
level = "D"
stu_dic[name] = level
print(stu_dic)
五. 代码实现: 完善以上案例, 求出所有学生的总分以及平均分
stu_list = ["小王", , "小强", , "小华", ]
stu_dic = {}
stu_list_len = len(stu_list)
score_count = # 用来记录分数
score_avg = # 用来记录平均分数
for idx in range(, stu_list_len, ):
name, score = stu_list[idx: idx + ]
score_count += score
if score >= :
level = "A"
elif score >= :
level = "B"
elif score >= :
level = "C"
else:
level = "D"
stu_dic[name] = level
else:
score_avg = score_count / (stu_list_len // 2)
print(stu_dic)
print("总分:{},平均分:{}".format(score_count, score_avg))